首页 > 解决方案 > 按回车躲避...(快速时间事件)[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)

有没有其他更容易做到这一点的方法?

如果我遗漏了什么,请告诉我......我还是比较新的,想学习。谢谢 :)

标签: pythonpython-3.xinputtime

解决方案


为简单起见,您可以跟踪提示用户的时间以及他们输入响应后的时间。减去两者是他们的反应时间,您可以将其与超时进行比较。

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)

推荐阅读