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

(vip2019) #1

182 Chapter 8


As we build our ShowPic.py program, we’ll learn about the
three main parts of a game or animation in Pygame. First, there’s
the setup, where we import modules we need, create our screen,
and initialize some important variables. Then comes the game
loop, which handles events, draws graphics, and updates the dis-
play. This game loop is a while loop that keeps running as long as
the user doesn’t quit the game. Finally, we need a way to end the
program when the user quits the game.

s tting e up
First, download the smiley face image and save it in the same
folder as your Python programs. Go to http://www.nostarch.com/
teachkids/ to find the source code downloads and save the image
CrazySmile.bmp to the folder where you’ve been saving your .py
files. It doesn’t really matter where you keep your .py files; just
make sure to save the BMP (short for bitmap, a common image
file format) image file to the same location.
Next, let’s take care of the setup:

import pygame # Setup
pygame.init()
screen = pygame.display.set_mode([800,600])
keep_going = True
u pic = pygame.image.load("CrazySmile.bmp")

As always, we import the pygame module and then initialize
using the pygame.init() function. Next, we set up our screen to be a
new Pygame window 800×600 pixels in size. We create our Boolean
flag keep_going to control our game loop and set it equal to True.
Finally, we do something new: at u, we use pygame.image.load(),
which loads an image from a file. We create a variable for our
image file and load CrazySmile.bmp, which we’ll refer to as pic in
our program.

Creating a Game loop
At this point, we haven’t drawn anything, but we’ve set up Pygame
and loaded an image. The game loop is where we’ll actually display
the smiley face image on the screen. It’s also where we’ll handle
events from the user. Let’s start by handling one important event:
the user choosing to quit the game.
Free download pdf