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

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

same goes for larger fonts versus smaller fonts. The text string
will be rendered on a rectangular surface, so we’ll call our variable
text_rect for the rectangle that holds our drawn string:


text_rect = text.get_rect()


The get_rect() command on our text surface will return the
dimensions of the drawn string. Next we’ll center the text rect-
angle text_rect horizontally on the screen, using the .centerx
attribute, and position the text rectangle 10 pixels down from the
top of the screen so it’s easy to see. Here are the two commands to
set the position:


text_rect.centerx = screen.get_rect().centerx
text_rect.y = 10


It’s time to draw the text_rect image to the screen. We’ll do
this using the blit() function like we did for our picture pic:


screen.blit(text, text_rect)


With those changes, our Smiley Pong game has become like
the classic version of the game, but with our smiley face as the
ball. Run the app, and you’ll see something like Figure 10-5. We’re
on our way to an arcade-quality game!


Putting It All Together


We’ve used many coding skills to make this game. Variables, loops,
conditions, math, graphics, event handling—almost our full tool-
kit. Games are an adventure for both the coder and the player.
Producing a game is challenging and rewarding; we get to build
the gameplay we want, then share it with others. My sons loved
version 1.0 of the Smiley Pong game, and they gave me great ideas
for extending it to version 2.0.
Here’s the full version 1.0, SmileyPong1.py:


SmileyPong1.py


import pygame # Setup
pygame.init()
screen = pygame.display.set_mode([800,600])
pygame.display.set_caption("Smiley Pong")
keepGoing = True

Free download pdf