You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/reST/tut/newbieguide.rst
+68-93Lines changed: 68 additions & 93 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -43,10 +43,12 @@ several source files. Write your own functions, and practice manipulating
43
43
numbers and characters; know how to convert between the two. Get to the point
44
44
where the syntax for using lists and dictionaries is second-nature -- you don't
45
45
want to have to run to the documentation every time you need to slice a list or
46
-
sort a set of keys. Resist the temptation to run to a mailing list,
47
-
comp.lang.python, or IRC when you run into trouble. Instead, fire up the
48
-
interpreter and play with the problem for a few hours. Print out the `Python
49
-
2.0 Quick Reference`_ and keep it by your computer.
46
+
sort a set of keys. Resist the temptation to ask for direct help online when
47
+
you run into trouble. Instead, fire up the interpreter and play with the
48
+
problem for a few hours, or use print statements and debugging tools to find out
49
+
what's going wrong in your code. Get into the habit of looking things up in the
50
+
official _Python Docs, and Googling error messages to figure out what they
51
+
mean.
50
52
51
53
This may sound incredibly dull, but the confidence you'll gain through your
52
54
familiarity with python will work wonders when it comes time to write your
@@ -60,8 +62,8 @@ Recognize which parts of pygame you really need.
60
62
Looking at the jumble of classes at the top of the pygame Documentation index
61
63
may be confusing. The important thing is to realize that you can do a great
62
64
deal with only a tiny subset of functions. Many classes you'll probably never
63
-
use -- in a year, I haven't touched the ``Channel``, ``Joystick``, ``cursors``,
64
-
``Userrect``, ``surfarray`` or ``version`` functions.
65
+
use -- in a year, I haven't touched the ``Channel``, ``Joystick``, ``cursors``,
66
+
``surfarray`` or ``version`` functions.
65
67
66
68
67
69
Know what a surface is.
@@ -123,93 +125,51 @@ output file had the same pixel format as the input file. If you're writing a
123
125
game, you need speed. Use ``convert()``.
124
126
125
127
126
-
Dirty rect animation.
127
-
---------------------
128
-
129
-
The most common cause of inadequate frame rates in pygame programs results from
130
-
misunderstanding the ``pygame.display.update()`` function. With pygame, merely
131
-
drawing something to the display surface doesn't cause it to appear on the
132
-
screen -- you need to call ``pygame.display.update()``. There are three ways
133
-
of calling this function:
134
-
135
-
136
-
* ``pygame.display.update()`` -- This updates the whole window (or the whole screen for fullscreen displays).
137
-
* ``pygame.display.flip()`` -- This does the same thing, and will also do the right thing if you're using ``double-buffered`` hardware acceleration, which you're not, so on to...
138
-
* ``pygame.display.update(a rectangle or some list of rectangles)`` -- This updates just the rectangular areas of the screen you specify.
139
-
140
-
141
-
Most people new to graphics programming use the first option -- they update the
142
-
whole screen every frame. The problem is that this is unacceptably slow for
143
-
most people. Calling ``update()`` takes 35 milliseconds on my machine, which
144
-
doesn't sound like much, until you realize that 1000 / 35 = 28 frames per
145
-
second *maximum*. And that's with no game logic, no blits, no input, no AI,
146
-
nothing. I'm just sitting there updating the screen, and 28 fps is my maximum
147
-
framerate. Ugh.
148
-
149
-
The solution is called 'dirty rect animation'. Instead of updating the whole
150
-
screen every frame, only the parts that changed since the last frame are
151
-
updated. I do this by keeping track of those rectangles in a list, then
152
-
calling ``update(the_dirty_rectangles)`` at the end of the frame. In detail
153
-
for a moving sprite, I:
154
-
155
-
* Blit a piece of the background over the sprite's current location, erasing it.
156
-
* Append the sprite's current location rectangle to a list called dirty_rects.
157
-
* Move the sprite.
158
-
* Draw the sprite at it's new location.
159
-
* Append the sprite's new location to my dirty_rects list.
160
-
* Call ``display.update(dirty_rects)``
161
-
162
-
The difference in speed is astonishing. Consider thatSolarWolf_ has dozens of
163
-
constantly moving sprites updating smoothly, and still has enough time left
164
-
over to display a parallax starfield in the background, and update that too.
165
-
166
-
There are two cases where this technique just won't work. The first is where
167
-
the whole window or screen really is being updated every frame -- think of a
168
-
smooth-scrolling engine like an overhead real-time strategy game or a
169
-
side-scroller. So what do you do in this case? Well, the short answer is --
170
-
don't write this kind of game in pygame. The long answer is to scroll in steps
171
-
of several pixels at a time; don't try to make scrolling perfectly smooth.
172
-
Your player will appreciate a game that scrolls quickly, and won't notice the
173
-
background jumping along too much.
174
-
175
-
A final note -- not every game requires high framerates. A strategic wargame
176
-
could easily get by on just a few updates per second -- in this case, the added
177
-
complexity of dirty rect animation may not be necessary.
178
-
179
-
180
-
There is NO rule six.
181
-
---------------------
182
-
128
+
Some advice you'll encounter is outdated, obsolete, or optional.
**Especially in pygame 2, because HWSURFACE now does nothing**
133
+
When you read older bits of pygame documentation or guides online, you may see
134
+
some emphasis on only updating portions of the screen that are dirty for the
135
+
sake of performance (in this context, "dirty" means the region has changed since
136
+
the previous frame was drawn).
188
137
189
-
If you've been looking at the various flags you can use with
190
-
``pygame.display.set_mode()``,you may have thought like this: `Hey,
191
-
HWSURFACE! Well, I want that -- who doesn'tlike hardware acceleration. Ooo...
192
-
DOUBLEBUF; well, that sounds fast, I guess I want that too!`. It's not
193
-
your fault; we've been trained by yearsof3-d gaming to believe that hardware
194
-
acceleration is good, and software rendering is slow.
138
+
Generally this entails calling ``display.update(dirty_rects)`` instead of
139
+
``display.flip()``,not having scrolling backgrounds, or even not clearing the
140
+
screen every frame because otherwise pygame supposedly can'thandle it. Some of
141
+
pygame's API is designed to support this paradigm as well (e.g.
142
+
``pygame.sprite.RenderUpdates``), which made a lotofsense in the early 2000s
143
+
when pygame was first released.
195
144
196
-
Unfortunately, hardware rendering comes with a long list of drawbacks:
145
+
In the current year though, even modest computers are powerful enough to refresh
146
+
the entire display once per frame at 60 FPS and beyond. You can have a moving
147
+
camera, or dynamic backgrounds and your game should run totally fine. CPUs are
148
+
more powerful nowadays, and you can use `display.flip()` without fear.
197
149
198
-
* It only works on some platforms. Windows machines can usually get hardware surfaces if you ask for them. Most other platforms can't. Linux, for example, may be able to provide a hardware surface if X4 is installed, if DGA2 is working properly, and if the moons are aligned correctly. If a hardware surface is unavailable, SDL will silently give you a software surface instead.
150
+
That being said though, there are still plenty of ways to accidentally tank your
151
+
game's performance with poorly optimized rendering logic. For example, even on
152
+
modern hardware it's probably too slow to call ``set_at`` once per pixel on the
153
+
display surface. Being mindful of performance is still something you'll have to
154
+
do.
199
155
200
-
* It only works fullscreen.
156
+
**HWSURFACE and DOUBLEBUF**
201
157
202
-
* It complicates per-pixel access. If you have a hardware surface, you need to Lock the surface before writing or reading individual pixel values on it. If you don't, Bad Things Happen. Then you need to quickly Unlock the surface again, before the OS gets all confused and starts to panic. Most of this process is automated for you in pygame, but it's something else to take into account.
158
+
These ``display.set_mode()`` flags do nothing in pygame 2. There's no reason to
159
+
use them anymore.
203
160
204
-
* You lose the mouse pointer. If you specify ``HWSURFACE`` (and actually get it), your pointer will usually just vanish (or worse, hang around in a half-there, half-not flickery state). You'll need to create a sprite to act as a manual mouse pointer, and you'll need to worry about pointer acceleration and sensitivity. What a pain.
161
+
** The Sprite class**
162
+
163
+
You don't need to use the built-in Sprite or Group classes if you don't want to.
164
+
If you watch a lot of tutorials it may seem like Sprite is the fundamental
165
+
"GameObject" of pygame, from which all other objects must derive, but in reality
166
+
it's pretty much just a wrapper around a rect and a surface, with some
167
+
convenience methods. You may find it more intuitive (and fun) to design your
168
+
game's core classes from scratch.
205
169
206
-
* It might be slower anyway. Many drivers are not accelerated for the types of drawing that we do, and since everything has to be blitted across the video bus (unless you can cram your source surface into video memory as well), it might end up being slower than software access anyway.
207
170
208
-
Hardware rendering has it's place. It works pretty reliably under Windows, so
209
-
if you're not interested in cross-platform performance, it may provide you with
210
-
a substantial speed increase. However, it comes at a cost -- increased
211
-
headaches and complexity. It's best to stick with good old reliable
212
-
``SWSURFACE`` until you're sure you know what you're doing.
171
+
There is NO rule six.
172
+
---------------------
213
173
214
174
215
175
Don't get distracted by side issues.
@@ -271,7 +231,9 @@ I'd need them.
271
231
Don't bother with pixel-perfect collision detection.
So you've got your sprites moving around, and you need to know whether or not they're bumping into one another. It's tempting to write something like the following:
234
+
So you've got your sprites moving around, and you need to know whether or not
235
+
they're bumping into one another. It's tempting to write something like the
236
+
following:
275
237
276
238
* Check to see if the rects are in collision. If they aren't, ignore them.
277
239
* For each pixel in the overlapping area, see if the corresponding pixels from both sprites are opaque. If so, there's a collision.
@@ -310,8 +272,8 @@ detects "chording" easily; that is, several states at the same time. If you
310
272
want to know whether the ``t`` and ``f`` keys are down at the same time, just
311
273
check::
312
274
313
-
if(key.get_pressed[K_t] and key.get_pressed[K_f]):
314
-
print"Yup!"
275
+
if key.get_pressed[K_t] and key.get_pressed[K_f]:
276
+
print("Yup!")
315
277
316
278
In the queue system, however, each keypress arrives in the queue as a
317
279
completely separate event, so you'd need to remember that the ``t`` key was
@@ -342,6 +304,14 @@ and it will fill the event queue with ``NOEVENTS``. Use ``set_blocked()`` to
342
304
select just those event types you're interested in -- your queue will be much
343
305
more manageable.
344
306
307
+
Another note about the event queue -- even if you don't want to use it, you must
308
+
still clear it periodically because it's still going to be filling up with events
309
+
in the background as the user presses keys and mouses over the window. On Windows,
310
+
if your game goes too long without clearing the queue, the operating system will
311
+
think it has frozen and show a "The application is not responding" message.
312
+
Iterating over ``event.get()`` or simply calling ``event.clear()`` once per frame
313
+
will avoid this.
314
+
345
315
346
316
Colorkey vs. Alpha.
347
317
-------------------
@@ -386,11 +356,14 @@ good that if your code is still slow, and you've done the things I've mentioned
386
356
above, then the problem lies in the way you're addressing your data in python.
387
357
Certain idioms are just going to be slow in python no matter what you do.
388
358
Luckily, python is a very clear language -- if a piece of code looks awkward or
389
-
unwieldy, chances are its speed can be improved, too. Read over `Python
390
-
Performance Tips`_ for some great advice on how you can improve the speed of
391
-
your code. That said, premature optimisation is the root of all evil; if it's
392
-
just not fast enough, don't torture the code trying to make it faster. Some
393
-
things are just not meant to be :)
359
+
unwieldy, chances are its speed can be improved, too. Read over `Why Pygame is
360
+
Slow`_ for some deeper insight into why pygame might be considered slower than
361
+
other frameworks/engines, and what that actually means in practice.
362
+
And if you're truly stumped by performance problems, profilers likecProfile_ or
363
+
SnakeViz_ can help identify bottlenecks (they'll tell you which parts of the
364
+
code are taking the longest to execute). That said, premature optimisation is
365
+
the root of all evil; if it's already fast enough, don't torture the code trying
366
+
to make it faster. If it's fast enough, let it be :)
394
367
395
368
396
369
There you go. Now you know practically everything I know about using pygame.
@@ -404,6 +377,8 @@ the author of Twitch, an entirely average pygame arcade game.*