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

(vip2019) #1

214 Chapter 9


Putting It all together
The last step is to end the program with pygame.quit() as usual.
Here’s the full program.
DragDots.py

import pygame # Setup
pygame.init()
screen = pygame.display.set_mode([800,600])
pygame.display.set_caption("Click and drag to draw")
keep_going = True
YELLOW = (255,255,0) # RGB color triplet for YELLOW
radius = 15
mousedown = False

while keep_going: # Game loop
for event in pygame.event.get(): # Handling events
if event.type == pygame.QUIT:
keep_going = False
if event.type == pygame.MOUSEBUTTONDOWN:
mousedown = True
if event.type == pygame.MOUSEBUTTONUP:
mousedown = False
if mousedown: # Draw/update graphics
spot = pygame.mouse.get_pos()
pygame.draw.circle(screen, YELLOW, spot, radius)
pygame.display.update() # Update display

pygame.quit() # Exit

The DragDots.py app is so fast and responsive that it almost
feels like we’re painting with a continuous brush instead of a series
of dots; we have to drag the mouse pretty quickly to see the dots
drawn separately. Pygame allows us to build much faster and more
fluid games and animation than the turtle graphics we drew in
previous chapters.
Even though the for loop handles every event during every
pass through the while loop that keeps our app open, Pygame
is efficient enough to do this dozens or even hundreds of times
per second. This gives the illusion of instantaneous motion and
reaction to our every movement and command—an important
consideration as we build animations and interactive games.
Pygame is up to the challenge and is the right toolkit for our
graphics-intensive needs.
Free download pdf