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

(vip2019) #1

208 Chapter 9


Interactive programs give us this sense of control in an app or
game, because we can move or interact with a character or other
object in the program. That’s exactly what you’ll learn to do in
this chapter: we’ll use Pygame’s ability to handle user interaction
from the mouse to make our programs more interactive and more
engaging for the user.

Adding Interaction: Click and Drag


Let’s add user interaction by developing two programs that will
allow the user to draw interactively on the screen. First, we’ll build
on our Pygame foundation to handle events like mouse-button clicks
and to enable the user to draw dots on the screen. Then, we’ll add
logic to handle mouse-button presses and releases separately and
let the user drag the mouse with the button pressed to draw, like
in a paint program.

Clicking for Dots


We’ll build our ClickDots.py program using the same steps as
in ShowPic.py (page 184) with a setup, a game loop, and an exit.
Pay extra attention to the event-handling portion of the game loop,
since that’s where we’ll add the if statement that will process
mouse clicks.

s tupe
Here are our first few lines of setup. Start a new file and save it as
ClickDots.py (the final program is shown on page 210).

import pygame # Setup
pygame.init()
screen = pygame.display.set_mode([800,600])
pygame.display.set_caption("Click to draw")

Our setup begins with import pygame and pygame.init() as usual,
and then we create a screen object as our drawing window display.
This time, though, we’ve added a title, or caption, to the window
with pygame.display.set_caption(). This lets the user know what
the program is. The argument we pass to set_caption() is a string
of text that will appear on the title bar of the window, as shown at
the top of Figure 9-1.
Free download pdf