210 Chapter 9
At u, we handle the pygame.QUIT event by setting our loop vari-
able keep_going to False.
The second if statement, at v, handles a new event type: the
pygame.MOUSEBUTTONDOWN event that tells us that the user has pressed
one of the mouse buttons. Whenever the user presses a mouse but-
ton, this event will appear in the list of events that our program
gets from pygame.event.get(), and we can use an if statement both
to check for the event and to tell the program what to do when the
event occurs. At w, we create a variable called spot to hold the x-
and y-coordinates of the mouse’s position. We can get the location
of the mouse-click event with event.pos; event is the current event in
our for loop. Our if statement has just verified that this particular
event is of type pygame.MOUSEBUTTONDOWN, and mouse events have a pos
attribute (in this case, event.pos) that stores the (x, y) coordinate
pair telling us where the mouse event occurred.
Once we know the location
on the screen where the user clicked
the mouse button, at x we tell the
program to draw a filled circle on
the screen surface, in the RED color
from our setup, at the location spot,
with the radius of 15 we specified in
our setup.
Putting It all together
The only thing left to do is update the display and tell our pro-
gram what to do when it’s time to exit. Here’s the full program for
ClickDots.py.
ClickDots.py
import pygame # Setup
pygame.init()
screen = pygame.display.set_mode([800,600])
pygame.display.set_caption("Click to draw")
keep_going = True
RED = (255,0,0) # RGB color triplet for RED
radius = 15
while keep_going: # Game loop
for event in pygame.event.get(): # Handling events
if event.type == pygame.QUIT:
keep_going = False