例如,您按下人民币并保持3秒钟,然后放开。因此该函数将返回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)
编辑::我也留下了上面的代码以供参考,但是下面的代码仅在释放鼠标时返回值。它使用pygame.MOUSEBUTTONDOWN
和pygame.MOUSEBUTTONUP
。我也把它设为一类,只是为了避免必须全局声明所有内容。
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句