Debian Codegraph @

doc/introduction.rst

raw
1 Introduction to Pygame Zero
2 ===========================
3
4 .. highlight:: python
5 :linenothreshold: 5
6
7 Creating a window
8 -----------------
9
10 First, create an empty file called ``intro.py``.
11
12 Verify that this runs and creates a blank window by running ::
13
14 pgzrun intro.py
15
16 Everything in Pygame Zero is optional; a blank file is a valid Pygame Zero
17 script!
18
19 You can quit the game by clicking on the window's close button or by pressing
20 ``Ctrl-Q`` (``⌘-Q`` on Mac). If the game stops responding for any reason, you
21 may need to terminate it by pressing ``Ctrl-C`` in your Terminal window.
22
23
24 Drawing a background
25 --------------------
26
27 Next, let's add a :func:`draw` function and set window dimensions. Pygame Zero
28 will call this function whenever it needs to paint the screen.
29
30 In ``intro.py``, add the following::
31
32 WIDTH = 300
33 HEIGHT = 300
34
35 def draw():
36 screen.fill((128, 0, 0))
37
38 Re-run ``pgzrun intro.py`` and the screen should now be a reddish square!
39
40 What is this code doing?
41
42 ``WIDTH`` and ``HEIGHT`` control the width and height of your window. The code
43 sets the window size to be 300 pixels in each dimension.
44
45 ``screen`` is a built-in that represents the window display. It has a
46 :ref:`range of methods for drawing sprites and shapes <screen>`. The
47 ``screen.fill()`` method call is filling the screen with a solid colour,
48 specified as a ``(red, green, blue)`` colour tuple. ``(128, 0, 0)`` will be a
49 medium-dark red. Try changing these values with numbers between 0 and 255
50 and see what colors you can create.
51
52 Let's set up a sprite that we can animate.
53
54
55 Draw a sprite
56 -------------
57
58 Before we can draw anything, we'll need to save an alien sprite to use. You can
59 right click on this one and save it ("Save Image As..." or similar).
60
61 .. image:: _static/alien.png
62
63 (This sprite has a transparency (or "alpha") channel, which is great for games!
64 But it's designed for a dark background, so you may not be able to see the
65 alien's space helmet until it is shown in the game).
66
67 .. tip::
68
69 You can find lots of free sprites, including this one, on `kenney.nl
70 <https://kenney.nl/assets?q=2d>`_. This one comes from the
71 `Platformer Art Deluxe pack
72 <https://kenney.nl/assets/platformer-art-deluxe>`_.
73
74 You need to save the file in the right place so that Pygame Zero can find it.
75 Create a directory called ``images`` and save the image into it as
76 ``alien.png``. Both of those must be lower case. Pygame Zero will complain
77 otherwise, to alert you to a potential cross-platform compatibility pitfall.
78
79 If you've done that, your project should look like this:
80
81 .. code-block:: none
82
83 .
84 ├── images/
85 │   └── alien.png
86 └── intro.py
87
88 ``images/`` is the standard directory that Pygame Zero will look in to find
89 your images.
90
91 There's a built-in class called :class:`Actor` that you can use to represent a
92 graphic to be drawn to the screen.
93
94 Let's define one now. Change the ``intro.py`` file to read::
95
96 alien = Actor('alien')
97 alien.pos = 100, 56
98
99 WIDTH = 500
100 HEIGHT = alien.height + 20
101
102 def draw():
103 screen.clear()
104 alien.draw()
105
106 Your alien should now be appearing on screen! By passing the string ``'alien'``
107 to the ``Actor`` class, it automatically loads the sprite, and has attributes
108 like positioning and dimensions. This allows us to set the ``HEIGHT`` of
109 the window based on the height of the alien.
110
111 The ``alien.draw()`` method draws the sprite to the screen at its current
112 position.
113
114 Moving the alien
115 ----------------
116
117 Let's set the alien off-screen; change the ``alien.pos`` line to read::
118
119 alien.topright = 0, 10
120
121 Note how you can assign to ``topright`` to move the alien actor by its
122 top-right corner. If the right-hand edge of the alien is at ``0``, the the
123 alien is just offscreen to the left. Now let's make it move. Add the following
124 code to the bottom of the file::
125
126 def update():
127 alien.left += 2
128 if alien.left > WIDTH:
129 alien.right = 0
130
131 Pygame Zero will call your :func:`update` function once every frame. Moving the
132 alien a small number of pixels every frame will cause it to slide across the
133 screen. Once it slides off the right-hand side of the screen, we reset it back
134 to the left.
135
136 Handling clicks
137 ---------------
138
139 Let's make the game do something when you click on the alien. To do this we
140 need to define a function called :func:`on_mouse_down`. Add this to the source
141 code::
142
143 def on_mouse_down(pos):
144 if alien.collidepoint(pos):
145 print("Eek!")
146 else:
147 print("You missed me!")
148
149 You should run the game and try clicking on and off the alien.
150
151 Pygame Zero is smart about how it calls your functions. If you don't define
152 your function to take a ``pos`` parameter, Pygame Zero will call it without
153 a position. There's also a ``button`` parameter for ``on_mouse_down``. So we
154 could have written::
155
156 def on_mouse_down():
157 print("You clicked!")
158
159 or::
160
161 def on_mouse_down(pos, button):
162 if button == mouse.LEFT and alien.collidepoint(pos):
163 print("Eek!")
164
165
166 Sounds and images
167 -----------------
168
169 Now let's make the alien appear hurt. Save these files:
170
171 * `alien_hurt.png <_static/alien_hurt.png>`_ - save this as ``alien_hurt.png``
172 in the ``images`` directory.
173 * `eep.wav <_static/eep.wav>`_ - create a directory called ``sounds`` and save
174 this as ``eep.wav`` in that directory.
175
176 Your project should now look like this:
177
178 .. code-block:: none
179
180 .
181 ├── images/
182 │   └── alien.png
183 │   └── alien_hurt.png
184 ├── sounds/
185 │   └── eep.wav
186 └── intro.py
187
188 ``sounds/`` is the standard directory that Pygame Zero will look in to find
189 your sound files.
190
191 Now let's change the ``on_mouse_down`` function to use these new resources::
192
193 def on_mouse_down(pos):
194 if alien.collidepoint(pos):
195 sounds.eep.play()
196 alien.image = 'alien_hurt'
197
198 Now when you click on the alien, you should hear a sound, and the sprite will
199 change to an unhappy alien.
200
201 There's a bug in this game though; the alien doesn't ever change back to a
202 happy alien (but the sound will play on each click). Let's fix this next.
203
204
205 Clock
206 -----
207
208 If you're familiar with Python outside of games programming, you might know the
209 ``time.sleep()`` method that inserts a delay. You might be tempted to write
210 code like this::
211
212 def on_mouse_down(pos):
213 if alien.collidepoint(pos):
214 sounds.eep.play()
215 alien.image = 'alien_hurt'
216 time.sleep(1)
217 alien.image = 'alien'
218
219 Unfortunately, this is not at all suitable for use in a game. ``time.sleep()``
220 blocks all activity; we want the game to go on running and animating. In fact
221 we need to return from ``on_mouse_down``, and let the game work out when to
222 reset the alien as part of its normal processing, all the while running your
223 ``draw()`` and ``update()`` methods.
224
225 This is not difficult with Pygame Zero, because it has a built-in
226 :class:`Clock` that can schedule functions to be called later.
227
228 First, let's "refactor" (ie. re-organise the code). We can create functions to
229 set the alien as hurt and also to change it back to normal::
230
231 def on_mouse_down(pos):
232 if alien.collidepoint(pos):
233 set_alien_hurt()
234
235
236 def set_alien_hurt():
237 alien.image = 'alien_hurt'
238 sounds.eep.play()
239
240
241 def set_alien_normal():
242 alien.image = 'alien'
243
244 This is not going to do anything different yet. ``set_alien_normal()`` won't be
245 called. But let's change ``set_alien_hurt()`` to use the clock, so that the
246 ``set_alien_normal()`` will be called a little while after. ::
247
248 def set_alien_hurt():
249 alien.image = 'alien_hurt'
250 sounds.eep.play()
251 clock.schedule_unique(set_alien_normal, 1.0)
252
253 ``clock.schedule_unique()`` will cause ``set_alien_normal()`` to be called
254 after ``1.0`` second. ``schedule_unique()`` also prevents the same function
255 being scheduled more than once, such as if you click very rapidly.
256
257 Try it, and you'll see the alien revert to normal after 1 second. Try clicking
258 rapidly and verify that the alien doesn't revert until 1 second after the last
259 click.
260
261
262 Summary
263 -------
264
265 We've seen how to load and draw sprites, play sounds, handle input events, and
266 use the built-in clock.
267
268 You might like to expand the game to keep score, or make the alien move more
269 erratically.
270
271 There are lots more features built in to make Pygame Zero easy to use. Check
272 out the :doc:`built in objects <builtins>` to learn how to use the rest of the
273 API.