Operation Manual

Experiments in Python
100
Notes:
Lesson 3.5: Simulations and games
Now we can handle graphics and sounds, as well as manipulating data and using
functions and classes. We can put all of this together to create something really
worth seeing - its time to write games!
Let’s go skiing!
For this experiment, you will need some little pictures (“sprites”), which will be
moved around the display. You can use any “paint” software to create a picture of
a skier, which is 20 pixels high and 20 pixels wide. Also, create a picture of a tree,
which is also 20 pixels high and 20 pixels wide (see the pictures on the next page).
# pyGameSkier.py
import pygame
# a world sprite is a pygame sprite
class worldSprite(pyga me.sprite.Sprite):
def __init__(self, location, picture):
pygame.sprite.Sprite.__init__(self)
self.image = picture
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
def draw(self,screen):
scre e n.blit(self.im ag e, self.rect)
# draw this sprite on the screen (BLIT)
# a skier in the world knows how fast it is going
# and it can move horizontally
class worldSkier( w o r l d S p r i t e ):
speed = 5
def update( s e l f, d i r e c t i o n ):
self.rect.left += direction * self.speed
self.rect.left = max(0, min(3 8 0, s e l f.r e c t.l e f t ))
class skiWorld(object):
running = False
keydir = 0
def __init__( s e l f ):
self.running = True
self.skier = worldSkier([190, 50],
pygame.image.load("skier.png"))
def updateWorld( s e l f ):
# the skier is part of the world and needs updating
self.skier.update(self.keydir)
def drawWorld(self, canvas):
canvas.ll([255, 250, 250]) # make a snowy white background
world.skier.draw(canvas) # draw the player on the screen