Operation Manual
Experiments in Python
104
Notes:
This world tree group does nothing yet because it has not been used by the main
game. The next listing changes the main game to use the new class.
skiWorld
Make these changes to the class “skiWorld”, don’t add them to the end of your
program. See if you understand how to extend the skiWorld so that it will create
trees, update them, draw them and check if the skier collides with the group
of trees.
def __init__( s e l f ):
self.running = True
self.skier = worldSkier([190, 50], pygame.image.load("skier.png"))
## adding trees
self.trees = worldTreeGroup(pygame.image.load("block.png"))
def updateWorld( s e l f ):
# the skier is part of the world and needs updating
self.skier.update(self.keydir)
## move the tree rows - removing any
## line that is off the top of the screen
self.trees.update()
## check if the skier has collided with any
## tree sprite in the tree rows in the tree group
if pyga me.sprite.spritecollide(self.skier, self.trees, False):
self.running = False
## check if the tree group has run out of tree rows –
## skier got to the bottom of the piste
if len(self.trees)==0:
self.running = False
def drawWorld(self, canvas):
canvas.ll([255, 250, 250]) # make a snowy white background
world.trees.draw(canvas) # draw the trees
world.skier.draw(canvas) # draw the player on the screen
In the skiWorld, one of these groups of trees is added when the world is initialised,
the trees are updated when the world is updated and it checks for collision
between the skier and any sprite in the group of tree rows. Lastly, if the tree group
is empty, the game is over.
The only change to the main loop is that the group draws on the canvas.
You could try adding sound effects using the sound example earlier. If you can
find some “wav” files from another source, you just need to play them. This will
save you generating them yourself.