Debian Codegraph @

examples/game/version3/asteroid.py

raw symbols SCIP
1 import pyglet
2 from game import load, player
3
4 # Set up a window
5 game_window = pyglet.window.Window(800, 600)
6
7 main_batch = pyglet.graphics.Batch()
8
9 # Set up the two top labels
10 score_label = pyglet.text.Label(text="Score: 0", x=10, y=575, batch=main_batch)
11 level_label = pyglet.text.Label(text="Version 3: Basic Collision",
12 x=400, y=575, anchor_x='center', batch=main_batch)
13
14 # Initialize the player sprite
15 player_ship = player.Player(x=400, y=300, batch=main_batch)
16
17 # Make three sprites to represent remaining lives
18 player_lives = load.player_lives(2, main_batch)
19
20 # Make three asteroids so we have something to shoot at
21 asteroids = load.asteroids(3, player_ship.position, main_batch)
22
23 # Store all objects that update each frame in a list
24 game_objects = [player_ship] + asteroids
25
26 # Tell the main window that the player object responds to events
27 game_window.push_handlers(player_ship.key_handler)
28
29
30 @game_window.event
31 def on_draw():
32 game_window.clear()
33 main_batch.draw()
34
35
36 def update(dt):
37 for obj in game_objects:
38 obj.update(dt)
39
40 # To avoid handling collisions twice, we employ nested loops of ranges.
41 # This method also avoids the problem of colliding an object with itself.
42 for i in range(len(game_objects)):
43 for j in range(i + 1, len(game_objects)):
44
45 obj_1 = game_objects[i]
46 obj_2 = game_objects[j]
47
48 # Make sure the objects haven't already been killed
49 if not obj_1.dead and not obj_2.dead:
50 if obj_1.collides_with(obj_2):
51 obj_1.handle_collision_with(obj_2)
52 obj_2.handle_collision_with(obj_1)
53
54 # Get rid of dead objects
55 for to_remove in [obj for obj in game_objects if obj.dead]:
56 # Remove the object from any batches it is a member of
57 to_remove.delete()
58
59 # Remove the object from our list
60 game_objects.remove(to_remove)
61
62
63 if __name__ == "__main__":
64 # Update the game 120 times per second
65 pyglet.clock.schedule_interval(update, 1 / 120.0)
66
67 # Tell pyglet to do its thing
68 pyglet.app.run()