python - 如何制作一个返回鼠标释放后经过的时间量的计时器
问题描述
例如你按下你的RMB并保持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)
推荐阅读
- octave - 软件包未安装
- typescript - 如何在 TypeScript 中使用扩展运算符组合对象
- sql - 查询oracle中保留原始删除重复记录
- hibernate - 根据 HQL 查询结果动态生成 javaFX TableView 的列和行
- javascript - 控制 indexedDB 中相对于异步请求的清理功能的执行顺序?
- python - 未发送 JSON 数据 - Django Rest Framework / React
- arrays - 如何在 Angular Typescript 中将数组作为表单数据发布
- yaml - 版本化 yaml 文件的最佳方法是什么?
- google-cloud-platform - Terraform:未创建 google_sql_database_instance
- android - 旋转活动时如何不破坏 ViewModel