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 Ball

Now, please welcome, the star of our show: the ball! To keep track of it, we use four variables, as detailed in Table 13-1.

Table 13-1 Variables for the Ball

Variable

Meaning

ballx

X position (from 1 to 20)

bally

Y position (from 1 to 20)

ballxdir

Direction of travel horizontally. 1 for right or –1 for left.

ballydir

Direction of travel vertically. 1 for down or –1 for up.

The drawball() function accepts two arguments for the ball’s position and draws the ball there. Because you draw a circle by giving Pygame its center instead of its top-left corner, we had to add 10 to the pixel coordinates given by realx() and realy(). To give the ball some depth, we’ve added a second circle to it in a color and position that looks like a reflected light. Actually, that might be overselling it, but it does make the ball look less flat.

def drawball(x,y):

pygame.draw.circle (gameSurface,BLUE,(realx(x)+10,Ærealy(y)+10),10,0)

pygame.draw.circle (gameSurface,LIGHTBLUE,(realx(x)Æ+6,realy(y)+6),2,0)

That function goes with the rest at the top of your program listing. Back in the main part of the program, when a game begins, we want to position the ball in a random location in the top seven rows of the screen where we know there isn’t a brick. To do that, we use a while loop that keeps picking random coordinates until it finds an empty square. We also check for ballx being zero to get us over the while statement first time around and pick our ...

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