pymunk_demo_platformer_08.py Full Listing#

pymunk_demo_platformer_08.py#
  1"""
  2Example of Pymunk Physics Engine Platformer
  3"""
  4from typing import Optional
  5import arcade
  6
  7SCREEN_TITLE = "PyMunk Platformer"
  8
  9# How big are our image tiles?
 10SPRITE_IMAGE_SIZE = 128
 11
 12# Scale sprites up or down
 13SPRITE_SCALING_PLAYER = 0.5
 14SPRITE_SCALING_TILES = 0.5
 15
 16# Scaled sprite size for tiles
 17SPRITE_SIZE = int(SPRITE_IMAGE_SIZE * SPRITE_SCALING_PLAYER)
 18
 19# Size of grid to show on screen, in number of tiles
 20SCREEN_GRID_WIDTH = 25
 21SCREEN_GRID_HEIGHT = 15
 22
 23# Size of screen to show, in pixels
 24SCREEN_WIDTH = SPRITE_SIZE * SCREEN_GRID_WIDTH
 25SCREEN_HEIGHT = SPRITE_SIZE * SCREEN_GRID_HEIGHT
 26
 27# --- Physics forces. Higher number, faster accelerating.
 28
 29# Gravity
 30GRAVITY = 1500
 31
 32# Damping - Amount of speed lost per second
 33DEFAULT_DAMPING = 1.0
 34PLAYER_DAMPING = 0.4
 35
 36# Friction between objects
 37PLAYER_FRICTION = 1.0
 38WALL_FRICTION = 0.7
 39DYNAMIC_ITEM_FRICTION = 0.6
 40
 41# Mass (defaults to 1)
 42PLAYER_MASS = 2.0
 43
 44# Keep player from going too fast
 45PLAYER_MAX_HORIZONTAL_SPEED = 450
 46PLAYER_MAX_VERTICAL_SPEED = 1600
 47
 48# Force applied while on the ground
 49PLAYER_MOVE_FORCE_ON_GROUND = 8000
 50
 51# Force applied when moving left/right in the air
 52PLAYER_MOVE_FORCE_IN_AIR = 900
 53
 54# Strength of a jump
 55PLAYER_JUMP_IMPULSE = 1800
 56
 57# Close enough to not-moving to have the animation go to idle.
 58DEAD_ZONE = 0.1
 59
 60# Constants used to track if the player is facing left or right
 61RIGHT_FACING = 0
 62LEFT_FACING = 1
 63
 64# How many pixels to move before we change the texture in the walking animation
 65DISTANCE_TO_CHANGE_TEXTURE = 20
 66
 67
 68class PlayerSprite(arcade.Sprite):
 69    """ Player Sprite """
 70    def __init__(self):
 71        """ Init """
 72        # Let parent initialize
 73        super().__init__()
 74
 75        # Set our scale
 76        self.scale = SPRITE_SCALING_PLAYER
 77
 78        # Images from Kenney.nl's Character pack
 79        # main_path = ":resources:images/animated_characters/female_adventurer/femaleAdventurer"
 80        main_path = ":resources:images/animated_characters/female_person/femalePerson"
 81        # main_path = ":resources:images/animated_characters/male_person/malePerson"
 82        # main_path = ":resources:images/animated_characters/male_adventurer/maleAdventurer"
 83        # main_path = ":resources:images/animated_characters/zombie/zombie"
 84        # main_path = ":resources:images/animated_characters/robot/robot"
 85
 86        # Load textures for idle standing
 87        self.idle_texture_pair = arcade.load_texture_pair(f"{main_path}_idle.png")
 88        self.jump_texture_pair = arcade.load_texture_pair(f"{main_path}_jump.png")
 89        self.fall_texture_pair = arcade.load_texture_pair(f"{main_path}_fall.png")
 90
 91        # Load textures for walking
 92        self.walk_textures = []
 93        for i in range(8):
 94            texture = arcade.load_texture_pair(f"{main_path}_walk{i}.png")
 95            self.walk_textures.append(texture)
 96
 97        # Set the initial texture
 98        self.texture = self.idle_texture_pair[0]
 99
