Debian Codegraph @

doc/builtins.rst

raw
1 Built-in Objects
2 ================
3
4 Pygame Zero provides useful built-in objects to help you make games easily.
5
6
7 .. _screen:
8
9 Screen
10 ------
11
12 .. toctree::
13 :hidden:
14
15 ptext
16
17 The ``screen`` object represents your game screen.
18
19 It is a thin wrapper around a Pygame surface that allows you to easily
20 draw images to the screen ("blit" them).
21
22 .. class:: Screen
23
24 .. attribute:: surface
25
26 The raw `Pygame surface`_ that represents the screen buffer. You can
27 use this for advanced graphics operations.
28
29 .. _`Pygame surface`: https://www.pygame.org/docs/ref/surface.html
30
31 .. method:: clear()
32
33 Reset the screen to black.
34
35 .. method:: fill((red, green, blue))
36
37 Fill the screen with a solid color.
38
39 .. method:: blit(image, (left, top))
40
41 Draw the image to the screen at the given position.
42
43 ``blit()`` accepts either a Surface or a string as its ``image``
44 parameter. If ``image`` is a ``str`` then the named image will be
45 loaded from the ``images/`` directory.
46
47 .. method:: draw.line(start, end, (r, g, b))
48
49 Draw a line from start to end.
50
51 .. method:: draw.circle(pos, radius, (r, g, b))
52
53 Draw the outline of a circle.
54
55 .. method:: draw.filled_circle(pos, radius, (r, g, b))
56
57 Draw a filled circle.
58
59 .. method:: draw.rect(rect, (r, g, b))
60
61 Draw the outline of a rectangle.
62
63 Takes a :ref:`Rect <rect>`.
64
65 .. method:: draw.filled_rect(rect, (r, g, b))
66
67 Draw a filled rectangle.
68
69 .. method:: draw.text(text, [pos], **kwargs)
70
71 Draw text.
72
73 There's an extremely rich API for positioning and formatting text; see
74 :doc:`ptext` for full details.
75
76 .. method:: draw.textbox(text, rect, **kwargs)
77
78 Draw text, sized to fill the given :ref:`Rect`.
79
80 There's an extremely rich API for formatting text; see
81 :doc:`ptext` for full details.
82
83 .. _rect:
84
85 Rect
86 ----
87
88 The `Pygame Rect`_ class is available as a built in. This can be used in a
89 variety of ways, from detecting clicks within a region to drawing a box onto
90 the screen:
91
92 For example, you can draw a box with::
93
94 RED = 200, 0, 0
95 BOX = Rect((20, 20), (100, 100))
96
97 def draw():
98 screen.draw.rect(BOX, RED)
99
100
101 .. _`Pygame Rect`: https://www.pygame.org/docs/ref/rect.html
102
103
104 Resource Loading
105 ----------------
106
107 The ``images`` and ``sounds`` objects can be used to load images and sounds
108 from files stored in the ``images`` and ``sounds`` subdirectories respectively.
109 Pygame Zero will handle loading of these resources on demand and will cache
110 them to avoid reloading them.
111
112 You generally need to ensure that your images are named with lowercase letters,
113 numbers and underscores only. They also have to start with a letter.
114
115 File names like these will work well with the resource loader::
116
117 alien.png
118 alien_hurt.png
119 alien_run_7.png
120
121 These will not work::
122
123 3.png
124 3degrees.png
125 my-cat.png
126 sam's dog.png
127
128 Images
129 ''''''
130
131 Pygame Zero can load images in ``.png``, ``.gif``, and ``.jpg`` formats. PNG is
132 recommended: it will allow high quality images with transparency.
133
134 We need to ensure an images directory is set up. If your project contains the
135 following files::
136
137 space_game.py
138 images/alien.png
139
140 Then ``space_game.py`` could draw the 'alien' sprite to the screen with this
141 code::
142
143 def draw():
144 screen.clear()
145 screen.blit('alien', (10, 10))
146
147 The name passed to ``blit()`` is the name of the image file within the images
148 directory, without the file extension.
149
150 Or using the :ref:`actor` API, ::
151
152 alien = Actor('alien')
153
154 def draw():
155 alien.draw()
156
157 There are some restrictions on the file names in both cases: they may only
158 contain lowercase latin letters, numbers and underscores. This is to prevent
159 compatibility problems when your game is played on a different operating system
160 that has different case sensitivity.
161
162 Image Surfaces
163 ''''''''''''''
164
165 You can also load images from the ``images`` directory using the ``images``
166 object. This allows you to work with the image data itself, query its
167 dimensions and so on::
168
169 forest = []
170 for i in range(5):
171 forest.append(
172 Actor('tree', topleft=(images.tree.width * i, 0))
173 )
174
175 Each loaded image is a Pygame ``Surface``. You will typically use
176 ``screen.blit(...)`` to draw this to the screen. It also provides handy methods
177 to query the size of the image in pixels:
178
179 .. class:: Surface
180
181 .. method:: get_width()
182
183 Returns the width of the image in pixels.
184
185 .. method:: get_height()
186
187 Returns the height of the image in pixels.
188
189 .. method:: get_size()
190
191 Returns a tuple (width, height) indicating the size in pixels of the
192 surface.
193
194 .. method:: get_rect()
195
196 Get a :class:`Rect` that is pre-populated with the bounds of the image
197 if the image was located at the origin.
198
199 Effectively this is equivalent to::
200
201 Rect((0, 0), image.get_size())
202
203
204 Sounds
205 ''''''
206
207 Pygame Zero can load sounds in ``.wav`` and ``.ogg`` formats. WAV is great for
208 small sound effects, while OGG is a compressed format that is more suited to
209 music. You can find free .ogg and .wav files online that can be used in your
210 game.
211
212 We need to ensure a sounds directory is set up. If your project contains the
213 following files::
214
215 drum_kit.py
216 sounds/drum.wav
217
218 Then ``drum_kit.py`` could play the drum sound whenever the mouse is clicked
219 with this code::
220
221 def on_mouse_down():
222 sounds.drum.play()
223
224 Each loaded sound is a Pygame ``Sound``, and has various methods to play and
225 stop the sound as well as query its length in seconds:
226
227 .. class:: Sound
228
229 .. method:: play()
230
231 Play the sound.
232
233 .. method:: play(loops)
234
235 Play the sound, but loop it a number of times.
236
237 :param loops: The number of times to loop. If you pass ``-1`` as the
238 number of times to loop, the sound will loop forever (or
239 until you call :meth:`.Sound.stop()`
240
241 .. method:: stop()
242
243 Stop playing the sound.
244
245 .. method:: get_length()
246
247 Get the duration of the sound in seconds.
248
249 You should avoid using the ``sounds`` object to play longer pieces of music.
250 Because the sounds sytem will fully load the music into memory before playing
251 it, this can use a lot of memory, as well as introducing a delay while the
252 music is loaded.
253
254 .. _music:
255
256 Music
257 -----
258
259 .. versionadded:: 1.1
260
261 .. warning::
262
263 The music API is experimental and may be subject to cross-platform
264 portability issues.
265
266 In particular:
267
268 * MP3 may not be available on some Linux distributions.
269 * Some OGG Vorbis files seem to hang Pygame with 100% CPU.
270
271 In the case of the latter issue, the problem may be fixed by re-encoding
272 (possibly with a different encoder).
273
274
275 A built-in object called ``music`` provides access to play music from within
276 a ``music/`` directory (alongside your ``images/`` and ``sounds/`` directories,
277 if you have them). The music system will load the track a little bit at a time
278 while the music plays, avoiding the problems with using ``sounds`` to play
279 longer tracks.
280
281 Another difference to the sounds system is that only one music track can be
282 playing at a time. If you play a different track, the previously playing track
283 will be stopped.
284
285
286 .. function:: music.play(name)
287
288 Play a music track from the given file. The track will loop indefinitely.
289
290 This replaces the currently playing track and cancels any tracks previously
291 queued with ``queue()``.
292
293 You do not need to include the extension in the track name; for example, to
294 play the file ``handel.mp3`` on a loop::
295
296 music.play('handel')
297
298 .. function:: music.play_once(name)
299
300 Similar to ``play()``, but the music will stop after playing through once.
301
302 .. function:: music.queue(name)
303
304 Similar to ``play_once()``, but instead of stopping the current music, the
305 track will be queued to play after the current track finishes (or after
306 any other previously queued tracks).
307
308 .. function:: music.stop()
309
310 Stop the music.
311
312 .. function:: music.pause()
313
314 Pause the music temporarily. It can be resumed by calling
315 ``unpause()``.
316
317 .. function:: music.unpause()
318
319 Unpause the music.
320
321 .. function:: music.is_playing()
322
323 Returns True if the music is playing (and is not paused), False otherwise.
324
325 .. function:: music.fadeout(duration)
326
327 Fade out and eventually stop the current music playback.
328
329 :param duration: The duration in seconds over which the sound will be faded
330 out. For example, to fade out over half a second, call
331 ``music.fadeout(0.5)``.
332
333 .. function:: music.set_volume(volume)
334
335 Set the volume of the music system.
336
337 This takes a number between 0 (meaning silent) and 1 (meaning full volume).
338
339 .. function:: music.get_volume()
340
341 Get the current volume of the music system.
342
343
344 If you have started a music track playing using :func:`music.play_once()`, you
345 can use the :func:`on_music_end() hook <on_music_end>` to do something when the
346 music ends - for example, to pick another track at random.
347
348
349 .. _clock:
350
351 Clock
352 -----
353
354 Often when writing a game, you will want to schedule some game event to occur
355 at a later time. For example, we may want a big boss alien to appear after 60
356 seconds. Or perhaps a power-up will appear every 20 seconds.
357
358 More subtle are the situations when you want to delay some action for a shorter
359 period. For example you might have a laser weapon that takes 1 second to charge
360 up.
361
362 We can use the ``clock`` object to schedule a function to happen in the
363 future.
364
365 Let's start by defining a function ``fire_laser`` that we want to run in the
366 future::
367
368 def fire_laser():
369 lasers.append(player.pos)
370
371 Then when the fire button is pressed, we will ask the ``clock`` to call it for
372 us after exactly 1 second::
373
374 def on_mouse_down():
375 clock.schedule(fire_laser, 1.0)
376
377 Note that ``fire_laser`` is the function itself; without parentheses, it is
378 not being called here! The clock will call it for us.
379
380 (It is a good habit to write out times in seconds with a decimal point, like
381 ``1.0``. This makes it more obvious when you are reading it back, that you are
382 referring to a time value and not a count of things.)
383
384 ``clock`` provides the following useful methods:
385
386 .. class:: Clock
387
388 .. method:: schedule(callback, delay)
389
390 Schedule `callback` to be called after the given delay.
391
392 Repeated calls will schedule the callback repeatedly.
393
394 :param callback: A callable that takes no arguments.
395 :param delay: The delay, in seconds, before the function should be
396 called.
397
398 .. method:: schedule_unique(callback, delay)
399
400 Schedule `callback` to be called once after the given delay.
401
402 If `callback` was already scheduled, cancel and reschedule it. This
403 applies also if it was scheduled multiple times: after calling
404 ``schedule_unique``, it will be scheduled exactly once.
405
406 :param callback: A callable that takes no arguments.
407 :param delay: The delay, in seconds, before the function should be
408 called.
409
410 .. method:: schedule_interval(callback, interval)
411
412 Schedule `callback` to be called repeatedly.
413
414 :param callback: A callable that takes no arguments.
415 :param interval: The interval in seconds between calls to `callback`.
416
417 .. method:: unschedule(callback)
418
419 Unschedule callback if it has been previously scheduled (either because
420 it has been scheduled with ``schedule()`` and has not yet been called,
421 or because it has been scheduled to repeat with
422 ``schedule_interval()``.
423
424
425 Note that the Pygame Zero clock only holds weak references to each callback
426 you give it. It will not fire scheduled events if the objects and methods are
427 not referenced elsewhere. This can help prevent the clock keeping objects
428 alive and continuing to fire unexpectedly after they are otherwise dead.
429
430 The downside to the weak references is that you won't be able to schedule
431 lambdas or any other object that has been created purely to be scheduled. You
432 will have to keep a reference to the object.
433
434 .. _actor:
435
436 Actors
437 ------
438
439 Once you have many images moving around in a game it can be convenient to have
440 something that holds in one place the image and where it is on screen. We'll
441 call each moving image on screen an ``Actor``. You can create an actor by supplying
442 at least an image name (from the images folder above). To draw the alien talked
443 about above::
444
445 alien = Actor('alien', (50, 50))
446
447 def draw():
448 screen.clear()
449 alien.draw()
450
451 You can move the actor around by setting its pos attribute in an update::
452
453 def update():
454 if keyboard.left:
455 alien.x -= 1
456 elif keyboard.right:
457 alien.x += 1
458
459 And you may change the image used to draw the actor by setting its image
460 attribute to some new image name::
461
462 alien.image = 'alien_hurt'
463
464 Actors have all the same attributes and methods as :ref:`Rect <rect>`,
465 including methods like `.colliderect()`__ which can be used to test whether
466 two actors have collided.
467
468 .. __: https://www.pygame.org/docs/ref/rect.html#pygame.Rect.colliderect
469
470
471 Positioning Actors
472 ''''''''''''''''''
473
474 If you assign a new value to one of the position attributes then the actor will
475 be moved. For example::
476
477 alien.right = WIDTH
478
479 will position the alien so its right-hand side is set to ``WIDTH``.
480
481 Similarly, you can also set the initial position of the actor in the
482 constructor, by passing one of these as a keyword argument: ``pos``,
483 ``topleft``, ``topright``, ``bottomleft``, ``bottomright``, ``midtop``,
484 ``midleft``, ``midright``, ``midbottom`` or ``center``:
485
486 .. image:: _static/actor/anchor_points.png
487
488 This can be done during creation or by assigning a pair of x, y co-ordinates.
489 For example::
490
491 WIDTH = 200
492 HEIGHT = 200
493
494 alien = Actor('alien', center=(100,100))
495
496 def draw():
497 screen.clear()
498 alien.draw()
499
500 .. image:: _static/actor/alien_center.png
501
502 Changing ``center=(100, 100)`` to ``midbottom=(100, 200)`` gives you:
503
504 .. image:: _static/actor/alien_midbottom.png
505
506 If you don't specify an initial position, the actor will initially be
507 positioned in the top-left corner (equivalent to ``topleft=(0, 0)``).
508
509 .. _anchor:
510
511 Anchor point
512 ''''''''''''
513
514 Actors have an "anchor position", which is a convenient way to position the
515 actor in the scene. By default, the anchor position is the center, so the
516 ``.pos`` attribute refers to the center of the actor (and so do the ``x`` and
517 ``y`` coordinates). It's common to want to set the anchor point to another
518 part of the sprite (perhaps the feet - so that you can easily set the Actor to
519 be "standing on" something)::
520
521 alien = Actor('alien', anchor=('center', 'bottom'))
522 spaceship = Actor('spaceship', anchor=(10, 50))
523
524 ``anchor`` is specified as a tuple ``(xanchor, yanchor)``, where the values can
525 be floats or the strings ``left``, ``center``/``middle``, ``right``, ``top`` or
526 ``bottom`` as appropriate.
527
528
529 .. _rotation:
530
531 Rotation
532 ''''''''
533
534 .. versionadded:: 1.2
535
536 The ``.angle`` attribute of an Actor controls the rotation of the sprite, in
537 degrees, anticlockwise (counterclockwise).
538
539 The centre of rotation is the Actor's :ref:`anchor point <anchor>`.
540
541 Note that this will change the ``width`` and ``height`` of the Actor.
542
543 For example, to make an asteroid sprite spinning slowly anticlockwise in
544 space::
545
546 asteroid = Actor('asteroid', center=(300, 300))
547
548 def update():
549 asteroid.angle += 1
550
551 To have it spin clockwise, we'd change ``update()`` to::
552
553 def update():
554 asteroid.angle -= 1
555
556 As a different example, we could make an actor ``ship`` always face the mouse
557 pointer. Because :meth:`~Actor.angle_to()` returns 0 for "right", the sprite we
558 use for "ship" should face right::
559
560 ship = Actor('ship')
561
562 def on_mouse_move(pos):
563 ship.angle = ship.angle_to(pos)
564
565 .. image:: _static/rotation.svg
566 :alt: Diagram showing how to set up sprites for rotation with angle_to()
567
568 Remember that angles loop round, so 0 degrees == 360 degrees == 720 degrees.
569 Likewise -180 degrees == 180 degrees.
570
571
572 Distance and angle to
573 '''''''''''''''''''''
574
575 Actors have convenient methods for calculating their distance or angle to other
576 Actors or ``(x, y)`` coordinate pairs.
577
578 .. method:: Actor.distance_to(target)
579
580 Return the distance from this actor's position to target, in pixels.
581
582
583 .. method:: Actor.angle_to(target)
584
585 Return the angle from this actor's position to target, in degrees.
586
587 This will return a number between -180 and 180 degrees. Right is 0 degrees
588 and the angles increase going anticlockwise.
589
590 Therefore:
591
592 * Left is 180 degrees.
593 * Up is 90 degrees.
594 * Down is -90 degrees.
595
596
597 The Keyboard
598 ------------
599
600 You probably noticed that we used the ``keyboard`` in the above code.
601 If you'd like to know what keys are pressed on the keyboard, you can query the
602 attributes of the ``keyboard`` builtin. If, say, the left arrow is held down,
603 then ``keyboard.left`` will be ``True``, otherwise it will be ``False``.
604
605 There are attributes for every key; some examples::
606
607 keyboard.a # The 'A' key
608 keyboard.left # The left arrow key
609 keyboard.rshift # The right shift key
610 keyboard.kp0 # The '0' key on the keypad
611 keyboard.k_0 # The main '0' key
612
613 The full set of key constants is given in the `Buttons and Keys`_
614 documentation, but the attributes are lowercase, because these are variables
615 not constants.
616
617 .. deprecated:: 1.1
618
619 Uppercase and prefixed attribute names (eg. ``keyboard.LEFT`` or
620 ``keyboard.K_a``) are now deprecated; use lowercase attribute names
621 instead.
622
623 .. _`Buttons and Keys`: hooks.html#buttons-and-keys
624
625 .. versionadded:: 1.1
626
627 You can now also query the state of the keys using the keyboard constants
628 themselves::
629
630 keyboard[keys.A] # True if the 'A' key is pressed
631 keyboard[keys.SPACE] # True if the space bar is pressed
632
633
634 Animations
635 ----------
636
637 You can animate most things in pygame using the builtin ``animate()``. For
638 example, to move an :ref:`Actor <actor>` from its current position on the
639 screen to the position ``(100, 100)``::
640
641 animate(alien, pos=(100, 100))
642
643 .. function:: animate(object, tween='linear', duration=1, on_finished=None, **targets)
644
645 Animate the attributes on object from their current value to that
646 specified in the targets keywords.
647
648 :param tween: The type of *tweening* to use.
649 :param duration: The duration of the animation, in seconds.
650 :param on_finished: Function called when the animation finishes.
651 :param targets: The target values for the attributes to animate.
652
653 The tween argument can be one of the following:
654
655 +--------------------+------------------------------------------------------+
656 | 'linear' | Animate at a constant speed from start to finish |
657 +--------------------+------------------------------------------------------+
658 | 'accelerate' | Start slower and accelerate to finish |
659 +--------------------+------------------------------------------------------+
660 | 'decelerate' | Start fast and decelerate to finish |
661 +--------------------+------------------------------------------------------+
662 | 'accel_decel' | Accelerate to mid point and decelerate to finish |
663 +--------------------+------------------------------------------------------+
664 | 'end_elastic' | Give a little wobble at the end |
665 +--------------------+------------------------------------------------------+
666 | 'start_elastic' | Have a little wobble at the start |
667 +--------------------+------------------------------------------------------+
668 | 'both_elastic' | Have a wobble at both ends |
669 +--------------------+------------------------------------------------------+
670 | 'bounce_end' | Accelerate to the finish and bounce there |
671 +--------------------+------------------------------------------------------+
672 | 'bounce_start' | Bounce at the start |
673 +--------------------+------------------------------------------------------+
674 | 'bounce_start_end' | Bounce at both ends |
675 +--------------------+------------------------------------------------------+
676
677 The ``animate()`` function returns an ``Animation`` instance:
678
679 .. class:: Animation
680
681 .. method:: stop(complete=False)
682
683 Stop the animation, optionally completing the transition to the final
684 property values.
685
686 :param complete: Set the animated attribute to the target value.
687
688 .. attribute:: running
689
690 This will be True if the animation is running. It will be False
691 when the duration has run or the ``stop()`` method was called before
692 then.
693
694 .. attribute:: on_finished
695
696 You may set this attribute to a function which will be called
697 when the animation duration runs out. The ``on_finished`` argument
698 to ``animate()`` also sets this attribute. It is not called when
699 ``stop()`` is called. This function takes no arguments.
700
701
702 Tone Generator
703 --------------
704
705 .. versionadded:: 1.2
706
707 Pygame Zero can play tones using a built-in synthesizer.
708
709 .. function:: tone.play(pitch, duration)
710
711 Play a note at the given pitch for the given duration.
712
713 Duration is in seconds.
714
715 The `pitch` can be specified as a number in which case it is the frequency
716 of the note in hertz.
717
718 Alternatively, the pitch can be specified as a string representing a note
719 name and octave. For example:
720
721 * ``'E4'`` would be E in octave 4.
722 * ``'A#5'`` would be A-sharp in octave 5.
723 * ``'Bb3'`` would be B-flat in octave 3.
724
725 Creating notes, particularly long notes, takes time - up to several
726 milliseconds. You can create your notes ahead of time so that this doesn't slow
727 your game down while it is running:
728
729 .. function:: tone.create(pitch, duration)
730
731 Create and return a Sound object.
732
733 The arguments are as for play(), above.
734
735 This could be used in a Pygame Zero program like this::
736
737 beep = tone.create('A3', 0.5)
738
739 def on_mouse_down():
740 beep.play()