pymunk_demo_platformer_12.py Full Listing

pymunk_demo_platformer_12.py
  1"""
  2Example of Pymunk Physics Engine Platformer
  3"""
  4
  5import math
  6from typing import Optional
  7import arcade
  8
  9SCREEN_TITLE = "PyMunk Platformer"
 10
 11# How big are our image tiles?
 12SPRITE_IMAGE_SIZE = 128
 13
 14# Scale sprites up or down
 15SPRITE_SCALING_PLAYER = 0.5
 16SPRITE_SCALING_TILES = 0.5
 17
 18# Scaled sprite size for tiles
 19SPRITE_SIZE = int(SPRITE_IMAGE_SIZE * SPRITE_SCALING_PLAYER)
 20
 21# Size of grid to show on screen, in number of tiles
 22SCREEN_GRID_WIDTH = 25
 23SCREEN_GRID_HEIGHT = 15
 24
 25# Size of screen to show, in pixels
 26SCREEN_WIDTH = SPRITE_SIZE * SCREEN_GRID_WIDTH
 27SCREEN_HEIGHT = SPRITE_SIZE * SCREEN_GRID_HEIGHT
 28
 29# --- Physics forces. Higher number, faster accelerating.
 30
 31# Gravity
 32GRAVITY = 1500
 33
 34# Damping - Amount of speed lost per second
 35DEFAULT_DAMPING = 1.0
 36PLAYER_DAMPING = 0.4
 37
 38# Friction between objects
 39PLAYER_FRICTION = 1.0
 40WALL_FRICTION = 0.7
 41DYNAMIC_ITEM_FRICTION = 0.6
 42
 43# Mass (defaults to 1)
 44PLAYER_MASS = 2.0
 45
 46# Keep player from going too fast
 47PLAYER_MAX_HORIZONTAL_SPEED = 450
 48PLAYER_MAX_VERTICAL_SPEED = 1600
 49
 50# Force applied while on the ground
 51PLAYER_MOVE_FORCE_ON_GROUND = 8000
 52
 53# Force applied when moving left/right in the air
 54PLAYER_MOVE_FORCE_IN_AIR = 900
 55
 56# Strength of a jump
 57PLAYER_JUMP_IMPULSE = 1800
 58
 59# Close enough to not-moving to have the animation go to idle.
 60DEAD_ZONE = 0.1
 61
 62# Constants used to track if the player is facing left or right
 63RIGHT_FACING = 0
 64LEFT_FACING = 1
 65
 66# How many pixels to move before we change the texture in the walking animation
 67DISTANCE_TO_CHANGE_TEXTURE = 20
 68
 69# How much force to put on the bullet
 70BULLET_MOVE_FORCE = 4500
 71
 72# Mass of the bullet
 73BULLET_MASS = 0.1
 74
 75# Make bullet less affected by gravity
 76BULLET_GRAVITY = 300
 77
 78
 79class PlayerSprite(arcade.Sprite):
 80    """Player Sprite"""
 81
 82    def __init__(
 83        self, ladder_list: arcade.SpriteList, hit_box_algorithm: arcade.hitbox.HitBoxAlgorithm
 84    ):
 85        """Init"""
 86        # Let parent initialize
 87        super().__init__(scale=SPRITE_SCALING_PLAYER)
 88
 89        # Images from Kenney.nl's Character pack
 90        # main_path = ":resources:images/animated_characters/female_adventurer/femaleAdventurer"
 91        main_path = ":resources:images/animated_characters/female_person/femalePerson"
 92        # main_path = ":resources:images/animated_characters/male_person/malePerson"
 93        # main_path = ":resources:images/animated_characters/male_adventurer/maleAdventurer"
 94        # main_path = ":resources:images/animated_characters/zombie/zombie"
 95        # main_path = ":resources:images/animated_characters/robot/robot"
 96
 97        idle_texture = arcade.load_texture(
 98            f"{main_path}_idle.png", hit_box_algorithm=hit_box_algorithm
 99        )
