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