Debian Codegraph @

examples/game/version4/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 4: Bullets and Structure",
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 # Add any specified event handlers to the event handler stack
27 for obj in game_objects:
28 for handler in obj.event_handlers:
29 game_window.push_handlers(handler)
30
31
32 @game_window.event
33 def on_draw():
34 game_window.clear()
35 main_batch.draw()
36
37
38 def update(dt):
39 # To avoid handling collisions twice, we employ nested loops of ranges.
40 # This method also avoids the problem of colliding an object with itself.
41 for i in range(len(game_objects)):
42 for j in range(i + 1, len(game_objects)):
43
44 obj_1 = game_objects[i]
45 obj_2 = game_objects[j]
46
47 # Make sure the objects haven't already been killed
48 if not obj_1.dead and not obj_2.dead:
49 if obj_1.collides_with(obj_2):
50 obj_1.handle_collision_with(obj_2)
51 obj_2.handle_collision_with(obj_1)
52
53 # Let's not modify the list while traversing it
54 to_add = []
55
56 for obj in game_objects:
57 obj.update(dt)
58 to_add.extend(obj.new_objects)
59 obj.new_objects = []
60
61 # Get rid of dead objects
62 for to_remove in [obj for obj in game_objects if obj.dead]:
63 # If the dying object spawned any new objects, add those to the game_objects list later
64 to_add.extend(obj.new_objects)
65
66 # Remove the object from any batches it is a member of
67 to_remove.delete()
68
69 # Remove the object from our list
70 game_objects.remove(to_remove)
71
72 # Add new objects to the list
73 game_objects.extend(to_add)
74
75
76 if __name__ == "__main__":
77 # Update the game 120 times per second
78 pyglet.clock.schedule_interval(update, 1 / 120.0)
79
80 # Tell pyglet to do its thing
81 pyglet.app.run()