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