python - 按回车躲避...(快速时间事件)[Python 3]
问题描述
我一直在寻找这个答案的stackoverflow,但我似乎找不到任何更新的答案。
我希望有一个提示说Press enter to dodge
(它可以是像空格这样的任何按钮,如果我猜这样更容易的话if keyboard.is_pressed
)
必须同时有一个从整数变量倒计时的计时器,timer
当它达到零时,它会告诉用户他们被击中并设置dodge = False
,否则,如果他们确实按下了键,它会告诉他们他们躲避并设置dodge = True
我一直在尝试,但效果不佳,因为无论他们是否及时闪避,它总是检测到正在按下输入:
from threading import Timer
dodge = False
timeout = 3
t = Timer(timeout, print, ['You were hit!'])
t.start()
prompt = f"You have {timeout} seconds to dodge, press enter...\n"
answer = input(prompt)
t.cancel()
if answer == " ":
print("You didn't dodge!")
dodge = False
else:
print("You dodged")
dodge = True
print(dodge)
有没有其他更容易做到这一点的方法?
如果我遗漏了什么,请告诉我......我还是比较新的,想学习。谢谢 :)
解决方案
为简单起见,您可以跟踪提示用户的时间以及他们输入响应后的时间。减去两者是他们的反应时间,您可以将其与超时进行比较。
from threading import Timer
import time
timeout = 3
t = Timer(timeout, print, ["You were hit!"])
t.start()
start_time = time.time()
prompt = f"You have {timeout} seconds to dodge, press enter...\n"
answer = input(prompt)
t.cancel()
end_time = time.time()
reaction_time = end_time - start_time
if reaction_time > timeout:
print("You didn't dodge!")
dodge = False
else:
print("You dodged")
dodge = True
print(dodge)
推荐阅读
- scala - Spark中两个大型数据集之间的交叉连接
- android - 删除或重命名 Play 商店包,以便我可以重新发布
- ruby - 找出数组中有多少元素包含数字
- firebase - Firebase/Firestore 未正确刷新数据
- javascript - 如何让用户输入在点击事件的函数中运行?
- php - 如何将简单的文件路径数组转换为表示 PHP 中文件层次结构的嵌套数组?
- excel - 如何格式化大型数据集的单列中的选择单元格
- c++ - 如何将项目共享“系统调用”作为单例对象构建和链接到引导加载程序?
- python - 将 csv 文件编号转换为书面段落?
- jquery - 删除元素后简单的按钮功能停止