To draw a continual line in the window, instead of single squares, we need to draw a line between the last position of the mouse and the next position of the mouse. This will then draw the line to bridge any gaps if the mouse moves too fast for the main loop. This means storing the position of the mouse in the last loop and then drawing a line from the last position of the mouse to the position of the mouse in the current loop. You can do it like this:
last_mouse_pos $=(0,0)$
while not done:
for event in pygame.event.get () :
elif event.type == MOUSEBUTTONDOWN and \
event.button == 1:
mouse_down = True
last_mouse_pos = pygame.mouse.get_pos()
..
elif event.type == MOUSEMOTION and \
mouse_down is True:
pygame.draw.line(screen, white,
last_mouse_pos,
pygame.mouse.get_pos(),
5)
last_mouse_pos = pygame.mouse.get_pos()
pygame.display.update()
Instead of drawing the square as a point under the mouse, a line is created with the pygame. draw. line () function. It takes as parameters the screen, line color, starting pixel position, ending pixel position, and line width.
You will now have the ability to scrawl in white on the window, as shown in Figure 7.2:
(Figure can't copy)
Often, when using a mouse in a graphics environment, the user will want to click on a button or object. This involves calculating whether the mouse position is inside the visual boundaries of the object. For a button, which is basically a rectangle, the mouse position must be inside the range of the button's top-left and bottom-right coordinates, as shown in Figure 7.3:
(Figure can't copy)
Given these values, the logic to determine whether the mouse is inside the button boundaries is as follows:
if $x<m x<(x+$ width $)$ and $y<m y<(y+h e i g h t)$