简体   繁体   中英

How to make a “while mouse down” loop in pygame

So I currently have this code for an airbrush in a drawing app. When the function is active, it should draw on a canvas, basically like an airbrush. But right now, I don't know how to make pygame detect a mouse down or mouse up and make a while loop out of it. Here is the code:

def airbrush():
    airbrush = True
    cur = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    while click == True:
        pygame.draw.circle(gameDisplay, colorChosen, (cur[0] + random.randrange(brushSize), cur[1] + random.randrange(brushSize)), random.randrange(1, 5))
        pygame.display.update()
        clock.tick(60)

Right now, I have "while click" which doesn't work. What should I replace "click" with to make this work so that while the mouse is held down, it paints, but when the mouse is "up", it stops?

The state which is returned by pygame.mouse.get_pressed() is evaluated once when pygame.event.get() is called. The return value of pygame.mouse.get_pressed() is tuple with th states of the buttons.

Don't implement a separate event handling in a function. Do the event handling in the main loop:

done = False
while not done:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    airbrush()
    pygame.display.flip()

Evaluate the current state of a button (eg left button), of the current frame, in the function airbrush :

def airbrush():
    airbrush = True
    cur = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if click[0] == True: # evaluate left button
        pygame.draw.circle(gameDisplay, colorChosen, (cur[0] + random.randrange(brushSize), cur[1] + random.randrange(brushSize)), random.randrange(1, 5))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM