User Interaction: Get into the Game 213
Next, we’ll add event handlers to our game loop. These event
handlers will set mousedown to True if the user is holding down the
mouse and False if not.
Game Loop: handling mouse Presses and releases
Make your game loop look like this:
while keep_going: # Game loop
for event in pygame.event.get(): # Handling events
if event.type == pygame.QUIT:
keep_going = False
u if event.type == pygame.MOUSEBUTTONDOWN:
v mousedown = True
w if event.type == pygame.MOUSEBUTTONUP:
x mousedown = False
y if mousedown: # Draw/update graphics
z spot = pygame.mouse.get_pos()
{ pygame.draw.circle(screen, YELLOW, spot, radius)
| pygame.display.update() # Update display
The game loop starts just like our other Pygame apps, but
at u, when we check to see whether the user has pressed one of
the mouse buttons, instead of drawing immediately, we set our
mousedown variable to True v. This will be the signal our program
needs to begin drawing.
The next if statement at w checks whether the user has
released the mouse button. If so, the line at x changes mousedown
back to False. This will let our game loop know to stop drawing
whenever the mouse button is up.
At y, our for loop is over (as we can see by the indentation),
and our game loop continues by checking whether the mouse button
is currently pressed (that is, if mousedown is True). If the mouse button
is down, the mouse is currently being dragged, so we want to allow
the user to draw on the screen.
At z, we get the current location of the mouse directly, with
spot = pygame.mouse.get_pos(), rather than pulling the position of the
last click, because we want to draw wherever the user is dragging
the mouse, not just at the location where they first pressed the but-
ton. At {, we draw the current circle on the screen surface, in the
color specified by YELLOW, at the (x, y) location spot where the mouse
is currently being dragged, with the radius of 15 that we specified
in the setup section of our code. Finally, we finish the game loop
at | by updating the display window with pygame.display.update().