pymunk_demo_platformer_08.py Full Listing

pymunk_demo_platformer_08.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
 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        # Hit box will be set based on the first image used.
101        self.hit_box = self.texture.hit_box_points
102
103        # Default to face-right
104        self.character_face_direction = RIGHT_FACING
105
106        # Index of our current texture
107        self.cur_texture = 0
108
109        # How far have we traveled horizontally since changing the texture
110        self.x_odometer = 0
111
112    def pymunk_moved(self, physics_engine, dx, dy, d_angle):
113        """ Handle being moved by the pymunk engine """
114        # Figure out if we need to face left or right
115        if dx < -DEAD_ZONE and self.character_face_direction == RIGHT_FACING:
116            self.character_face_direction = LEFT_FACING
117        elif dx > DEAD_ZONE and self.character_face_direction == LEFT_FACING:
118            self.character_face_direction = RIGHT_FACING
119
120        # Are we on the ground?
121        is_on_ground = physics_engine.is_on_ground(self)
122
123        # Add to the odometer how far we've moved
124        self.x_odometer += dx
125
126        # Jumping animation
127        if not is_on_ground:
128            if dy > DEAD_ZONE:
129                self.texture = self.jump_texture_pair[self.character_face_direction]
130                return
131            elif dy < -DEAD_ZONE:
132                self.texture = self.fall_texture_pair[self.character_face_direction]
133                return
134
135        # Idle animation
136        if abs(dx) <= DEAD_ZONE:
137            self.texture = self.idle_texture_pair[self.character_face_direction]
138            return
139
140        # Have we moved far enough to change the texture?
141        if abs(self.x_odometer) > DISTANCE_TO_CHANGE_TEXTURE:
142
143            # Reset the odometer
144            self.x_odometer = 0
145
146            # Advance the walking animation
147            self.cur_texture += 1
148            if self.cur_texture > 7:
149                self.cur_texture = 0
150            self.texture = self.walk_textures[self.cur_texture][self.character_face_direction]
151
152class GameWindow(arcade.Window):
153    """ Main Window """
154
155    def __init__(self, width, height, title):
156        """ Create the variables """
157
158        # Init the parent class
159        super().__init__(width, height, title)
160
161        # Player sprite
162        self.player_sprite: Optional[PlayerSprite] = None
163
164        # Sprite lists we need
165        self.player_list: Optional[arcade.SpriteList] = None
166        self.wall_list: Optional[arcade.SpriteList] = None
167        self.bullet_list: Optional[arcade.SpriteList] = None
168        self.item_list: Optional[arcade.SpriteList] = None
169
170        # Track the current state of what key is pressed
171        self.left_pressed: bool = False
172        self.right_pressed: bool = False
173
174        # Physics engine
175        self.physics_engine = Optional[arcade.PymunkPhysicsEngine]
176
177        # Set background color
178        arcade.set_background_color(arcade.color.AMAZON)
179
180    def setup(self):
181        """ Set up everything with the game """
182
183        # Create the sprite lists
184        self.player_list = arcade.SpriteList()
185        self.bullet_list = arcade.SpriteList()
186
187        # Read in the tiled map
188        map_name = "pymunk_test_map.tmx"
189        my_map = arcade.tilemap.read_tmx(map_name)
190
191        # Read in the map layers
192        self.wall_list = arcade.tilemap.process_layer(my_map, 'Platforms', SPRITE_SCALING_TILES)
193        self.item_list = arcade.tilemap.process_layer(my_map, 'Dynamic Items', SPRITE_SCALING_TILES)
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 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=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        arcade.start_render()
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 method """
320    window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
321    window.setup()
322    arcade.run()
323
324
325if __name__ == "__main__":
326    main()