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 """ Init """
81 # Let parent initialize
82 super().__init__()
83
84 # Set our scale
85 self.scale = SPRITE_SCALING_PLAYER
86
87 # Images from Kenney.nl's Character pack
88 # main_path = ":resources:images/animated_characters/female_adventurer/femaleAdventurer"
89 main_path = ":resources:images/animated_characters/female_person/femalePerson"
90 # main_path = ":resources:images/animated_characters/male_person/malePerson"
91 # main_path = ":resources:images/animated_characters/male_adventurer/maleAdventurer"
92 # main_path = ":resources:images/animated_characters/zombie/zombie"
93 # main_path = ":resources:images/animated_characters/robot/robot"
94
95 # Load textures for idle standing
96 self.idle_texture_pair = arcade.load_texture_pair(f"{main_path}_idle.png")
97 self.jump_texture_pair = arcade.load_texture_pair(f"{main_path}_jump.png")
98 self.fall_texture_pair = arcade.load_texture_pair(f"{main_path}_fall.png")
99
100 # Load textures for walking
101 self.walk_textures = []
102 for i in range(8):
103 texture = arcade.load_texture_pair(f"{main_path}_walk{i}.png")
104 self.walk_textures.append(texture)
105
106 # Set the initial texture
107 self.texture = self.idle_texture_pair[0]
108
109 # Hit box will be set based on the first image used.
110 self.hit_box = self.texture.hit_box_points
111
112 # Default to face-right
113 self.character_face_direction = RIGHT_FACING
114
115 # Index of our current texture
116 self.cur_texture = 0
117
118 # How far have we traveled horizontally since changing the texture
119 self.x_odometer = 0
120
121 def pymunk_moved(self, physics_engine, dx, dy, d_angle):
122 """ Handle being moved by the pymunk engine """
123 # Figure out if we need to face left or right
124 if dx < -DEAD_ZONE and self.character_face_direction == RIGHT_FACING:
125 self.character_face_direction = LEFT_FACING
126 elif dx > DEAD_ZONE and self.character_face_direction == LEFT_FACING:
127 self.character_face_direction = RIGHT_FACING
128
129 # Are we on the ground?
130 is_on_ground = physics_engine.is_on_ground(self)
131
132 # Add to the odometer how far we've moved
133 self.x_odometer += dx
134
135 # Jumping animation
136 if not is_on_ground:
137 if dy > DEAD_ZONE:
138 self.texture = self.jump_texture_pair[self.character_face_direction]
139 return
140 elif dy < -DEAD_ZONE:
141 self.texture = self.fall_texture_pair[self.character_face_direction]
142 return
143
144 # Idle animation
145 if abs(dx) <= DEAD_ZONE:
146 self.texture = self.idle_texture_pair[self.character_face_direction]
147 return
148
149 # Have we moved far enough to change the texture?
150 if abs(self.x_odometer) > DISTANCE_TO_CHANGE_TEXTURE:
151
152 # Reset the odometer
153 self.x_odometer = 0
154
155 # Advance the walking animation
156 self.cur_texture += 1
157 if self.cur_texture > 7:
158 self.cur_texture = 0
159 self.texture = self.walk_textures[self.cur_texture][self.character_face_direction]
160
161class GameWindow(arcade.Window):
162 """ Main Window """
163
164 def __init__(self, width, height, title):
165 """ Create the variables """
166
167 # Init the parent class
168 super().__init__(width, height, title)
169
170 # Player sprite
171 self.player_sprite: Optional[PlayerSprite] = None
172
173 # Sprite lists we need
174 self.player_list: Optional[arcade.SpriteList] = None
175 self.wall_list: Optional[arcade.SpriteList] = None
176 self.bullet_list: Optional[arcade.SpriteList] = None
177 self.item_list: Optional[arcade.SpriteList] = None
178
179 # Track the current state of what key is pressed
180 self.left_pressed: bool = False
181 self.right_pressed: bool = False
182
183 # Physics engine
184 self.physics_engine = Optional[arcade.PymunkPhysicsEngine]
185
186 # Set background color
187 arcade.set_background_color(arcade.color.AMAZON)
188
189 def setup(self):
190 """ Set up everything with the game """
191
192 # Create the sprite lists
193 self.player_list = arcade.SpriteList()
194 self.bullet_list = arcade.SpriteList()
195
196 # Read in the tiled map
197 map_name = "pymunk_test_map.tmx"
198 my_map = arcade.tilemap.read_tmx(map_name)
199
200 # Read in the map layers
201 self.wall_list = arcade.tilemap.process_layer(my_map, 'Platforms', SPRITE_SCALING_TILES)
202 self.item_list = arcade.tilemap.process_layer(my_map, 'Dynamic Items', SPRITE_SCALING_TILES)
203
204 # Create player sprite
205 self.player_sprite = PlayerSprite()
206
207 # Set player location
208 grid_x = 1
209 grid_y = 1
210 self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2
211 self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2
212 # Add to player sprite list
213 self.player_list.append(self.player_sprite)
214
215 # --- Pymunk Physics Engine Setup ---
216
217 # The default damping for every object controls the percent of velocity
218 # the object will keep each second. A value of 1.0 is no speed loss,
219 # 0.9 is 10% per second, 0.1 is 90% per second.
220 # For top-down games, this is basically the friction for moving objects.
221 # For platformers with gravity, this should probably be set to 1.0.
222 # Default value is 1.0 if not specified.
223 damping = DEFAULT_DAMPING
224
225 # Set the gravity. (0, 0) is good for outer space and top-down.
226 gravity = (0, -GRAVITY)
227
228 # Create the physics engine
229 self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping,
230 gravity=gravity)
231
232 # Add the player.
233 # For the player, we set the damping to a lower value, which increases
234 # the damping rate. This prevents the character from traveling too far
235 # after the player lets off the movement keys.
236 # Setting the moment to PymunkPhysicsEngine.MOMENT_INF prevents it from
237 # rotating.
238 # Friction normally goes between 0 (no friction) and 1.0 (high friction)
239 # Friction is between two objects in contact. It is important to remember
240 # in top-down games that friction moving along the 'floor' is controlled
241 # by damping.
242 self.physics_engine.add_sprite(self.player_sprite,
243 friction=PLAYER_FRICTION,
244 mass=PLAYER_MASS,
245 moment=arcade.PymunkPhysicsEngine.MOMENT_INF,
246 collision_type="player",
247 max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
248 max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED)
249
250 # Create the walls.
251 # By setting the body type to PymunkPhysicsEngine.STATIC the walls can't
252 # move.
253 # Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC
254 # PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be
255 # repositioned by code and don't respond to physics forces.
256 # Dynamic is default.
257 self.physics_engine.add_sprite_list(self.wall_list,
258 friction=WALL_FRICTION,
259 collision_type="wall",
260 body_type=arcade.PymunkPhysicsEngine.STATIC)
261
262 # Create the items
263 self.physics_engine.add_sprite_list(self.item_list,
264 friction=DYNAMIC_ITEM_FRICTION,
265 collision_type="item")
266
267 def on_key_press(self, key, modifiers):
268 """Called whenever a key is pressed. """
269
270 if key == arcade.key.LEFT:
271 self.left_pressed = True
272 elif key == arcade.key.RIGHT:
273 self.right_pressed = True
274 elif key == arcade.key.UP:
275 # find out if player is standing on ground
276 if self.physics_engine.is_on_ground(self.player_sprite):
277 # She is! Go ahead and jump
278 impulse = (0, PLAYER_JUMP_IMPULSE)
279 self.physics_engine.apply_impulse(self.player_sprite, impulse)
280
281 def on_key_release(self, key, modifiers):
282 """Called when the user releases a key. """
283
284 if key == arcade.key.LEFT:
285 self.left_pressed = False
286 elif key == arcade.key.RIGHT:
287 self.right_pressed = False
288
289 def on_mouse_press(self, x, y, button, modifiers):
290 """ Called whenever the mouse button is clicked. """
291
292 bullet = arcade.SpriteSolidColor(20, 5, arcade.color.DARK_YELLOW)
293 self.bullet_list.append(bullet)
294
295 # Position the bullet at the player's current location
296 start_x = self.player_sprite.center_x
297 start_y = self.player_sprite.center_y
298 bullet.position = self.player_sprite.position
299
300 # Get from the mouse the destination location for the bullet
301 # IMPORTANT! If you have a scrolling screen, you will also need
302 # to add in self.view_bottom and self.view_left.
303 dest_x = x
304 dest_y = y
305
306 # Do math to calculate how to get the bullet to the destination.
307 # Calculation the angle in radians between the start points
308 # and end points. This is the angle the bullet will travel.
309 x_diff = dest_x - start_x
310 y_diff = dest_y - start_y
311 angle = math.atan2(y_diff, x_diff)
312
313 # What is the 1/2 size of this sprite, so we can figure out how far
314 # away to spawn the bullet
315 size = max(self.player_sprite.width, self.player_sprite.height) / 2
316
317 # Use angle to to spawn bullet away from player in proper direction
318 bullet.center_x += size * math.cos(angle)
319 bullet.center_y += size * math.sin(angle)
320
321 # Set angle of bullet
322 bullet.angle = math.degrees(angle)
323
324 # Gravity to use for the bullet
325 # If we don't use custom gravity, bullet drops too fast, or we have
326 # to make it go too fast.
327 # Force is in relation to bullet's angle.
328 bullet_gravity = (0, -BULLET_GRAVITY)
329
330 # Add the sprite. This needs to be done AFTER setting the fields above.
331 self.physics_engine.add_sprite(bullet,
332 mass=BULLET_MASS,
333 damping=1.0,
334 friction=0.6,
335 collision_type="bullet",
336 gravity=bullet_gravity,
337 elasticity=0.9)
338
339 # Add force to bullet
340 force = (BULLET_MOVE_FORCE, 0)
341 self.physics_engine.apply_force(bullet, force)
342
343 def on_update(self, delta_time):
344 """ Movement and game logic """
345
346 is_on_ground = self.physics_engine.is_on_ground(self.player_sprite)
347 # Update player forces based on keys pressed
348 if self.left_pressed and not self.right_pressed:
349 # Create a force to the left. Apply it.
350 if is_on_ground:
351 force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0)
352 else:
353 force = (-PLAYER_MOVE_FORCE_IN_AIR, 0)
354 self.physics_engine.apply_force(self.player_sprite, force)
355 # Set friction to zero for the player while moving
356 self.physics_engine.set_friction(self.player_sprite, 0)
357 elif self.right_pressed and not self.left_pressed:
358 # Create a force to the right. Apply it.
359 if is_on_ground:
360 force = (PLAYER_MOVE_FORCE_ON_GROUND, 0)
361 else:
362 force = (PLAYER_MOVE_FORCE_IN_AIR, 0)
363 self.physics_engine.apply_force(self.player_sprite, force)
364 # Set friction to zero for the player while moving
365 self.physics_engine.set_friction(self.player_sprite, 0)
366 else:
367 # Player's feet are not moving. Therefore up the friction so we stop.
368 self.physics_engine.set_friction(self.player_sprite, 1.0)
369
370 # Move items in the physics engine
371 self.physics_engine.step()
372
373 def on_draw(self):
374 """ Draw everything """
375 arcade.start_render()
376 self.wall_list.draw()
377 self.bullet_list.draw()
378 self.item_list.draw()
379 self.player_list.draw()
380
381def main():
382 """ Main method """
383 window = GameWindow(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
384 window.setup()
385 arcade.run()
386
387
388if __name__ == "__main__":
389 main()