100        jump_texture = arcade.load_texture(f"{main_path}_jump.png")
101        fall_texture = arcade.load_texture(f"{main_path}_fall.png")
102
103        # Load textures for idle standing
104        self.idle_texture_pair = idle_texture, idle_texture.flip_left_right()
105        self.jump_texture_pair = jump_texture, jump_texture.flip_left_right()
106        self.fall_texture_pair = fall_texture, fall_texture.flip_left_right()
107
108        # Load textures for walking
109        self.walk_textures = []
110        for i in range(8):
111            texture = arcade.load_texture(f"{main_path}_walk{i}.png")
112            self.walk_textures.append((texture, texture.flip_left_right()))
113
114        # Load textures for climbing
115        self.climbing_textures = []
116        texture = arcade.load_texture(f"{main_path}_climb0.png")
117        self.climbing_textures.append(texture)
118        texture = arcade.load_texture(f"{main_path}_climb1.png")
119        self.climbing_textures.append(texture)
120
121        # Set the initial texture
122        self.texture = self.idle_texture_pair[0]
123
124        # Default to face-right
125        self.character_face_direction = RIGHT_FACING
126
127        # Index of our current texture
128        self.cur_texture = 0
129
130        # How far have we traveled horizontally since changing the texture
131        self.x_odometer = 0
132        self.y_odometer = 0
133
134        self.ladder_list = ladder_list
135        self.is_on_ladder = False
136
137    def pymunk_moved(self, physics_engine, dx, dy, d_angle):
138        """Handle being moved by the pymunk engine"""
139        # Figure out if we need to face left or right
140        if dx < -DEAD_ZONE and self.character_face_direction == RIGHT_FACING:
141            self.character_face_direction = LEFT_FACING
142        elif dx > DEAD_ZONE and self.character_face_direction == LEFT_FACING:
143            self.character_face_direction = RIGHT_FACING
144
145        # Are we on the ground?
146        is_on_ground = physics_engine.is_on_ground(self)
147
148        # Are we on a ladder?
149        if len(arcade.check_for_collision_with_list(self, self.ladder_list)) > 0:
150            if not self.is_on_ladder:
151                self.is_on_ladder = True
152                self.pymunk.gravity = (0, 0)
153                self.pymunk.damping = 0.0001
154                self.pymunk.max_vertical_velocity = PLAYER_MAX_HORIZONTAL_SPEED
155        else:
156            if self.is_on_ladder:
157                self.pymunk.damping = 1.0
158                self.pymunk.max_vertical_velocity = PLAYER_MAX_VERTICAL_SPEED
159                self.is_on_ladder = False
160                self.pymunk.gravity = None
161
162        # Add to the odometer how far we've moved
163        self.x_odometer += dx
164        self.y_odometer += dy
165
166        if self.is_on_ladder and not is_on_ground:
167            # Have we moved far enough to change the texture?
168            if abs(self.y_odometer) > DISTANCE_TO_CHANGE_TEXTURE:
169                # Reset the odometer
170                self.y_odometer = 0
171
172                # Advance the walking animation
173                self.cur_texture += 1
174
175            if self.cur_texture > 1:
176                self.cur_texture = 0
177            self.texture = self.climbing_textures[self.cur_texture]
178            return
179
180        # Jumping animation
181        if not is_on_ground:
182            if dy > DEAD_ZONE:
183                self.texture = self.jump_texture_pair[self.character_face_direction]
184                return
185            elif dy < -DEAD_ZONE:
186                self.texture = self.fall_texture_pair[self.character_face_direction]
187                return
188
189        # Idle animation
190        if abs(dx) <= DEAD_ZONE:
191            self.texture = self.idle_texture_pair[self.character_face_direction]
192            return
193
194        # Have we moved far enough to change the texture?
195        if abs(self.x_odometer) > DISTANCE_TO_CHANGE_TEXTURE:
196            # Reset the odometer
197            self.x_odometer = 0
198
199            # Advance the walking animation
200            self.cur_texture += 1
201            if self.cur_texture > 7:
202                self.cur_texture = 0
203            self.texture = self.walk_textures[self.cur_texture][self.character_face_direction]
204
205
206class BulletSprite(arcade.SpriteSolidColor):
207    """Bullet Sprite"""
208
209    def pymunk_moved(self, physics_engine, dx, dy, d_angle):
210        """Handle when the sprite is moved by the physics engine."""
211        # If the bullet falls below the screen, remove it
212        if self.center_y < -100:
213            self.remove_from_sprite_lists()
214
215
216class GameWindow(arcade.Window):
217    """Main Window"""
218
219    def __init__(self, width, height, title):
220        """Create the variables"""
221
222        # Init the parent class
223        super().__init__(width, height, title)
224
225        # Player sprite
226        self.player_sprite: PlayerSprite | None = None
227
228        # Sprite lists we need
229        self.player_list: arcade.SpriteList | None = None
230        self.wall_list: arcade.SpriteList | None = None
231        self.bullet_list: arcade.SpriteList | None = None
232        self.item_list: arcade.SpriteList | None = None
233        self.moving_sprites_list: arcade.SpriteList | None = None
234        self.ladder_list: arcade.SpriteList | None = None
235
236        # Track the current state of what key is pressed
237        self.left_pressed: bool = False
238        self.right_pressed: bool = False
239        self.up_pressed: bool = False
240        self.down_pressed: bool = False
241
242        # Physics engine
243        self.physics_engine: Optional[arcade.PymunkPhysicsEngine] = None
244
245        # Set background color
246        self.background_color = arcade.color.AMAZON
247
248    def setup(self):
249        """Set up everything with the game"""
250
251        # Create the sprite lists
252        self.player_list = arcade.SpriteList()
253        self.bullet_list = arcade.SpriteList()
254
255        # Map name
256        map_name = ":resources:/tiled_maps/pymunk_test_map.json"
257
258        # Load in TileMap
259        tile_map = arcade.load_tilemap(map_name, SPRITE_SCALING_TILES)
260
261        # Pull the sprite layers out of the tile map
262        self.wall_list = tile_map.sprite_lists["Platforms"]
263        self.item_list = tile_map.sprite_lists["Dynamic Items"]
264        self.ladder_list = tile_map.sprite_lists["Ladders"]
265        self.moving_sprites_list = tile_map.sprite_lists["Moving Platforms"]
266
267        # Create player sprite
268        self.player_sprite = PlayerSprite(
269            self.ladder_list, hit_box_algorithm=arcade.hitbox.algo_detailed
270        )
271
272        # Set player location
273        grid_x = 1
274        grid_y = 1
275        self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2
276        self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2
277        # Add to player sprite list
278        self.player_list.append(self.player_sprite)
279
280        # --- Pymunk Physics Engine Setup ---
281
282        # The default damping for every object controls the percent of velocity
283        # the object will keep each second. A value of 1.0 is no speed loss,
284        # 0.9 is 10% per second, 0.1 is 90% per second.
285        # For top-down games, this is basically the friction for moving objects.
286        # For platformers with gravity, this should probably be set to 1.0.
287        # Default value is 1.0 if not specified.
288        damping = DEFAULT_DAMPING
289
290        # Set the gravity. (0, 0) is good for outer space and top-down.
291        gravity = (0, -GRAVITY)
292
293        # Create the physics engine
294        self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping, gravity=gravity)
295
296        def wall_hit_handler(bullet_sprite, _wall_sprite, _arbiter, _space, _data):
297            """Called for bullet/wall collision"""
298            bullet_sprite.remove_from_sprite_lists()
299
300        self.physics_engine.add_collision_handler("bullet", "wall", post_handler=wall_hit_handler)
301
302        def item_hit_handler(bullet_sprite, item_sprite, _arbiter, _space, _data):
303            """Called for bullet/wall collision"""
304            bullet_sprite.remove_from_sprite_lists()
305            item_sprite.remove_from_sprite_lists()
306
307        self.physics_engine.add_collision_handler("bullet", "item", post_handler=item_hit_handler)
308
309        # Add the player.
310        # For the player, we set the damping to a lower value, which increases
311        # the damping rate. This prevents the character from traveling too far
312        # after the player lets off the movement keys.
313        # Setting the moment of intertia to PymunkPhysicsEngine.MOMENT_INF prevents it from
314        # rotating.
315        # Friction normally goes between 0 (no friction) and 1.0 (high friction)
316        # Friction is between two objects in contact. It is important to remember
317        # in top-down games that friction moving along the 'floor' is controlled
318        # by damping.
319        self.physics_engine.add_sprite(
320            self.player_sprite,
321            friction=PLAYER_FRICTION,
322            mass=PLAYER_MASS,
323            moment_of_inertia=arcade.PymunkPhysicsEngine.MOMENT_INF,
324            collision_type="player",
325            max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
326            max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED,
327        )
328
329        # Create the walls.
330        # By setting the body type to PymunkPhysicsEngine.STATIC the walls can't
331        # move.
332        # Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC
333        # PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be
334        # repositioned by code and don't respond to physics forces.
335        # Dynamic is default.
336        self.physics_engine.add_sprite_list(
337            self.wall_list,
338            friction=WALL_FRICTION,
339            collision_type="wall",
340            body_type=arcade.PymunkPhysicsEngine.STATIC,
341        )
342
343        # Create the items
344        self.physics_engine.add_sprite_list(
345            self.item_list, friction=DYNAMIC_ITEM_FRICTION, collision_type="item"
346        )
347
348        # Add kinematic sprites
349        self.physics_engine.add_sprite_list(
350            self.moving_sprites_list, body_type=arcade.PymunkPhysicsEngine.KINEMATIC
351        )
352
353    def on_key_press(self, key, modifiers):
354        """Called whenever a key is pressed."""
355
356        if key in (arcade.key.LEFT, arcade.key.A):
357            self.left_pressed = True
358        elif key in (arcade.key.RIGHT, arcade.key.D):
359            self.right_pressed = True
360        elif key in (arcade.key.UP, arcade.key.W):
361            self.up_pressed = True
362            # find out if player is standing on ground, and not on a ladder
363            if (
364                self.physics_engine.is_on_ground(self.player_sprite)
365                and not self.player_sprite.is_on_ladder
366            ):
367                # She is! Go ahead and jump
368                impulse = (0, PLAYER_JUMP_IMPULSE)
369                self.physics_engine.apply_impulse(self.player_sprite, impulse)
370        elif key in (arcade.key.DOWN, arcade.key.S):
371            self.down_pressed = True
372
373    def on_key_release(self, key, modifiers):
374        """Called when the user releases a key."""
375
376        if key in (arcade.key.LEFT, arcade.key.A):
377            self.left_pressed = False
378        elif key in (arcade.key.RIGHT, arcade.key.D):
379            self.right_pressed = False
380        elif key in (arcade.key.UP, arcade.key.W):
381            self.up_pressed = False
382        elif key in (arcade.key.DOWN, arcade.key.S):
383            self.down_pressed = False
384
385    def on_mouse_press(self, x, y, button, modifiers):
386        """Called whenever the mouse button is clicked."""
387
388        bullet = BulletSprite(width=20, height=5, color=arcade.color.DARK_YELLOW)
389        self.bullet_list.append(bullet)
390
391        # Position the bullet at the player's current location
392        start_x = self.player_sprite.center_x
393        start_y = self.player_sprite.center_y
394        bullet.position = self.player_sprite.position
395
396        # Get from the mouse the destination location for the bullet
397        # IMPORTANT! If you have a scrolling screen, you will also need
398        # to add in self.view_bottom and self.view_left.
399        dest_x = x
400        dest_y = y
401
402        # Do math to calculate how to get the bullet to the destination.
403        # Calculation the angle in radians between the start points
404        # and end points. This is the angle the bullet will travel.
405        x_diff = dest_x - start_x
406        y_diff = dest_y - start_y
407        angle = math.atan2(y_diff, x_diff)
408
409        # What is the 1/2 size of this sprite, so we can figure out how far
410        # away to spawn the bullet
411        size = max(self.player_sprite.width, self.player_sprite.height) / 2
412
413        # Use angle to to spawn bullet away from player in proper direction
414        bullet.center_x += size * math.cos(angle)
415        bullet.center_y += size * math.sin(angle)
416
417        # Set angle of bullet
418        bullet.angle = math.degrees(angle)
419
420        # Gravity to use for the bullet
421        # If we don't use custom gravity, bullet drops too fast, or we have
422        # to make it go too fast.
423        # Force is in relation to bullet's angle.
424        bullet_gravity = (0, -BULLET_GRAVITY)
425
426        # Add the sprite. This needs to be done AFTER setting the fields above.
427        self.physics_engine.add_sprite(
428            bullet,
429            mass=BULLET_MASS,
430            damping=1.0,
431            friction=0.6,
432            collision_type="bullet",
433            gravity=bullet_gravity,
434            elasticity=0.9,
435        )
436
437        # Add force to bullet
438        force = (BULLET_MOVE_FORCE, 0)
439        self.physics_engine.apply_force(bullet, force)
440
441    def on_update(self, delta_time):
442        """Movement and game logic"""
443
444        is_on_ground = self.physics_engine.is_on_ground(self.player_sprite)
445        # Update player forces based on keys pressed
446        if self.left_pressed and not self.right_pressed:
447            # Create a force to the left. Apply it.
448            if is_on_ground or self.player_sprite.is_on_ladder:
449                force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0)
450            else:
451                force = (-PLAYER_MOVE_FORCE_IN_AIR, 0)
452            self.physics_engine.apply_force(self.player_sprite, force)
453            # Set friction to zero for the player while moving
454            self.physics_engine.set_friction(self.player_sprite, 0)
455        elif self.right_pressed and not self.left_pressed:
456            # Create a force to the right. Apply it.
457            if is_on_ground or self.player_sprite.is_on_ladder:
458                force = (PLAYER_MOVE_FORCE_ON_GROUND, 0)
459            else:
460                force = (PLAYER_MOVE_FORCE_IN_AIR, 0)
461            self.physics_engine.apply_force(self.player_sprite, force)
462            # Set friction to zero for the player while moving
463            self.physics_engine.set_friction(self.player_sprite, 0)
464        elif self.up_pressed and not self.down_pressed:
465            # Create a force to the right. Apply it.
466            if self.player_sprite.is_on_ladder:
467                force = (0, PLAYER_MOVE_FORCE_ON_GROUND)
468                self.physics_engine.apply_force(self.player_sprite, force)
469                # Set friction to zero for the player while moving
470                self.physics_engine.set_friction(self.player_sprite, 0)
471        elif self.down_pressed and not self.up_pressed:
472            # Create a force to the right. Apply it.
473            if self.player_sprite.is_on_ladder:
474                force = (0, -PLAYER_MOVE_FORCE_ON_GROUND)
475                self.physics_engine.apply_force(self.player_sprite, force)
476                # Set friction to zero for the player while moving
477                self.physics_engine.set_friction(self.player_sprite, 0)
478
479        else:
480            # Player's feet are not moving. Therefore up the friction so we stop.
481            self.physics_engine.set_friction(self.player_sprite, 1.0)
482
483        # Move items in the physics engine
484        self.physics_engine.step()
485
486        # For each moving sprite, see if we've reached a boundary and need to
487        # reverse course.
488        for moving_sprite in self.moving_sprites_list:
489            if (
490                moving_sprite.boundary_right
491                and moving_sprite.change_x > 0
492                and moving_sprite.right > moving_sprite.boundary_right
493            ):
494                moving_sprite.change_x *= -1
495            elif (
496                moving_sprite.boundary_left
497                and moving_sprite.change_x < 0
498                and moving_sprite.left > moving_sprite.boundary_left
499            ):
500                moving_sprite.change_x *= -1
501            if (
502                moving_sprite.boundary_top
503                and moving_sprite.change_y > 0
504                and moving_sprite.top > moving_sprite.boundary_top
505            ):
506                moving_sprite.change_y *= -1
507            elif (
508                moving_sprite.boundary_bottom
509                and moving_sprite.change_y < 0
510                and moving_sprite.bottom < moving_sprite.boundary_bottom
511            ):
512                moving_sprite.change_y *= -1
513
514            # Figure out and set our moving platform velocity.
515            # Pymunk uses velocity is in pixels per second. If we instead have
516            # pixels per frame, we need to convert.
517            velocity = (
518                moving_sprite.change_x * 1 / delta_time,
519                moving_sprite.change_y * 1 / delta_time,
520            )
521            self.physics_engine.set_velocity(moving_sprite, velocity)
522
523    def on_draw(self):
524        """Draw everything"""
525        self.clear()
526        self.wall_list.draw()
527        self.ladder_list.draw()
528        self.moving_sprites_list.draw()
529        self.bullet_list.draw()
530        self.item_list.draw()
531        self.player_list.draw()
532
533        # for item in self.player_list:
534        #     item.draw_hit_box(arcade.color.RED)
535        # for item in self.item_list:
536        #     item.draw_hit_box(arcade.color.RED)
537
538
539def main():
540    """Main function"""
541    window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
542    window.setup()
543    arcade.run()
544
545
546if __name__ == "__main__":
547    main()