You are on page 1of 24

Meet Pygame

Noah Kantrowitz
June 8, 2007
The Basics

• Cross-platform
• Based on SDL (don’t quote me on that)
• Handle input (keyboard, mouse) and output
(graphics, audio)
Starting Up

• import pygame
• pygame.init()
• Cue music ...
The Screen

• screen = pygame.display.set_mode((x, y))

• screen = pygame.display.get_surface()

• pygame.display.flip()

• pygame.display.update(dirty)
Surfaces

• The basic element of graphics


• pygame.image.load(file)
• .convert_alpha() vs .set_colorkey((r,g,b))
• dest.blit(src, (x, y))
Formats

• Native support for the following:


JPEG PNG GIF BMP PCX
TGA TIF LBM PBM XPM
• SVG will need to worked out
• Stay tuned ...
The Loop

while True:
<timing>
<event handling>
<update phase>
<draw phase>
The Loop

while True:
<timing>
<event handling>
<update phase>
<draw phase>
Timing

• from pygame.time import Clock


• clock = Clock()
• delta = clock.tick(30)
The Loop

while True:
<timing>
<event handling>
<update phase>
<draw phase>
Event Handling

for evt in pygame.event.get():


if evt.type == pygame.QUIT:
sys.exit()
...
Event Handling

• Other types:
QUIT KEYUP KEYDOWN
MOUSEMOTION MOUSEBUTTONUP MOUSEBUTTONDOWN
Key Events

• evt.key == pygame.K_a
• See the Pygame documentation for the full
list of key constants.
Mouse Events

• evt.pos
• evt.button (for the button events)
The Loop

while True:
<timing>
<event handling>
<update phase>
<draw phase>
Sprites

• pygame.sprite.Sprite
• class Foo(Sprite):
• Must call superclass __init__()
• .image, .rect
Groups

• pygame.sprite.Group
• RenderUpdates, OrderedUpdates
• .add(), .remove()
• .update(*args)
• More on these in a moment
The Loop

while True:
<timing>
<event handling>
<update phase>
<draw phase>
Drawing

• .draw(dest)
• Dirty updates
• pygame.draw.update(dirty)
Rects

• pygame.Rect(left,top,width,height)

• surf.get_rect() Always at (0,0)


• Attributes:
top bottom left right topleft bottomleft
topright bottomright midtop midbottom midleft midright
center centerx centery size width height
Collisions

• Rect-based
• spritecollide(sprite,group,kill)
• spritecollideany(sprite,group)
• groupcollide(group1,group2,kill1,kill2)
Sound

• pygame.mixer.Sound(file)
• .play(), .stop()
• pygame.mixer.music
Text

• Try to avoid it for now.


More?

• http://www.pygame.org/docs
• Email me. (noah@laptop.org)

You might also like