Search code examples
pythonpygamepygame-clock

Stopwatch between mouse up/down


I am trying to test the time between mouse down and mouse up events by using a simple stopwatch in a while loop. The mouse down event works fine, but when i release the mouse for mouse up, the seconds continue to go up and do not stop.

from pygame import *
import time
screen = display.set_mode((160, 90))
sec = 0
while True:
    new_event = event.poll()
    if new_event.type == MOUSEBUTTONDOWN:
        while True: # Basic stopwatch started
            time.sleep(1)
            sec += 1
            print(sec)
            # In loop, when mouse button released,
            # supposed to end stopwatch
            if new_event.type == MOUSEBUTTONUP:
                break
    display.update()

I want the stopwatch to end after the mouse is released. eg. If the mouse is just clicked, the seconds should be 1. If the mouse is held for 5 seconds, it should not continue past 5.


Solution

  • Use pygame.time.get_ticks to get the number of milliseconds since pygame.init() was called.
    Store the milliseconds when MOUSEBUTTONDOWN and calculate the time difference in the main loop:

    from pygame import *
    
    screen = display.set_mode((160, 90))
    
    clock = time.Clock()
    run = True
    started = False
    while run:
    
        for new_event in event.get():
            if new_event.type == QUIT:
                run = False
    
            if new_event.type == MOUSEBUTTONDOWN:
                start_time = time.get_ticks()
                started = True
    
            if new_event.type == MOUSEBUTTONUP:
                started = False
    
        if started:        
            current_time = time.get_ticks()
            sec = (current_time - start_time) / 1000.0
            print(sec)
    
        display.update()