如何制作一个计时器 returns 释放鼠标后经过的时间

How to make a timer that returns the amount of time passed after mouse is released

比如你按住人民币3秒然后松开。所以函数将 return 3.

running = True
timer = 0

while running:
if pygame.mouse.get_pressed(3)[2]:
      timer += 33.3
elif timer:
      print("%.2f" % (timer / 1000))
      timer = 0
for event in pygame.event.get():
     if event.type = pygame.QUIT:
           running = False

pygame.time.Clock().tick(30)

这是一个好习惯吗?

像这样

import pygame
import time

#create window
win = pygame.display.set_mode((500, 500))

#take start time, end time and bool is mouse is pressed
def get_time(start, end, pressed):

    #calculate time
    timer = end - start

    #return timer if it is pressed
    if pressed:
        return timer


#get start time
start = time.time()

while True:
    pygame.event.get()

    #get if RMB is pressed
    pressed = pygame.mouse.get_pressed()[2]

    #calculate current time
    now = time.time()

    #call the function and store the return value in a variable
    timepressed = get_time(start, now, pressed)

    #print the value
    print(timepressed)
    

编辑::我也留下了上面的代码以供参考,但下面的代码仅 returns 释放鼠标时的值。它使用 pygame.MOUSEBUTTONDOWNpygame.MOUSEBUTTONUP。我还把它设为 class 只是为了避免必须将所有内容都声明为全局。

import pygame
import time

#create window
win = pygame.display.set_mode((500, 500))

class Timer:
    def __init__(self):
        #start time
        self.start = time.time()

        #timer is the amount of time passed after mouse is pressed
        self.timer = 0

        #mouse button up
        self.up = False

        #mouse button down
        self.down = False

        #if rmb is held down
        self.rmb = False

        #now 
        self.now = 0


    #update now
    def update(self):
        self.now = time.time()


    def timeRMB(self):
        #if rmb is pressed and pygame mouse button down is true
        if self.rmb:
            if self.down:
                #actual timer
                self.timer = self.now - self.start

        else:
            #if mouse button up is true
            if self.up:
                #reset the timer 
                self.start = self.now
                return self.timer
            
        

#get start time
timer = Timer()

while True:
    events = pygame.event.get()

    #get if RMB is pressed
    timer.rmb = pygame.mouse.get_pressed()[2]


    #get mouse events
    for event in events:
        if event.type == pygame.MOUSEBUTTONDOWN:
            timer.down = True
        if not event.type == pygame.MOUSEBUTTONDOWN:
             timer.down = False
        if event.type == pygame.MOUSEBUTTONUP:
            timer.up = True
        if not event.type == pygame.MOUSEBUTTONUP:
            timer.up = False

    timer.update()

    #call the function and store the return value in a variable
    timepressed = timer.timeRMB()

    print(timepressed)