Debian Codegraph @

doc/programming_guide/examplegame.rst

raw
1 .. _programming-guide-game:
2
3 In-depth game example
4 =====================
5
6 This tutorial will walk you through the steps of writing a simple Asteroids
7 clone. It is assumed that the reader is familiar with writing and running
8 Python programs. This is not a programming tutorial, but it should hopefully
9 be clear enough to follow even if you're a beginner. If you get stuck,
10 first have a look at the relevant sections of the programming guide.
11 The full source code can also be found in the `examples/game/` folder
12 of the pyglet source directory, which you can follow along with.
13 If anything is still not clear, let us know!
14
15 Basic graphics
16 --------------
17
18 Lets begin! The first version of our game will simply show a score of zero,
19 a label showing the name of the program, three randomly placed asteroids,
20 and the player’s ship. Nothing will move.
21
22 Setting up
23 ^^^^^^^^^^
24
25 First things first, make sure you have pyglet installed. Then, we will set
26 up the folder structure for our project. Since this example game is written
27 in stages, we will have several `version` folders at various stages of
28 development. We will also have a shared resource folder with the images,
29 called ‘resources,’ outside of the example folders. Each `version` folder
30 contains a Python file called `asteroid.py` which runs the game, as well as
31 a sub-folder named `game` where we will place additional modules; this is
32 where most of the logic will be. Your folder structure should look like this::
33
34 game/
35 resources/
36 (images go here)
37 version1/
38 asteroid.py
39 game/
40 __init__.py
41
42 Getting a window
43 ^^^^^^^^^^^^^^^^
44
45 To set up a window, simply `import pyglet`, create a new instance of
46 :class:`pyglet.window.Window`, and call `pyglet.app.run()`::
47
48 import pyglet
49 game_window = pyglet.window.Window(800, 600)
50
51 if __name__ == '__main__':
52 pyglet.app.run()
53
54 If you run the code above, you should see a window full of junk that
55 goes away when you press Esc. (What you are seeing is raw uninitialized
56 graphics memory).
57
58 Loading and displaying an image
59 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
60
61 Since our images will reside in a directory other than the example’s root
62 directory, we need to tell pyglet where to find them::
63
64 import pyglet
65 pyglet.resource.path = ['../resources']
66 pyglet.resource.reindex()
67
68 pyglet's :mod:`pyglet.resource` module takes all of the hard work out of
69 finding and loading game resources such as images, sounds, etc.. All that
70 you need to do is tell it where to look, and reindex it. In this example
71 game, the resource path starts with `../` because the resources folder is
72 on the same level as the `version1` folder. If we left it off, pyglet
73 would look inside `version1/` for the `resources/` folder.
74
75 Now that pyglet’s resource module is initialized, we can easily load the images
76 with the :func:`~pyglet.resource.image` function of the resource module::
77
78 player_image = pyglet.resource.image("player.png")
79 bullet_image = pyglet.resource.image("bullet.png")
80 asteroid_image = pyglet.resource.image("asteroid.png")
81
82 Centering the images
83 ^^^^^^^^^^^^^^^^^^^^
84
85 Pyglet will draw and position all images from their lower left corner by
86 default. We don’t want this behavior for our images, which need to rotate
87 around their centers. All we have to do to achieve this is to set their
88 anchor points. Lets create a function to simplify this::
89
90 def center_image(image):
91 """Sets an image's anchor point to its center"""
92 image.anchor_x = image.width // 2
93 image.anchor_y = image.height // 2
94
95 Now we can just call center_image() on all of our loaded images::
96
97 center_image(player_image)
98 center_image(bullet_image)
99 center_image(asteroid_image)
100
101 Remember that the center_image() function must be defined before it can be
102 called at the module level. Also, note that zero degrees points directly
103 to the right in pyglet, so the images are all drawn with their front
104 pointing to the right.
105
106 To access the images from asteroid.py, we need to use something like
107 `from game import resources`, which we’ll get into in the next section.
108
109 Initializing objects
110 ^^^^^^^^^^^^^^^^^^^^
111
112 We want to put some labels at the top of the window to give the player some
113 information about the score and the current difficulty level. Eventually,
114 we will have a score display, the name of the level, and a row of icons
115 representing the number of remaining lives.
116
117 Making the labels
118 ^^^^^^^^^^^^^^^^^
119
120 To make a text label in pyglet, just initialize a :class:`pyglet.text.Label` object::
121
122 score_label = pyglet.text.Label(text="Score: 0", x=10, y=575)
123 level_label = pyglet.text.Label(text="My Amazing Game",
124 x=game_window.width//2, y=575, anchor_x='center')
125
126 Notice that the second label is centered using the anchor_x attribute.
127
128 Drawing the labels
129 ^^^^^^^^^^^^^^^^^^
130
131 We want pyglet to run some specific code whenever the window is drawn.
132 An :meth:`~pyglet.window.Window.on_draw` event is dispatched to the window
133 to give it a chance to redraw its contents. pyglet provides several ways
134 to attach event handlers to objects; a simple way is to use a decorator::
135
136 @game_window.event
137 def on_draw():
138 # draw things here
139
140 The `@game_window.event` decorator lets the Window instance know that our
141 `on_draw()` function is an event handler.
142 The :meth:`~pyglet.window.Window.on_draw` event is fired whenever
143 - you guessed it - the window needs to be redrawn. Other events include
144 :meth:`~pyglet.window.Window.on_mouse_press` and
145 :meth:`~pyglet.window.Window.on_key_press`.
146
147 Now we can fill the method with the functions necessary to draw our labels.
148 Before we draw anything, we should clear the screen. After that, we can
149 simply call each object’s draw() function::
150
151 @game_window.event
152 def on_draw():
153 game_window.clear()
154
155 level_label.draw()
156 score_label.draw()
157
158 Now when you run asteroid.py, you should get a window with a score of zero
159 in the upper left corner and a centered label reading “My Amazing Game”
160 at the top of the screen.
161
162 Making the player and asteroid sprites
163 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
164
165 The player should be an instance or subclass of :class:`pyglet.sprite.Sprite`,
166 like so::
167
168 from game import resources
169 ...
170 player_ship = pyglet.sprite.Sprite(img=resources.player_image, x=400, y=300)
171
172 To get the player to draw on the screen, add a line to `on_draw()`::
173
174 @game_window.event
175 def on_draw():
176 ...
177 player_ship.draw()
178
179 Loading the asteroids is a little more complicated, since we’ll need to place
180 more than one at random locations that don’t immediately collide with the
181 player. Let’s put the loading code in a new game submodule called load.py::
182
183 import pyglet
184 import random
185 from . import resources
186
187 def asteroids(num_asteroids):
188 asteroids = []
189 for i in range(num_asteroids):
190 asteroid_x = random.randint(0, 800)
191 asteroid_y = random.randint(0, 600)
192 new_asteroid = pyglet.sprite.Sprite(img=resources.asteroid_image,
193 x=asteroid_x, y=asteroid_y)
194 new_asteroid.rotation = random.randint(0, 360)
195 asteroids.append(new_asteroid)
196 return asteroids
197
198 All we are doing here is making a few new sprites with random positions.
199 There’s still a problem, though - an asteroid might randomly be placed
200 exactly where the player is, causing immediate death. To fix this issue,
201 we’ll need to be able to tell how far away new asteroids are from the player.
202 Here is a simple function to calculate that distance::
203
204 import math
205 ...
206 def distance(point_1=(0, 0), point_2=(0, 0)):
207 """Returns the distance between two points"""
208 return math.sqrt((point_1[0] - point_2[0]) ** 2 + (point_1[1] - point_2[1]) ** 2)
209
210 To check new asteroids against the player’s position, we need to pass the
211 player’s position into the `asteroids()` function and keep regenerating
212 new coordinates until the asteroid is far enough away. pyglet sprites
213 keep track of their position both as a tuple (Sprite.position) and as
214 x, y, and z attributes (Sprite.x, Sprite.y, Sprite.z). To keep our code
215 short, we’ll just pass the position tuple into the function. We're not using
216 the z value, so we just use a throwaway variable for that::
217
218 def asteroids(num_asteroids, player_position):
219 asteroids = []
220 for i in range(num_asteroids):
221 asteroid_x, asteroid_y, _ = player_position
222 while distance((asteroid_x, asteroid_y), player_position) < 100:
223 asteroid_x = random.randint(0, 800)
224 asteroid_y = random.randint(0, 600)
225 new_asteroid = pyglet.sprite.Sprite(
226 img=resources.asteroid_image, x=asteroid_x, y=asteroid_y)
227 new_asteroid.rotation = random.randint(0, 360)
228 asteroids.append(new_asteroid)
229 return asteroids
230
231 For each asteroid, it chooses random positions until it finds one away from
232 the player, creates the sprite, and gives it a random rotation. Each asteroid
233 is appended to a list, which is returned.
234
235 Now you can load three asteroids like this::
236
237 from game import resources, load
238 ...
239 asteroids = load.asteroids(3, player_ship.position)
240
241 The asteroids variable now contains a list of sprites. Drawing them on the
242 screen is as simple as it was for the player’s ship - just call their
243 :meth:`~pyglet.sprite.Sprite.draw` methods:
244
245 .. code:: python
246
247 @game_window.event
248 def on_draw():
249 ...
250 for asteroid in asteroids:
251 asteroid.draw()
252
253 This wraps up the first section. Your "game" doesn't do much of anything yet,
254 but we'll get to that in the following sections. You may want to look over
255 the `examples/game/version1` folder in the pyglet source to review what we've
256 done, and to find a functional copy.
257
258
259 Basic motion
260 ------------
261
262 In the second version of the example, we’ll introduce a simpler, faster way
263 to draw all of the game objects, as well as add row of icons indicating the
264 number of lives left. We’ll also write some code to make the player and the
265 asteroids obey the laws of physics.
266
267 Drawing with batches
268 ^^^^^^^^^^^^^^^^^^^^
269
270 Calling each object’s `draw()` method manually can become cumbersome and
271 tedious if there are many different kinds of objects. It's also very
272 inefficient if you need to draw a large number of objects. The pyglet
273 :class:`pyglet.graphics.Batch` class simplifies drawing by letting you draw
274 all your objects with a single function call. All you need to do is create
275 a batch, pass it into each object you want to draw, and call the batch’s
276 :meth:`~pyglet.graphics.Batch.draw` method.
277
278 To create a new batch, simply create an instance of :class:`pyglet.graphics.Batch`::
279
280 main_batch = pyglet.graphics.Batch()
281
282 To make an object a member of a batch, just pass the batch into its
283 constructor as the batch keyword argument::
284
285 score_label = pyglet.text.Label(text="Score: 0", x=10, y=575, batch=main_batch)
286
287 Add the batch keyword argument to each graphical object created in asteroid.py.
288
289 To use the batch with the asteroid sprites, we’ll need to pass the batch into
290 the `game.load.asteroid()` function, then just add it as a keyword argument to
291 each new sprite. Update the function::
292
293 def asteroids(num_asteroids, player_position, batch=None):
294 ...
295 new_asteroid = pyglet.sprite.Sprite(img=resources.asteroid_image,
296 x=asteroid_x, y=asteroid_y,
297 batch=batch)
298
299 And update the place where it’s called::
300
301 asteroids = load.asteroids(3, player_ship.position, main_batch)
302
303 Now you can replace those five lines of `draw()` calls with just one::
304
305 main_batch.draw()
306
307 Now when you run asteroid.py, it should look exactly the same.
308
309 Displaying little ship icons
310 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
311
312 To show how many lives the player has left, we’ll need to draw a little row
313 of icons in the upper right corner of the screen. Since we’ll be making more
314 than one using the same template, let’s create a function called
315 `player_lives()` in the `load` module to generate them. The icons should look
316 the same as the player’s ship. We could create a scaled version using an
317 image editor, or we could just let pyglet do the scaling. I don’t know about
318 you, but I prefer the option that requires less work.
319
320 The function for creating the icons is almost exactly the same as the one for
321 creating asteroids. For each icon we just create a sprite, give it a position
322 and scale, and append it to the return list::
323
324 def player_lives(num_icons, batch=None):
325 player_lives = []
326 for i in range(num_icons):
327 new_sprite = pyglet.sprite.Sprite(img=resources.player_image,
328 x=785-i*30, y=585, batch=batch)
329 new_sprite.scale = 0.5
330 player_lives.append(new_sprite)
331 return player_lives
332
333 The player icon is 50x50 pixels, so half that size will be 25x25. We want to
334 put a little bit of space between each icon, so we create them at 30-pixel
335 intervals starting from the right side of the screen and moving to the left.
336 Note that like the `asteroids()` function, `player_lives()` takes a `batch`
337 argument.
338
339 Making things move
340 ^^^^^^^^^^^^^^^^^^
341
342 The game would be pretty boring if nothing on the screen ever moved. To
343 achieve motion, we’ll need to write our own set of classes to handle
344 frame-by-frame movement calculations. We’ll also need to write a Player
345 class to respond to keyboard input.
346
347 **Creating the basic motion class**
348
349 Since every visible object is represented by at least one Sprite, we may as
350 well make our basic motion class a subclass of pyglet.sprite.Sprite. Another
351 approach would be to have our class have a sprite attribute.
352
353 Create a new game submodule called physicalobject.py and declare a
354 PhysicalObject class. The only new attributes we’ll be adding will store the
355 object’s velocity, so the constructor will be simple::
356
357 class PhysicalObject(pyglet.sprite.Sprite):
358
359 def __init__(self, *args, **kwargs):
360 super().__init__(*args, **kwargs)
361
362 self.velocity_x, self.velocity_y = 0.0, 0.0
363
364 Each object will need to be updated every frame, so let’s write an `update()`
365 method::
366
367 def update(self, dt):
368 self.x += self.velocity_x * dt
369 self.y += self.velocity_y * dt
370
371 What’s dt? It’s the "delta time", or "time step". Game frames are not
372 instantaneous, and they don’t always take equal amounts of time to draw.
373 If you’ve ever tried to play a modern game on an old machine, you know
374 that frame rates can jump all over the place. There are a number of
375 ways to deal with this problem, the simplest one being to just multiply all
376 time-sensitive operations by dt. I’ll show you how this value is calculated
377 later.
378
379 If we give objects a velocity and just let them go, they will fly off the
380 screen before long. Since we’re making an Asteroids clone, we would rather
381 they just wrapped around the screen. Here is a simple function that
382 accomplishes the goal::
383
384 def check_bounds(self):
385 min_x = -self.image.width / 2
386 min_y = -self.image.height / 2
387 max_x = 800 + self.image.width / 2
388 max_y = 600 + self.image.height / 2
389 if self.x < min_x:
390 self.x = max_x
391 elif self.x > max_x:
392 self.x = min_x
393 if self.y < min_y:
394 self.y = max_y
395 elif self.y > max_y:
396 self.y = min_y
397
398 As you can see, it simply checks to see if objects are no longer visible on
399 the screen, and if so, it moves them to the other side of the screen.
400 To make every PhysicalObject use this behavior, add a call to
401 `self.check_bounds()` at the end of `update()`.
402
403 To make the asteroids use our new motion code, just import the physicalobject
404 module and change the `new_asteroid = ...` line to create a new
405 `PhysicalObject` instead of a `Sprite`. You’ll also want to give them a random
406 initial velocity. Here is the new, improved `load.asteroids()` function:
407
408 .. code:: python
409
410 def asteroids(num_asteroids, player_position, batch=None):
411 ...
412 new_asteroid = physicalobject.PhysicalObject(...)
413 new_asteroid.rotation = random.randint(0, 360)
414 new_asteroid.velocity_x = random.random()*40
415 new_asteroid.velocity_y = random.random()*40
416 ...
417
418 Writing the game update function
419 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
420
421 To call each object’s `update()` method every frame, we first need to have a
422 list of those objects. For now, we can just declare it after setting up all
423 the other objects::
424
425 game_objects = [player_ship] + asteroids
426
427 Now we can write a simple function to iterate over the list::
428
429 def update(dt):
430 for obj in game_objects:
431 obj.update(dt)
432
433 The `update()` function takes a `dt` parameter because it is still not the
434 source of the actual time step.
435
436 Calling the update() function
437 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
438
439 We need to update the objects at least once per frame. What’s a frame? Well,
440 most screens have a maximum refresh rate of 60 hertz. If we set our loop to
441 run at exactly 60 hertz, though, the motion will look a little jerky because
442 it won’t match the screen exactly. Instead, we can have it
443 update twice as fast, 120 times per second, to get smooth animation.
444
445 The best way to call a function 120 times per second is to ask pyglet to do it.
446 The :mod:`pyglet.clock` module contains a number of ways to call functions
447 periodically or at some specified time in the future. The one we want is
448 :meth:`pyglet.clock.schedule_interval`::
449
450 pyglet.clock.schedule_interval(update, 1/120.0)
451
452 Putting this line above `pyglet.app.run()` in the if `__name__ == '__main__'`
453 block tells pyglet to call `update()` 120 times per second. Pyglet will pass
454 in the elapsed time, i.e. `dt`, as the only parameter.
455
456 Now when you run asteroid.py, you should see your formerly static asteroids
457 drifting serenely across the screen, reappearing on the other side when they
458 slide off the edge.
459
460 Writing the Player class
461 ^^^^^^^^^^^^^^^^^^^^^^^^
462
463 In addition to obeying the basic laws of physics, the player object needs to
464 respond to keyboard input. Start by creating a `game.player` module,
465 importing the appropriate modules, and subclassing `PhysicalObject`::
466
467 from . import physicalobject, resources
468
469
470 class Player(physicalobject.PhysicalObject):
471
472 def __init__(self, *args, **kwargs):
473 super().__init__(img=resources.player_image, *args, **kwargs)
474
475 So far, the only difference between a Player and a PhysicalObject is that a
476 Player will always have the same image. But Player objects need a couple
477 more attributes. Since the ship will always thrust with the same force in
478 whatever direction it points, we’ll need to define a constant for the
479 magnitude of that force. We should also define a constant for the ship’s
480 rotation speed::
481
482 self.thrust = 300.0
483 self.rotate_speed = 200.0
484
485 Now we need to get the class to respond to user input. Pyglet uses an
486 event-based approach to input, sending key press and key release events
487 to registered event handlers. But we want to use a polling approach in
488 this example, checking periodically if a key is down. One way to accomplish
489 that is to maintain a dictionary of keys. First, we need to initialize the
490 dictionary in the constructor::
491
492 self.keys = dict(left=False, right=False, up=False)
493
494 Then we need to write two methods, `on_key_press()` and `on_key_release()`.
495 When pyglet checks a new event handler, it looks for these two methods,
496 among others::
497
498 import math
499 from pyglet.window import key
500 from . import physicalobject, resources
501
502 class Player(physicalobject.PhysicalObject)
503
504 def on_key_press(self, symbol, modifiers):
505 if symbol == key.UP:
506 self.keys['up'] = True
507 elif symbol == key.LEFT:
508 self.keys['left'] = True
509 elif symbol == key.RIGHT:
510 self.keys['right'] = True
511
512 def on_key_release(self, symbol, modifiers):
513 if symbol == key.UP:
514 self.keys['up'] = False
515 elif symbol == key.LEFT:
516 self.keys['left'] = False
517 elif symbol == key.RIGHT:
518 self.keys['right'] = False
519
520 That looks pretty cumbersome. There’s a better way to do it which we’ll see
521 later, but for now, this version serves as a good demonstration of pyglet’s
522 event system.
523
524 The last thing we need to do is write the `update()` method. It follows the
525 same behavior as a PhysicalObject plus a little extra, so we’ll need to call
526 PhysicalObject's `update()` method and then respond to input::
527
528 def update(self, dt):
529 super().update(dt)
530
531 if self.keys['left']:
532 self.rotation -= self.rotate_speed * dt
533 if self.keys['right']:
534 self.rotation += self.rotate_speed * dt
535
536 Pretty simple so far. To rotate the player, we just add the rotation speed
537 to the angle, multiplied by dt to account for time. Note that Sprite objects’
538 rotation attributes are in degrees, with clockwise as the positive direction.
539 This means that you need to call `math.degrees()` or `math.radians()` and make
540 the result negative whenever you use Python’s built-in math functions with
541 the Sprite class, since those functions use radians instead of degrees, and
542 their positive direction is counter-clockwise. The code to make the ship
543 thrust forward uses an example of such a conversion::
544
545 if self.keys['up']:
546 angle_radians = -math.radians(self.rotation)
547 force_x = math.cos(angle_radians) * self.thrust * dt
548 force_y = math.sin(angle_radians) * self.thrust * dt
549 self.velocity_x += force_x
550 self.velocity_y += force_y
551
552 First, we convert the angle to radians so that `math.cos()` and `math.sin()`
553 will get the correct values. Then we apply some simple physics to modify the
554 ship’s X and Y velocity components and push the ship in the right direction.
555
556 We now have a complete Player class. If we add it to the game and tell pyglet
557 that it’s an event handler, we should be good to go.
558
559 Integrating the player class
560 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
561
562 The first thing we need to do is make player_ship an instance of Player::
563
564 from game import player
565 ...
566 player_ship = player.Player(x=400, y=300, batch=main_batch)
567
568 Now we need to tell pyglet that player_ship is an event handler. To do that,
569 we need to push it onto the event stack with `game_window.push_handlers()`::
570
571 game_window.push_handlers(player_ship)
572
573 That’s it! Now you should be able to run the game and move the player with the
574 arrow keys.
575
576
577 Giving the player something to do
578 ---------------------------------
579
580 In any good game, there needs to be something working against the player.
581 In the case of Asteroids, it’s the threat of collision with, well, an asteroid.
582 Collision detection requires a lot of infrastructure in the code, so this
583 section will focus on making it work. We’ll also clean up the
584 player class and show some visual feedback for thrusting.
585
586 Simplifying player input
587 ^^^^^^^^^^^^^^^^^^^^^^^^
588
589 Right now, the Player class handles all of its own keyboard events.
590 It spends 13 lines of code doing nothing but setting boolean values in a
591 dictionary. One would think that there would be a better way, and there is:
592 :class:`pyglet.window.key.KeyStateHandler`. This handy class automatically
593 does what we have been doing manually: it tracks the state of every key on the
594 keyboard.
595
596 To start using it, we need to initialize it and push it onto the event stack
597 instead of the Player class. First, let’s add it to Player‘s constructor::
598
599 self.key_handler = key.KeyStateHandler()
600
601 We also need to push the key_handler object onto the event stack. Keep pushing
602 the player_ship object in addition to its key handler, because we’ll need it
603 to keep handling key press and release events later::
604
605 game_window.push_handlers(player_ship.key_handler)
606
607 Since Player now relies on key_handler to read the keyboard, we need to change
608 the `update()` method to use it. The only changes are in the if conditions::
609
610 if self.key_handler[key.LEFT]:
611 ...
612 if self.key_handler[key.RIGHT]:
613 ...
614 if self.key_handler[key.UP]:
615 ...
616
617 Now we can remove the `on_key_press()` and `on_key_release()` methods
618 from the class. It’s just that simple. If you need to see a list of key
619 constants, you can check the API documentation under
620 :class:`pyglet.window.key`.
621
622 Adding an engine flame
623 ^^^^^^^^^^^^^^^^^^^^^^
624
625 Without visual feedback, it can be difficult to tell if the ship is actually
626 thrusting forward or not, especially for an observer just watching someone
627 else play the game. One way to provide visual feedback is to show an engine
628 flame behind the player while the player is thrusting.
629
630 Loading the flame image
631 ^^^^^^^^^^^^^^^^^^^^^^^
632
633 The player will now be made of two sprites. There’s nothing preventing us
634 from letting a Sprite own another Sprite, so we’ll just give Player an
635 engine_sprite attribute and update it every frame. For our purposes,
636 this approach will be the simplest and most scalable.
637
638 To make the flame draw in the correct position, we could either do some
639 complicated math every frame, or we could just move the image’s anchor point.
640 First, load the image in resources.py::
641
642 engine_image = pyglet.resource.image("engine_flame.png")
643
644 To get the flame to draw behind the player, we need to move the flame image’s
645 center of rotation to the right, past the end of the image.
646 To do that, we just set its `anchor_x` and `anchor_y` attributes::
647
648 engine_image.anchor_x = engine_image.width * 1.5
649 engine_image.anchor_y = engine_image.height / 2
650
651 Now the image is ready to be used by the player class. If you’re still
652 confused about anchor points, experiment with the values for engine_image’s
653 anchor point when you finish this section.
654
655 Creating and drawing the flame
656 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
657
658 The engine sprite needs to be initialized with all the same arguments as
659 Player, except that it needs a different image and must be initially invisible.
660 The code for creating it belongs in `Player.__init__()` and is very
661 straightforward::
662
663 self.engine_sprite = pyglet.sprite.Sprite(img=resources.engine_image, *args, **kwargs)
664 self.engine_sprite.visible = False
665
666 To make the engine sprite appear only while the player is thrusting, we need
667 to add some logic to the if `self.key_handler[key.UP]` block in the `update()`
668 method::
669
670 if self.key_handler[key.UP]:
671 ...
672 self.engine_sprite.visible = True
673 else:
674 self.engine_sprite.visible = False
675
676 To make the sprite appear at the player’s position, we also need to update
677 its position and rotation attributes::
678
679 if self.key_handler[key.UP]:
680 ...
681 self.engine_sprite.rotation = self.rotation
682 self.engine_sprite.x = self.x
683 self.engine_sprite.y = self.y
684 self.engine_sprite.visible = True
685 else:
686 self.engine_sprite.visible = False
687
688 Cleaning up after death
689 ^^^^^^^^^^^^^^^^^^^^^^^
690
691 When the player is inevitably smashed to bits by an asteroid, he will
692 disappear from the screen. However, simply removing the Player instance
693 from the game_objects list is not enough for it to be removed from the
694 graphics batch. To do that, we need to call its `delete()` method.
695 Normally a Sprite‘s own `delete()` method will work fine without modifications,
696 but our subclass has its own child Sprite (the engine flame) which must
697 also be deleted when the Player instance is deleted. To get both to die
698 gracefully, we must write a simple but slightly enhanced `delete()` method::
699
700 def delete(self):
701 self.engine_sprite.delete()
702 super().delete()
703
704 The Player class is now cleaned up and ready to go.
705
706 Checking For collisions
707 ^^^^^^^^^^^^^^^^^^^^^^^
708
709 To make objects disappear from the screen, we’ll need to manipulate the game
710 objects list. Every object will need to check every other object’s position
711 against its own, and each object will have to decide whether or not it should
712 be removed from the list. The game loop will then check for dead objects
713 and remove them from the list.
714
715 Checking all object pairs
716 ^^^^^^^^^^^^^^^^^^^^^^^^^
717
718 We need to check every object against every other object. The simplest
719 method is to use nested loops. This method will be inefficient for a large
720 number of objects, but it will work for our purposes. We can use one easy
721 optimization and avoid checking the same pair of objects twice.
722 Here’s the setup for the loops, which belongs in `update()`.
723 It simply iterates over all object pairs without doing anything::
724
725 for i in range(len(game_objects)):
726 for j in range(i+1, len(game_objects)):
727 obj_1 = game_objects[i]
728 obj_2 = game_objects[j]
729
730 We’ll need a way to check if an object has already been killed. We could go
731 over to PhysicalObject right now and put it in, but let’s keep working on
732 the game loop and implement the method later. For now, we’ll just assume that
733 everything in game_objects has a dead attribute which will be False
734 until the class sets it to True, at which point it will be ignored and
735 eventually removed from the list.
736
737 To perform the actual check, we’ll also need to call two more methods that
738 don’t exist yet. One method will determine if the two objects actually collide,
739 and the other method will give each object an opportunity to respond to
740 the collision. The checking code itself is easy to understand,
741 so I won’t bother you with further explanations::
742
743 if not obj_1.dead and not obj_2.dead:
744 if obj_1.collides_with(obj_2):
745 obj_1.handle_collision_with(obj_2)
746 obj_2.handle_collision_with(obj_1)
747
748 Now all that remains is for us to go through the list and remove dead objects::
749
750 for to_remove in [obj for obj in game_objects if obj.dead]:
751 to_remove.delete()
752 game_objects.remove(to_remove)
753
754 As you can see, it simply calls the object’s `delete()` method to remove it
755 from any batches, then it removes it from the list. If you haven’t used list
756 comprehensions much, the above code might look like it’s removing objects
757 from the list while traversing it. Fortunately, the list comprehension is
758 evaluated before the loop actually runs, so there should be no problems.
759
760 Implementing the collision functions
761 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
762
763 We need to add three things to the PhysicalObject class: the dead attribute,
764 the `collides_with()` method, and the `handle_collision_with()` method.
765 The `collides_with()` method will need to use the `distance()` function,
766 so let’s start by moving that function into its own submodule of game,
767 called util.py::
768
769 import pyglet, math
770
771 def distance(point_1=(0, 0), point_2=(0, 0)):
772 return math.sqrt(
773 (point_1[0] - point_2[0]) ** 2 +
774 (point_1[1] - point_2[1]) ** 2)
775
776 Remember to call from util import distance in load.py. Now we can write
777 `PhysicalObject.collides_with()` without duplicating code::
778
779 def collides_with(self, other_object):
780 collision_distance = self.image.width/2 + other_object.image.width/2
781 actual_distance = util.distance(self.position, other_object.position)
782
783 return (actual_distance <= collision_distance)
784
785 The collision handler function is even simpler, since for now we just want
786 every object to die as soon as it touches another object::
787
788 def handle_collision_with(self, other_object):
789 self.dead = True
790
791 One last thing: set self.dead = False in PhysicalObject.__init__().
792
793 And that’s it! You should be able to zip around the screen, engine blazing
794 away. If you hit something, both you and the thing you collided with should
795 disappear from the screen. There’s still no game, but we are clearly
796 making progress.
797
798
799 Collision response
800 ------------------
801
802 In this section, we’ll add bullets. This new feature will require us to
803 start adding things to the game_objects list during the game,
804 as well as have objects check each others’ types to make a decision about
805 whether or not they should die.
806
807 Adding objects during play
808 ^^^^^^^^^^^^^^^^^^^^^^^^^^
809
810 **How?**
811
812 We handled object removal with a boolean flag. Adding objects will be
813 a little bit more complicated. For one thing, an object can’t just say
814 “Add me to the list!” It has to come from somewhere.
815 For another thing, an object might want to add more than one other
816 object at a time.
817
818 There are a few ways to solve this problem. To avoid circular references,
819 keep our constructors nice and short, and avoid adding extra modules,
820 we’ll have each object keep a list of new child objects to be added to
821 game_objects. This approach will make it easy for any object in the game
822 to spawn more objects.
823
824 Tweaking the game loop
825 ^^^^^^^^^^^^^^^^^^^^^^
826
827 The simplest way to check objects for children and add those children to
828 the list is to add two lines of code to the game_objects loop.
829 We haven’t implemented the new_objects attribute yet, but when we do,
830 it will be a list of objects to add::
831
832 for obj in game_objects:
833 obj.update(dt)
834 game_objects.extend(obj.new_objects)
835 obj.new_objects = []
836
837 Unfortunately, this simple solution is problematic. It’s generally a
838 bad idea to modify a list while iterating over it. The fix is to simply
839 add new objects to a separate list, then add the objects in the separate
840 list to game_objects after we have finished iterating over it.
841
842 Declare a to_add list just above the loop and add new objects to it instead.
843 At the very bottom of `update()`, after the object removal code,
844 add the objects in to_add to game_objects::
845
846 ...collision...
847
848 to_add = []
849
850 for obj in game_objects:
851 obj.update(dt)
852 to_add.extend(obj.new_objects)
853 obj.new_objects = []
854
855 ...removal...
856
857 game_objects.extend(to_add)
858
859 Putting the attribute in PhysicalObject
860 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
861
862 As mentioned before, all we have to do is declare a new_objects attribute
863 in the PhysicalObject class::
864
865 def __init__(self, *args, **kwargs):
866 ....
867 self.new_objects = []
868
869 To add a new object, all we have to do is put something in new_objects,
870 and the main loop will see it, add it to the game_objects list,
871 and clear new_objects.
872
873 Adding bullets
874 ^^^^^^^^^^^^^^
875
876 **Writing the bullet class**
877
878 For the most part, bullets act like any other PhysicalObject, but they have
879 two differences, at least in this game: they only collide with some objects,
880 and they disappear from the screen after a couple of seconds to prevent the
881 player from flooding the screen with bullets.
882
883 First, make a new submodule of game called bullet.py and start a simple
884 subclass of PhysicalObject::
885
886 import pyglet
887 from . import physicalobject, resources
888
889 class Bullet(physicalobject.PhysicalObject):
890 """Bullets fired by the player"""
891
892 def __init__(self, *args, **kwargs):
893 super().__init__(
894 resources.bullet_image, *args, **kwargs)
895
896 To get bullets to disappear after a time, we could keep track of our own
897 age and lifespan attributes, or we could let pyglet do all the work for us.
898 I don’t know about you, but I prefer the second option.
899 First, we need to write a function to call at the end of a bullet’s life::
900
901 def die(self, dt):
902 self.dead = True
903
904 Now we need to tell pyglet to call it after half a second or so.
905 We can do this as soon as the object is initialized by adding a call to
906 :meth:`pyglet.clock.schedule_once` to the constructor::
907
908 def __init__(self, *args, **kwargs):
909 super().__init__(resources.bullet_image, *args, **kwargs)
910 pyglet.clock.schedule_once(self.die, 0.5)
911
912 There’s still more work to be done on the Bullet class, but before we
913 do any more work on the class itself, let’s get them on the screen.
914
915 Firing bullets
916 ^^^^^^^^^^^^^^
917
918 The Player class will be the only class that fires bullets,
919 so let’s open it up, import the bullet module, and add a bullet_speed attribute
920 to its constructor::
921
922 ...
923 from . import bullet
924
925 class Player(physicalobject.PhysicalObject):
926 def __init__(self, *args, **kwargs):
927 super().__init__(img=resources.player_image, *args, **kwargs)
928 ...
929 self.bullet_speed = 700.0
930
931 Now we can write the code to create a new bullet and send it hurling off
932 into space. First, we need to resurrect the on_key_press() event handler::
933
934 def on_key_press(self, symbol, modifiers):
935 if symbol == key.SPACE:
936 self.fire()
937
938 The `fire()` method itself will be a bit more complicated. Most of the
939 calculations will be very similar to the ones for thrusting, but there
940 will be some differences. We’ll need to spawn the bullet out at the
941 nose of the ship, not at its center. We’ll also need to add the ship’s
942 existing velocity to the bullet’s new velocity, or the bullets will
943 end up going slower than the ship if the player gets going fast enough.
944
945 As usual, convert to radians and reverse the direction::
946
947 def fire(self):
948 angle_radians = -math.radians(self.rotation)
949
950 Next, calculate the bullet’s position and instantiate it::
951
952 ship_radius = self.image.width/2
953 bullet_x = self.x + math.cos(angle_radians) * ship_radius
954 bullet_y = self.y + math.sin(angle_radians) * ship_radius
955 new_bullet = bullet.Bullet(bullet_x, bullet_y, batch=self.batch)
956
957 Set its velocity using almost the same equations::
958
959 bullet_vx = (
960 self.velocity_x +
961 math.cos(angle_radians) * self.bullet_speed
962 )
963 bullet_vy = (
964 self.velocity_y +
965 math.sin(angle_radians) * self.bullet_speed
966 )
967 new_bullet.velocity_x = bullet_vx
968 new_bullet.velocity_y = bullet_vy
969
970 Finally, add it to the new_objects list so that the main loop will pick it up
971 and add it to game_objects::
972
973 self.new_objects.append(new_bullet)
974
975 At this point, you should be able to fire bullets out of the front of your
976 ship. There’s just one problem: as soon as you fire, your ship disappears.
977 You may have noticed earlier that asteroids also disappear when they touch
978 each other. To fix this problem, we’ll need to start customizing
979 each class’s `handle_collision_with()` method.
980
981 Customizing collision behavior
982 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
983
984 There are five kinds of collisions in the current version of the game:
985 bullet-asteroid, bullet-player, asteroid-player, bullet-bullet,
986 and asteroid-asteroid. There would be many more in a more complex game.
987
988 In general, objects of the same type should not be destroyed when they collide,
989 so we can generalize that behavior in PhysicalObject. Other interactions will
990 require a little more work.
991
992 **Letting twins ignore each other**
993
994 To let two asteroids or two bullets pass each other by without a word of
995 acknowledgement (or a dramatic explosion), we just need to check if their
996 classes are equal in the PhysicalObject.handle_collision_with() method::
997
998 def handle_collision_with(self, other_object):
999 if other_object.__class__ == self.__class__:
1000 self.dead = False
1001 else:
1002 self.dead = True
1003
1004 There are a few other, more elegant ways to check for object equality in
1005 Python, but the above code gets the job done.
1006
1007 Customizing bullet collisions
1008 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1009
1010 Since bullet collision behavior can vary so wildly across objects, let’s add
1011 a reacts_to_bullets attribute to PhysicalObjects which the Bullet class can
1012 check to determine if it should register a collision or not.
1013 We should also add an is_bullet attribute so we can check the collision
1014 properly from both objects.
1015
1016 (These are not “good” design decisions, but they will work.)
1017
1018 First, initialize the reacts_to_bullets attribute to True in the
1019 PhysicalObject constructor::
1020
1021 class PhysicalObject(pyglet.sprite.Sprite):
1022 def __init__(self, *args, **kwargs):
1023 ...
1024 self.reacts_to_bullets = True
1025 self.is_bullet = False
1026 ...
1027
1028 class Bullet(physicalobject.PhysicalObject):
1029 def __init__(self, *args, **kwargs):
1030 ...
1031 self.is_bullet = True
1032
1033 Then, insert a bit of code in `PhysicalObject.collides_with()` to ignore
1034 bullets under the right circumstances::
1035
1036 def collides_with(self, other_object):
1037 if not self.reacts_to_bullets and other_object.is_bullet:
1038 return False
1039 if self.is_bullet and not other_object.reacts_to_bullets:
1040 return False
1041 ...
1042
1043 Finally, set self.reacts_to_bullets = False in Player.__init__(). The `Bullet`
1044 class is completely finished! Now let’s make something happen when a bullet
1045 hits an asteroid.
1046
1047 Making asteroids explode
1048 ^^^^^^^^^^^^^^^^^^^^^^^^
1049
1050 Asteroids is challenging to players because every time you shoot an asteroid,
1051 it turns into more asteroids. We need to mimic that behavior if we want our
1052 game to be any fun. We’ve already done most of the hard parts.
1053 All that remains is to make another subclass of PhysicalObject and write
1054 a custom `handle_collision_with()` method, along with a couple of maintenance
1055 tweaks.
1056
1057 Writing the asteroid class
1058 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1059
1060 Create a new submodule of game called asteroid.py. Write the usual constructor
1061 to pass a specific image to the superclass, passing along any other parameters::
1062
1063 import pyglet
1064 from . import resources, physicalobject
1065
1066 class Asteroid(physicalobject.PhysicalObject):
1067 def __init__(self, *args, **kwargs):
1068 super().__init__(resources.asteroid_image, *args, **kwargs)
1069
1070 Now we need to write a new `handle_collision_with()` method. It should create
1071 a random number of new, smaller asteroids with random velocities. However,
1072 it should only do that if it’s big enough. An asteroid should divide at most
1073 twice, and if we scale it down by half each time, then an asteroid should stop
1074 dividing when it’s 1/4 the size of a new asteroid.
1075
1076 We want to keep the old behavior of ignoring other asteroids, so start the
1077 method with a call to the superclass’s method::
1078
1079 def handle_collision_with(self, other_object):
1080 super().handle_collision_with(other_object)
1081
1082 Now we can say that if it’s supposed to die, and it’s big enough, then we
1083 should create two or three new asteroids with random rotations and velocities.
1084 We should add the old asteroid’s velocity to the new ones to make it look
1085 like they come from the same object::
1086
1087 import random
1088
1089 class Asteroid:
1090 def handle_collision_with(self, other_object):
1091 super().handle_collision_with(other_object)
1092 if self.dead and self.scale > 0.25:
1093 num_asteroids = random.randint(2, 3)
1094 for i in range(num_asteroids):
1095 new_asteroid = Asteroid(x=self.x, y=self.y, batch=self.batch)
1096 new_asteroid.rotation = random.randint(0, 360)
1097 new_asteroid.velocity_x = (random.random() * 70 + self.velocity_x)
1098 new_asteroid.velocity_y = (random.random() * 70 + self.velocity_y)
1099 new_asteroid.scale = self.scale * 0.5
1100 self.new_objects.append(new_asteroid)
1101
1102 While we’re here, let’s add a small graphical touch to the asteroids by making
1103 them rotate a little. To do that, we’ll add a rotate_speed attribute and give
1104 it a random value. Then we’ll write an `update()` method to apply that
1105 rotation every frame.
1106
1107 Add the attribute in the constructor::
1108
1109 def __init__(self, *args, **kwargs):
1110 super().__init__(resources.asteroid_image, *args, **kwargs)
1111 self.rotate_speed = random.random() * 100.0 - 50.0
1112
1113 Then write the update() method::
1114
1115 def update(self, dt):
1116 super().update(dt)
1117 self.rotation += self.rotate_speed * dt
1118
1119 The last thing we need to do is go over to load.py and have the asteroid()
1120 method create a new Asteroid instead of a PhysicalObject::
1121
1122 from . import asteroid
1123
1124 def asteroids(num_asteroids, player_position, batch=None):
1125 ...
1126 for i in range(num_asteroids):
1127 ...
1128 new_asteroid = asteroid.Asteroid(x=asteroid_x, y=asteroid_y, batch=batch)
1129 ...
1130 return asteroids
1131
1132 Now we’re looking at something resembling a game. It's simple, but all of
1133 the basics are there.
1134
1135
1136 Next steps
1137 ----------
1138
1139 So instead of walking you through a standard refactoring session,
1140 I’m going to leave it as an exercise for you to do the following::
1141
1142 * Make the Score counter mean something
1143 * Let the player restart the level if they die
1144 * Implement lives and a “Game Over” screen
1145 * Add particle effects
1146
1147 Good luck! With a little effort, you should be able to figure out most of
1148 these things on your own. If you have trouble, join us on the pyglet
1149 `Discord server <https://discord.gg/QXyegWe>`_.