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

(vip2019) #1
User Interaction: Get into the Game 211

if event.type == pygame.MOUSEBUTTONDOWN:
spot = event.pos
pygame.draw.circle(screen, RED, spot, radius)
pygame.display.update() # Update display


pygame.quit() # Exit


This program is short but enables the user to draw pictures
one dot at a time, as shown back in Figure 9-1. If we want to draw
continuously as we drag the mouse with the button pressed, we just
need to handle one more type of mouse event, pygame.MOUSEBUTTONUP.
Let’s give that a try.


Dragging to Paint


Now let’s create a more natural drawing program, DragDots.py,
that lets the user click and drag to draw smoothly, as with a paint-
brush. We’ll get a smooth, interactive drawing app, as shown in
Figure 9-2.


Figure 9-2: Our DragDots.py program is a fun way to paint!


To create this effect, we need to change the logic of our pro-
gram. In ClickDots.py, we handled MOUSEBUTTONDOWN events by just
drawing a circle at the location of the mouse button click event. To
draw continuously, we need to recognize both the MOUSEBUTTONDOWN

Free download pdf