Raspberry_Pi_Education_Manual

Notes:

Adding trees

import random class worldTreeGroup (pygame.sprite.Group): speed = 5 def __init__ (self, picture): pygame.sprite.Group.__init__(self) treePicture = picture treeRow = pygame.sprite.Group()

# in rows with a gap somewhere in the middle # only have a line of trees every 5th row or the # game is too difficult for y in range (0, 400): if (y % 5 == 0): # every 5th, add tree row with a gap gapsize = 3 + random.randint(0,6) # size of gap # starting position of gap gapstart = random.randint(0,10 - (gapsize//2)) # create a row of 20 trees but 'gapsize' # skip trees in the middle for b in range (0,20): if b >= gapstart and gapsize > 0: gapsize-=1 else : newtree=worldSprite([b*20, (y+10)*20], treePicture) treeRow.add(newtree) self.add(treeRow) def update (self): for treeRow in self: treeRow.rect.top-=self.speed if treeRow.rect.top <= -20: treeRow.kill() # remove this block from ALL groups

Now, if we can get rows of trees advancing on the skier’s position, this game will be a lot more challenging. Also if the skier hits a tree, the game should stop.

To set up the “piste”, this additional class sets up rows of trees that have a gap in the middle for the skier to pass through. The initialiser creates a group of trees by using the picture it is given and adding it a number of times (leaving a gap) to a group representing a row of trees. It then adds that group to the larger group representing a group of tree rows. Notice the use of integer division, “//”, to divide the “gapsize”. Without it, dividing gapsize by 2 may give a half and not a whole number (an integer ). The update part of the class defines what a group of trees can do when it is updated. The group will take all the rows of trees within it and move them up by a small distance. Also, when the row of trees goes behind the skier, off the top of the screen, it will remove that row of trees.

Experiments in Python

103

Made with FlippingBook flipbook maker