Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping mousebutton down to draw lines

Tags:

python

pygame

Need to draw lines rather than dots with mousebuttondown

When mouse is clicked program draws dots, I assume another loop is needed to draw lines with the mouse button held down.


while keep_going:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            keep_going = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            spot = event.pos
            pygame.draw.circle(screen, GREEN, spot, radius)
            pygame.display.update()

I would like to draw lines instead of dots in my window.

like image 323
Ewanziak Avatar asked Oct 15 '25 07:10

Ewanziak


1 Answers

Use pygame.draw.lines, to connect a point list by a line.

Append the current mouse position to a list, if the mouse button is released:

if event.type == pygame.MOUSEBUTTONUP:
    points.append(event.pos)

Draw the list of points, if there is more than 1 point in the list:

if len(points) > 1:
    pygame.draw.lines(screen, (255, 255, 255), False, points, width)

Draw a "rubber band" from the last point in the list to the current mouse position:

if len(points):
    pygame.draw.line(screen, (255, 255, 255), points[-1], pygame.mouse.get_pos(), width)

See the simple example:

run = True
width = 3
points = []
while run:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.MOUSEBUTTONUP:
            points.append(event.pos)

    screen.fill(0)
    if len(points) > 1:
        pygame.draw.lines(screen, (255, 255, 255), False, points, width)
    if len(points):
        pygame.draw.line(screen, (255, 255, 255), points[-1], pygame.mouse.get_pos(), width)
    pygame.display.flip()
like image 57
Rabbid76 Avatar answered Oct 17 '25 22:10

Rabbid76