O'Reilly logo

Raspberry Pi For Dummies by Mike Cook, Sean McManus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Positioning the Bat

The game uses the variable batx to refer to the X coordinate of the bat in the game map. The player can’t move the bat up and down, so we’ve used a constant called BATY to represent the bat’s row. The variable batx is assigned a random value at the start, so the bat starts in a random position. When setting up the bat, we also set the player’s score to zero:

#initialize bat and score

batx=random.randint(1,19)

BATY=20

drawbat(batx)

score=0

The function drawbat() does exactly what it says on the function name. It takes the bat’s X position as an argument and draws the bat there. Like the bricks, we’ve compiled the bat from several rectangles so it looks a bit more interesting. Here’s the routine to draw the bat:

def drawbat(x):

pygame.draw.rect (gameSurface,LIGHTPURPLE,(realx(x),Ærealy(BATY),40,4))

pygame.draw.rect (gameSurface,PURPLE,(realx(x),realy Æ(BATY)+4,40,6))

pygame.draw.rect (gameSurface,SHADOW,(realx(x),realy Æ(BATY)+10,40,2))

pygame.draw.rect (gameSurface,SHADOW,(realx(x)+38,Ærealy(BATY),2,12))

One thing to notice here is that the bat is 40 pixels wide, which means it’s two bricks wide.

Animation is just an illusion. To make the bat look as though it’s moved, you delete it and then redraw it nearby. It happens so fast that our eyes think it’s jumped, but from a programming point of view, it’s important to know what’s really going on. As well as drawing the bat, you need to be able to clear it again. We use two functions for that. The blank() function ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required