100        # Default to face-right
101        self.character_face_direction = RIGHT_FACING
102
103        # Index of our current texture
104        self.cur_texture = 0
105
106        # How far have we traveled horizontally since changing the texture
107        self.x_odometer = 0
108
109    def pymunk_moved(self, physics_engine, dx, dy, d_angle):
110        """ Handle being moved by the pymunk engine """
111        # Figure out if we need to face left or right
112        if dx < -DEAD_ZONE and self.character_face_direction == RIGHT_FACING:
113            self.character_face_direction = LEFT_FACING
114        elif dx > DEAD_ZONE and self.character_face_direction == LEFT_FACING:
115            self.character_face_direction = RIGHT_FACING
116
117        # Are we on the ground?
118        is_on_ground = physics_engine.is_on_ground(self)
119
120        # Add to the odometer how far we've moved
121        self.x_odometer += dx
122
123        # Jumping animation
124        if not is_on_ground:
125            if dy > DEAD_ZONE:
126                self.texture = self.jump_texture_pair[self.character_face_direction]
127                return
128            elif dy < -DEAD_ZONE:
129                self.texture = self.fall_texture_pair[self.character_face_direction]
130                return
131
132        # Idle animation
133        if abs(dx) <= DEAD_ZONE:
134            self.texture = self.idle_texture_pair[self.character_face_direction]
135            return
136
137        # Have we moved far enough to change the texture?
138        if abs(self.x_odometer) > DISTANCE_TO_CHANGE_TEXTURE:
139
140            # Reset the odometer
141            self.x_odometer = 0
142
143            # Advance the walking animation
144            self.cur_texture += 1
145            if self.cur_texture > 7:
146                self.cur_texture = 0
147            self.texture = self.walk_textures[self.cur_texture][self.character_face_direction]
148
149
150class GameWindow(arcade.Window):
151    """ Main Window """
152
153    def __init__(self, width, height, title):
154        """ Create the variables """
155
156        # Init the parent class
157        super().__init__(width, height, title)
158
159        # Player sprite
160        self.player_sprite: Optional[PlayerSprite] = None
161
162        # Sprite lists we need
163        self.player_list: Optional[arcade.SpriteList] = None
164        self.wall_list: Optional[arcade.SpriteList] = None
165        self.bullet_list: Optional[arcade.SpriteList] = None
166        self.item_list: Optional[arcade.SpriteList] = None
167
168        # Track the current state of what key is pressed
169        self.left_pressed: bool = False
170        self.right_pressed: bool = False
171
172        # Physics engine
173        self.physics_engine = Optional[arcade.PymunkPhysicsEngine]
174
175        # Set background color
176        self.background_color = arcade.color.AMAZON
177
178    def setup(self):
179        """ Set up everything with the game """
180
181        # Create the sprite lists
182        self.player_list = arcade.SpriteList()
183        self.bullet_list = arcade.SpriteList()
184
185        # Map name
186        map_name = ":resources:/tiled_maps/pymunk_test_map.json"
187
188        # Load in TileMap
189        tile_map = arcade.load_tilemap(map_name, SPRITE_SCALING_TILES)
190
191        # Pull the sprite layers out of the tile map
192        self.wall_list = tile_map.sprite_lists["Platforms"]
193        self.item_list = tile_map.sprite_lists["Dynamic Items"]
194
195        # Create player sprite
196        self.player_sprite = PlayerSprite()
197
198        # Set player location
199        grid_x = 1
200        grid_y = 1
201        self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2
202        self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2
203        # Add to player sprite list
204        self.player_list.append(self.player_sprite)
205
206        # --- Pymunk Physics Engine Setup ---
207
208        # The default damping for every object controls the percent of velocity
209        # the object will keep each second. A value of 1.0 is no speed loss,
210        # 0.9 is 10% per second, 0.1 is 90% per second.
211        # For top-down games, this is basically the friction for moving objects.
212        # For platformers with gravity, this should probably be set to 1.0.
213        # Default value is 1.0 if not specified.
214        damping = DEFAULT_DAMPING
215
216        # Set the gravity. (0, 0) is good for outer space and top-down.
217        gravity = (0, -GRAVITY)
218
219        # Create the physics engine
220        self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping,
221                                                         gravity=gravity)
222
223        # Add the player.
224        # For the player, we set the damping to a lower value, which increases
225        # the damping rate. This prevents the character from traveling too far
226        # after the player lets off the movement keys.
227        # Setting the moment of inertia to PymunkPhysicsEngine.MOMENT_INF prevents it from
228        # rotating.
229        # Friction normally goes between 0 (no friction) and 1.0 (high friction)
230        # Friction is between two objects in contact. It is important to remember
231        # in top-down games that friction moving along the 'floor' is controlled
232        # by damping.
233        self.physics_engine.add_sprite(self.player_sprite,
234                                       friction=PLAYER_FRICTION,
235                                       mass=PLAYER_MASS,
236                                       moment_of_inertia=arcade.PymunkPhysicsEngine.MOMENT_INF,
237                                       collision_type="player",
238                                       max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
239                                       max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED)
240
241        # Create the walls.
242        # By setting the body type to PymunkPhysicsEngine.STATIC the walls can't
243        # move.
244        # Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC
245        # PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be
246        # repositioned by code and don't respond to physics forces.
247        # Dynamic is default.
248        self.physics_engine.add_sprite_list(self.wall_list,
249                                            friction=WALL_FRICTION,
250                                            collision_type="wall",
251                                            body_type=arcade.PymunkPhysicsEngine.STATIC)
252
253        # Create the items
254        self.physics_engine.add_sprite_list(self.item_list,
255                                            friction=DYNAMIC_ITEM_FRICTION,
256                                            collision_type="item")
257
258    def on_key_press(self, key, modifiers):
259        """Called whenever a key is pressed. """
260
261        if key == arcade.key.LEFT:
262            self.left_pressed = True
263        elif key == arcade.key.RIGHT:
264            self.right_pressed = True
265        elif key == arcade.key.UP:
266            # find out if player is standing on ground
267            if self.physics_engine.is_on_ground(self.player_sprite):
268                # She is! Go ahead and jump
269                impulse = (0, PLAYER_JUMP_IMPULSE)
270                self.physics_engine.apply_impulse(self.player_sprite, impulse)
271
272    def on_key_release(self, key, modifiers):
273        """Called when the user releases a key. """
274
275        if key == arcade.key.LEFT:
276            self.left_pressed = False
277        elif key == arcade.key.RIGHT:
278            self.right_pressed = False
279
280    def on_update(self, delta_time):
281        """ Movement and game logic """
282
283        is_on_ground = self.physics_engine.is_on_ground(self.player_sprite)
284        # Update player forces based on keys pressed
285        if self.left_pressed and not self.right_pressed:
286            # Create a force to the left. Apply it.
287            if is_on_ground:
288                force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0)
289            else:
290                force = (-PLAYER_MOVE_FORCE_IN_AIR, 0)
291            self.physics_engine.apply_force(self.player_sprite, force)
292            # Set friction to zero for the player while moving
293            self.physics_engine.set_friction(self.player_sprite, 0)
294        elif self.right_pressed and not self.left_pressed:
295            # Create a force to the right. Apply it.
296            if is_on_ground:
297                force = (PLAYER_MOVE_FORCE_ON_GROUND, 0)
298            else:
299                force = (PLAYER_MOVE_FORCE_IN_AIR, 0)
300            self.physics_engine.apply_force(self.player_sprite, force)
301            # Set friction to zero for the player while moving
302            self.physics_engine.set_friction(self.player_sprite, 0)
303        else:
304            # Player's feet are not moving. Therefore up the friction so we stop.
305            self.physics_engine.set_friction(self.player_sprite, 1.0)
306
307        # Move items in the physics engine
308        self.physics_engine.step()
309
310    def on_draw(self):
311        """ Draw everything """
312        self.clear()
313        self.wall_list.draw()
314        self.bullet_list.draw()
315        self.item_list.draw()
316        self.player_list.draw()
317
318def main():
319    """ Main function """
320    window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
321    window.setup()
322    arcade.run()
323
324
325if __name__ == "__main__":
326    main()