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

(vip2019) #1

178 Chapter 8


Type the following in a new IDLE window or download it from
http://www.nostarch.com/teachkids/:

ShowDot.py

import pygame

u pygame.init()
v screen = pygame.display.set_mode([800,600])

w keep_going = True
x GREEN = (0,255,0) # RGB color triplet for GREEN
radius = 50

y while keep_going:
z for event in pygame.event.get():
{ if event.type == pygame.QUIT:
keep_going = False
| pygame.draw.circle(screen, GREEN, (100,100), radius)
} pygame.display.update()

~ pygame.quit()

Let’s step through this program line by line. First, we import
the pygame module to gain access to its features. At u, we initialize
Pygame, or set it up for use. The command pygame.init() will need
to be called every time you want to use Pygame, and it always
comes after the import pygame command and before any other
Pygame functions.
At v, pygame.display.set_mode([800,600]) creates a display
window 800 pixels wide by 600 pixels tall. We store it in a vari-
able called screen. In Pygame, windows and graphics are called
surfaces, and the display surface screen is the main window where
all of our other graphics will be drawn.
At w, you might recognize our looping variable, keep_going:
we used this in our HighCard.py and FiveDice.py game loops in
Chapter 6 as a Boolean flag to tell our program to keep playing.
Here in our Pygame example, we use a game loop to continue
drawing the graphics screen until the user closes the window.
At x, we set up two variables, GREEN and radius, for use in
drawing our circle. The GREEN variable is set to the RGB triplet
value (0,255,0), a bright green. (RGB, or Red Green Blue, is one
of many ways to specify a color. To pick a color, you choose three
numbers, each between 0 and 255. The first number determines
Free download pdf