Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1
Game Programming: Coding for Fun 235

But we’re not going to draw this rectangle yet. Those variables
would be enough to draw a rectangle on the screen the first time,
but our paddle needs to follow the user’s mouse movements. We
want to draw the paddle on the screen centered around where the
user moves the mouse in the x direction (side to side), while keep-
ing the y-coordinate fixed near the bottom of the screen. To do this,
we need the x-coordinates of the mouse’s position. We can get the
position of the mouse by using pygame.mouse.get_pos(). In this case,
since we care only about the x-coordinate of get_pos(), and since x
comes first in our mouse position, we can get the x-coordinate of
the mouse with this:


paddlex = pygame.mouse.get_pos()[0]


But remember that Pygame starts drawing a rectangle at the
(x, y) position we provide, and it draws the rest of the rectangle to
the right of and below that location. To center the paddle where the
mouse is positioned, we need to subtract half the paddle’s width
from the mouse’s x-position, putting the mouse halfway through
the paddle:


paddlex -= paddlew/2


Now that we know the center of the paddle will always be
where the mouse is, all we need to do in our game loop is to draw
the paddle rectangle on the screen:


pygame.draw.rect(screen, WHITE, (paddlex, paddley, paddlew, paddleh))


If you add those three lines before the pygame.display.update()
in the while loop in SmileyBounce2.py and add the paddle color,
paddlew, paddleh, paddlex, and paddley to the setup section, you’ll see
the paddle follow your mouse. But the ball won’t bounce off the
paddle yet because we haven’t added the logic to test whether the
ball has collided with it. That’s our next step.


Keeping Score


Keeping score is part of what makes a game fun. Points, lives,
stars—whatever you use to keep score, there’s a sense of achieve-
ment that comes from seeing your score increase. In our Smiley
Pong game, we want the user to gain a point every time the ball
hits the paddle and lose a life when they miss the ball and it hits

Free download pdf