pymunk_demo_platformer_05.py Full Listing

pymunk_demo_platformer_05.py
  1"""
  2Example of Pymunk Physics Engine Platformer
  3"""
  4import math
  5from typing import Optional
  6import arcade
  7
  8SCREEN_TITLE = "PyMunk Platformer"
  9
 10# How big are our image tiles?
 11SPRITE_IMAGE_SIZE = 128
 12
 13# Scale sprites up or down
 14SPRITE_SCALING_PLAYER = 0.5
 15SPRITE_SCALING_TILES = 0.5
 16
 17# Scaled sprite size for tiles
 18SPRITE_SIZE = int(SPRITE_IMAGE_SIZE * SPRITE_SCALING_PLAYER)
 19
 20# Size of grid to show on screen, in number of tiles
 21SCREEN_GRID_WIDTH = 25
 22SCREEN_GRID_HEIGHT = 15
 23
 24# Size of screen to show, in pixels
 25SCREEN_WIDTH = SPRITE_SIZE * SCREEN_GRID_WIDTH
 26SCREEN_HEIGHT = SPRITE_SIZE * SCREEN_GRID_HEIGHT
 27
 28# --- Physics forces. Higher number, faster accelerating.
 29
 30# Gravity
 31GRAVITY = 1500
 32
 33# Damping - Amount of speed lost per second
 34DEFAULT_DAMPING = 1.0
 35PLAYER_DAMPING = 0.4
 36
 37# Friction between objects
 38PLAYER_FRICTION = 1.0
 39WALL_FRICTION = 0.7
 40DYNAMIC_ITEM_FRICTION = 0.6
 41
 42# Mass (defaults to 1)
 43PLAYER_MASS = 2.0
 44
 45# Keep player from going too fast
 46PLAYER_MAX_HORIZONTAL_SPEED = 450
 47PLAYER_MAX_VERTICAL_SPEED = 1600
 48
 49class GameWindow(arcade.Window):
 50    """ Main Window """
 51
 52    def __init__(self, width, height, title):
 53        """ Create the variables """
 54
 55        # Init the parent class
 56        super().__init__(width, height, title)
 57
 58        # Player sprite
 59        self.player_sprite: Optional[arcade.Sprite] = None
 60
 61        # Sprite lists we need
 62        self.player_list: Optional[arcade.SpriteList] = None
 63        self.wall_list: Optional[arcade.SpriteList] = None
 64        self.bullet_list: Optional[arcade.SpriteList] = None
 65        self.item_list: Optional[arcade.SpriteList] = None
 66
 67        # Track the current state of what key is pressed
 68        self.left_pressed: bool = False
 69        self.right_pressed: bool = False
 70
 71        # Physics engine
 72        self.physics_engine = Optional[arcade.PymunkPhysicsEngine]
 73
 74        # Set background color
 75        arcade.set_background_color(arcade.color.AMAZON)
 76
 77    def setup(self):
 78        """ Set up everything with the game """
 79
 80        # Create the sprite lists
 81        self.player_list = arcade.SpriteList()
 82        self.bullet_list = arcade.SpriteList()
 83
 84        # Read in the tiled map
 85        map_name = "pymunk_test_map.tmx"
 86        my_map = arcade.tilemap.read_tmx(map_name)
 87
 88        # Read in the map layers
 89        self.wall_list = arcade.tilemap.process_layer(my_map, 'Platforms', SPRITE_SCALING_TILES)
 90        self.item_list = arcade.tilemap.process_layer(my_map, 'Dynamic Items', SPRITE_SCALING_TILES)
 91
 92        # Create player sprite
 93        self.player_sprite = arcade.Sprite(":resources:images/animated_characters/female_person/femalePerson_idle.png",
 94                                           SPRITE_SCALING_PLAYER)
 95        # Set player location
 96        grid_x = 1
 97        grid_y = 1
 98        self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2
 99        self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2
100        # Add to player sprite list
101        self.player_list.append(self.player_sprite)
102
103        # --- Pymunk Physics Engine Setup ---
104
105        # The default damping for every object controls the percent of velocity
106        # the object will keep each second. A value of 1.0 is no speed loss,
107        # 0.9 is 10% per second, 0.1 is 90% per second.
108        # For top-down games, this is basically the friction for moving objects.
109        # For platformers with gravity, this should probably be set to 1.0.
110        # Default value is 1.0 if not specified.
111        damping = DEFAULT_DAMPING
112
113        # Set the gravity. (0, 0) is good for outer space and top-down.
114        gravity = (0, -GRAVITY)
115
116        # Create the physics engine
117        self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping,
118                                                         gravity=gravity)
119
120        # Add the player.
121        # For the player, we set the damping to a lower value, which increases
122        # the damping rate. This prevents the character from traveling too far
123        # after the player lets off the movement keys.
124        # Setting the moment to PymunkPhysicsEngine.MOMENT_INF prevents it from
125        # rotating.
126        # Friction normally goes between 0 (no friction) and 1.0 (high friction)
127        # Friction is between two objects in contact. It is important to remember
128        # in top-down games that friction moving along the 'floor' is controlled
129        # by damping.
130        self.physics_engine.add_sprite(self.player_sprite,
131                                       friction=PLAYER_FRICTION,
132                                       mass=PLAYER_MASS,
133                                       moment=arcade.PymunkPhysicsEngine.MOMENT_INF,
134                                       collision_type="player",
135                                       max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
136                                       max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED)
137
138        # Create the walls.
139        # By setting the body type to PymunkPhysicsEngine.STATIC the walls can't
140        # move.
141        # Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC
142        # PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be
143        # repositioned by code and don't respond to physics forces.
144        # Dynamic is default.
145        self.physics_engine.add_sprite_list(self.wall_list,
146                                            friction=WALL_FRICTION,
147                                            collision_type="wall",
148                                            body_type=arcade.PymunkPhysicsEngine.STATIC)
149
150        # Create the items
151        self.physics_engine.add_sprite_list(self.item_list,
152                                            friction=DYNAMIC_ITEM_FRICTION,
153                                            collision_type="item")
154
155    def on_key_press(self, key, modifiers):
156        """Called whenever a key is pressed. """
157        pass
158
159    def on_key_release(self, key, modifiers):
160        """Called when the user releases a key. """
161        pass
162
163    def on_update(self, delta_time):
164        """ Movement and game logic """
165        self.physics_engine.step()
166
167    def on_draw(self):
168        """ Draw everything """
169        arcade.start_render()
170        self.wall_list.draw()
171        self.bullet_list.draw()
172        self.item_list.draw()
173        self.player_list.draw()
174
175def main():
176    """ Main method """
177    window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
178    window.setup()
179    arcade.run()
180
181
182if __name__ == "__main__":
183    main()