Upgrade to Pro — share decks privately, control downloads, hide ads and more …

PyConZA 2014: "Pygame tutorial" by Neil Muller

Pycon ZA
October 02, 2014

PyConZA 2014: "Pygame tutorial" by Neil Muller

PyGame is a popular library for developing video games with Python which provides good support for 2D graphics, audio, user input and a number of useful utilities.

In this tutorial, I will cover the basics of writing a simple game using python and pygame, and explore Pygame's functionality. The tutorial will cover:

* The Pygame event system
* Drawing graphics to the screen
* Simple animations
* Sound and music support
* Pygame's Rect object and why you should embrace it

I will also discuss some of the pitfalls to be aware of when working with Pygame.

The slides and the examples used in the tutorial are available from: http://dip.sun.ac.za/~neil/talks/pyconza_2014/.

Pycon ZA

October 02, 2014
Tweet

More Decks by Pycon ZA

Other Decks in Programming

Transcript

  1. Outline What is Pygame What Pygame isn't Events Basic graphics

    Rectangles Sounds Surfaces Other Stu Where to go from here? Neil Muller Writing simple games with Pygame
  2. What is Pygame Wrapper around Simple DirectMedia Layer libraries in

    python SDL - designed to provide low level access to audio, keyboard, graphics hardware, etc. Provides framework and tools useful for writing 2d games Quite popular, although SDL is showing it's age a bit now Lots of discussion about creating an updated version using SDL2, but no real progress on that yet Still the basis for the majority of pyweek entries Usable on pypy via the pygame-c project, although support for several pygame features is still incomplete Neil Muller Writing simple games with Pygame
  3. What is Pygame Wrapper around Simple DirectMedia Layer libraries in

    python SDL - designed to provide low level access to audio, keyboard, graphics hardware, etc. Provides framework and tools useful for writing 2d games Quite popular, although SDL is showing it's age a bit now Lots of discussion about creating an updated version using SDL2, but no real progress on that yet Still the basis for the majority of pyweek entries Usable on pypy via the pygame-c project, although support for several pygame features is still incomplete This is an easy starting point for getting involved in pypy & c Neil Muller Writing simple games with Pygame
  4. What Pygame isn't Not a UI toolkit Widgets, etc are

    all roll-your-own Fortunately, there are a number of libraries where people have done all the hard UI work for you Neil Muller Writing simple games with Pygame
  5. What Pygame isn't Not a UI toolkit Widgets, etc are

    all roll-your-own Fortunately, there are a number of libraries where people have done all the hard UI work for you Unfortunately, there are also libraries where people have done all the hard UI work for you badly Neil Muller Writing simple games with Pygame
  6. What Pygame isn't Not a UI toolkit Widgets, etc are

    all roll-your-own Fortunately, there are a number of libraries where people have done all the hard UI work for you Unfortunately, there are also libraries where people have done all the hard UI work for you badly Not quite as portable as one would like Basics are very portable, since SDL is very portable, but a lot of useful features still depend on support libraries and compilation options OGG or proper PNG support can be problematic on some platforms due to dependency issues Neil Muller Writing simple games with Pygame
  7. What Pygame isn't Not a UI toolkit Widgets, etc are

    all roll-your-own Fortunately, there are a number of libraries where people have done all the hard UI work for you Unfortunately, there are also libraries where people have done all the hard UI work for you badly Not quite as portable as one would like Basics are very portable, since SDL is very portable, but a lot of useful features still depend on support libraries and compilation options OGG or proper PNG support can be problematic on some platforms due to dependency issues MacPorts builds being a traditional oender Neil Muller Writing simple games with Pygame
  8. What Pygame isn't Not a UI toolkit Widgets, etc are

    all roll-your-own Fortunately, there are a number of libraries where people have done all the hard UI work for you Unfortunately, there are also libraries where people have done all the hard UI work for you badly Not quite as portable as one would like Basics are very portable, since SDL is very portable, but a lot of useful features still depend on support libraries and compilation options OGG or proper PNG support can be problematic on some platforms due to dependency issues MacPorts builds being a traditional oender Not a 3D framework Basically limited to creating surfaces for OpenGL Can still be useful in 3D games for it's other features Neil Muller Writing simple games with Pygame
  9. Hello World Explicitly need to initialise pygame modules that will

    be used pygame.init() will initialise all modules, which may or may not be what you want Neil Muller Writing simple games with Pygame
  10. Hello World Explicitly need to initialise pygame modules that will

    be used pygame.init() will initialise all modules, which may or may not be what you want pygame.display.ip updates the entire display We can do smaller updates using pygame.display.update Neil Muller Writing simple games with Pygame
  11. Hello World Explicitly need to initialise pygame modules that will

    be used pygame.init() will initialise all modules, which may or may not be what you want pygame.display.ip updates the entire display We can do smaller updates using pygame.display.update Not every application can use pygame.display.update (scrolling backgrounds, etc) And on modern hardware, the housekeeping required isn't worth the nominal performance gain Neil Muller Writing simple games with Pygame
  12. The Event Loop User interaction creates events Typical loop is

    either pygame.event.poll (get single event) or pygame.event.get (get all events) Events have type and dictionary of interesting properties (pos for mouse events, key for keyboard, etc) Neil Muller Writing simple games with Pygame
  13. The Event Loop User interaction creates events Typical loop is

    either pygame.event.poll (get single event) or pygame.event.get (get all events) Events have type and dictionary of interesting properties (pos for mouse events, key for keyboard, etc) Use pygame.time.Clock to manage speed through the loop Speed specied in Hz Neil Muller Writing simple games with Pygame
  14. The Event Loop User interaction creates events Typical loop is

    either pygame.event.poll (get single event) or pygame.event.get (get all events) Events have type and dictionary of interesting properties (pos for mouse events, key for keyboard, etc) Use pygame.time.Clock to manage speed through the loop Speed specied in Hz Returns time taken between ticks - useful for crude proling of game delays pygame.time.set_timer() can be used to for timed events Neil Muller Writing simple games with Pygame
  15. The Event Loop User interaction creates events Typical loop is

    either pygame.event.poll (get single event) or pygame.event.get (get all events) Events have type and dictionary of interesting properties (pos for mouse events, key for keyboard, etc) Use pygame.time.Clock to manage speed through the loop Speed specied in Hz Returns time taken between ticks - useful for crude proling of game delays pygame.time.set_timer() can be used to for timed events Custom events can be dened Added to the event queue with pygame.event.post Neil Muller Writing simple games with Pygame
  16. The Event Loop User interaction creates events Typical loop is

    either pygame.event.poll (get single event) or pygame.event.get (get all events) Events have type and dictionary of interesting properties (pos for mouse events, key for keyboard, etc) Use pygame.time.Clock to manage speed through the loop Speed specied in Hz Returns time taken between ticks - useful for crude proling of game delays pygame.time.set_timer() can be used to for timed events Custom events can be dened Added to the event queue with pygame.event.post Very limited number of event types (32 total) 0 for no event, 1-23 are reserved by SDL (mouse motion, etc), leaving 24-31 for user events Neil Muller Writing simple games with Pygame
  17. The Event Loop User interaction creates events Typical loop is

    either pygame.event.poll (get single event) or pygame.event.get (get all events) Events have type and dictionary of interesting properties (pos for mouse events, key for keyboard, etc) Use pygame.time.Clock to manage speed through the loop Speed specied in Hz Returns time taken between ticks - useful for crude proling of game delays pygame.time.set_timer() can be used to for timed events Custom events can be dened Added to the event queue with pygame.event.post Very limited number of event types (32 total) 0 for no event, 1-23 are reserved by SDL (mouse motion, etc), leaving 24-31 for user events Can attach arbitrary extra information to posted events Neil Muller Writing simple games with Pygame
  18. Not all interfaces allow passing custom event pygame callbacks, such

    as set_timer, only allow specifying event type Annoyingly, due to implementation details, introspection of events is limited
  19. Not all interfaces allow passing custom event pygame callbacks, such

    as set_timer, only allow specifying event type Annoyingly, due to implementation details, introspection of events is limited Limited number of user events seldom an issue But it is something to be aware of when using an existing pygame library Reusing a event type used by our library can cause some very unexpected behaviour Can lter event queue for various eects
  20. Not all interfaces allow passing custom event pygame callbacks, such

    as set_timer, only allow specifying event type Annoyingly, due to implementation details, introspection of events is limited Limited number of user events seldom an issue But it is something to be aware of when using an existing pygame library Reusing a event type used by our library can cause some very unexpected behaviour Can lter event queue for various eects Event queue is of nite length, so needs to be processed reasonably quickly Especially true if a lot of mouse motion is happening, since that generates a lot of events
  21. Basic Graphics Rule 1 of Pygame: Everything is a surface

    blit will copy from one surface to another Blitting will handle alpha blending and pixel format conversions automatically Neil Muller Writing simple games with Pygame
  22. Basic Graphics Rule 1 of Pygame: Everything is a surface

    blit will copy from one surface to another Blitting will handle alpha blending and pixel format conversions automatically Pixel format conversion can be slow Surfaces can be explicitly converted when rst created / loaded Neil Muller Writing simple games with Pygame
  23. Basic Graphics Rule 1 of Pygame: Everything is a surface

    blit will copy from one surface to another Blitting will handle alpha blending and pixel format conversions automatically Pixel format conversion can be slow Surfaces can be explicitly converted when rst created / loaded Default display surface attributes vary depending on setup If your game is unexpectedly slow on some systems, this is the most likely cause Neil Muller Writing simple games with Pygame
  24. Rectangles Rule 2 of Pygame: Everything is a rectangle Every

    surface has an associated rectangle Most coordinates can also be expressed as rectangles Neil Muller Writing simple games with Pygame
  25. Rectangles Rule 2 of Pygame: Everything is a rectangle Every

    surface has an associated rectangle Most coordinates can also be expressed as rectangles Lots of utility functions and methods for manipulating / querying rectangles either in-place or returning copies Rectangle position can be specied / queried in a number of ways center, topleft, bottomright, midleft, etc. Neil Muller Writing simple games with Pygame
  26. Rectangles Rule 2 of Pygame: Everything is a rectangle Every

    surface has an associated rectangle Most coordinates can also be expressed as rectangles Lots of utility functions and methods for manipulating / querying rectangles either in-place or returning copies Rectangle position can be specied / queried in a number of ways center, topleft, bottomright, midleft, etc. Various useful transformations Inate, clip, union and so forth Rectangles also can do collision detection Neil Muller Writing simple games with Pygame
  27. Rectangles Rule 2 of Pygame: Everything is a rectangle Every

    surface has an associated rectangle Most coordinates can also be expressed as rectangles Lots of utility functions and methods for manipulating / querying rectangles either in-place or returning copies Rectangle position can be specied / queried in a number of ways center, topleft, bottomright, midleft, etc. Various useful transformations Inate, clip, union and so forth Rectangles also can do collision detection Can test against multiple rectangles eciently (collidelist, collidedictall, etc) Per-pixel collision detection is also possible, but expensive Neil Muller Writing simple games with Pygame
  28. Sounds All lives in pygame.mixer Parameters set during mixer initialisation

    Need to call pygame.mixer.quit() if you want to change the values Neil Muller Writing simple games with Pygame
  29. Sounds All lives in pygame.mixer Parameters set during mixer initialisation

    Need to call pygame.mixer.quit() if you want to change the values Sound system consists of mixer, Channel Objects and Sound Objects Usually only worried about the Sound Object WAV only in guaranteed format, but MOD, OGG and MP3 available if SDL_mixer supports them. Neil Muller Writing simple games with Pygame
  30. Sounds All lives in pygame.mixer Parameters set during mixer initialisation

    Need to call pygame.mixer.quit() if you want to change the values Sound system consists of mixer, Channel Objects and Sound Objects Usually only worried about the Sound Object WAV only in guaranteed format, but MOD, OGG and MP3 available if SDL_mixer supports them. sound playback occurs in background thread Multiple sounds get mixed together transparently. Each sound can be played by multiple channels Limited by the number of channels available - default is 8, but can be tweaked Neil Muller Writing simple games with Pygame
  31. Channels allow ner control eects -> looping, etc. Can queue

    up multiple sounds on a Channel Channels can generate events when the current sound ends Limited to specifying event type, though, so somewhat limited
  32. Channels allow ner control eects -> looping, etc. Can queue

    up multiple sounds on a Channel Channels can generate events when the current sound ends Limited to specifying event type, though, so somewhat limited Special music object for background music Doesn't load entire sound at once Can only be one music object at a time
  33. Channels allow ner control eects -> looping, etc. Can queue

    up multiple sounds on a Channel Channels can generate events when the current sound ends Limited to specifying event type, though, so somewhat limited Special music object for background music Doesn't load entire sound at once Can only be one music object at a time pre_init allows passing settings to mixer if using pygame.init() Sounds get resampled to mixer on load Need to reload Sounds if you re-init the mixer with dierent settings
  34. Surfaces Lots of fancy eects available for blending Very useful

    for generating eects on the y Neil Muller Writing simple games with Pygame
  35. Surfaces Lots of fancy eects available for blending Very useful

    for generating eects on the y Functions for drawing directly on surfaces line, arc, etc Neil Muller Writing simple games with Pygame
  36. Surfaces Lots of fancy eects available for blending Very useful

    for generating eects on the y Functions for drawing directly on surfaces line, arc, etc Drawing routines use quite simplistic algorithms, so prone to artifacts Also comparatively slow Neil Muller Writing simple games with Pygame
  37. Surfaces Lots of fancy eects available for blending Very useful

    for generating eects on the y Functions for drawing directly on surfaces line, arc, etc Drawing routines use quite simplistic algorithms, so prone to artifacts Also comparatively slow Can also manipulate surface contents directly ll, scroll set_at and get_at can be used to manipulate individual pixels Neil Muller Writing simple games with Pygame
  38. Surfaces Lots of fancy eects available for blending Very useful

    for generating eects on the y Functions for drawing directly on surfaces line, arc, etc Drawing routines use quite simplistic algorithms, so prone to artifacts Also comparatively slow Can also manipulate surface contents directly ll, scroll set_at and get_at can be used to manipulate individual pixels This is very slow, though PixelArray, surfarry (numpy) exist to address this, but still not the fastest thing to try do Neil Muller Writing simple games with Pygame
  39. Can also specify a clipping rectangle on a surface Restricts

    operations to the clipped area Subsurfaces share pixel data with the parent surface, but separate surface properties, such as the clipping rectangle
  40. Can also specify a clipping rectangle on a surface Restricts

    operations to the clipped area Subsurfaces share pixel data with the parent surface, but separate surface properties, such as the clipping rectangle Various transformations scale, rotate, ip, etc Some special ones - scale2x, rotozoom
  41. Other Stu pygame.joystick for managing joystick properties Need to explicitly

    initialise a joystick device before events are added to the queue pygame.mouse - mouse properties and position Mostly useful for mouse cursor properties pygame.mask 2d bitmasks used for pixel collisions Also provides some occasionally useful analysis functions (centroid, connected component analysis, etc) pygame.sprite classes for managing visible game objects Various methods for managing updates and collisions Very useful when it's model works for your game Neil Muller Writing simple games with Pygame
  42. Where to go from here? Online resources for pygame are

    quite extensive www.pygame.org has pretty good docs Various other tutorials online pygame-users mailing list #pygame, #pyweek (during pyweek) on freenode good sources of advice Neil Muller Writing simple games with Pygame
  43. Where to go from here? Online resources for pygame are

    quite extensive www.pygame.org has pretty good docs Various other tutorials online pygame-users mailing list #pygame, #pyweek (during pyweek) on freenode good sources of advice Pyweek is a great way to learn pygame Pyweek 19 starts 5th October Neil Muller Writing simple games with Pygame
  44. Where to go from here? Online resources for pygame are

    quite extensive www.pygame.org has pretty good docs Various other tutorials online pygame-users mailing list #pygame, #pyweek (during pyweek) on freenode good sources of advice Pyweek is a great way to learn pygame Pyweek 19 starts 5th October Pygame is a mature project, so development activity is comparatively slow bitbucket.org/pygame/pygame/ pygame-c (on github) if you're interested in pygame on pypy Neil Muller Writing simple games with Pygame