pymunk_demo_platformer_12.py Full Listing#

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