我正在为一个学校编码“挑战”写一个不是很棒的小游戏,我需要在引入按键进入系统的同时设置一个特定动作的时间限制。我有一个完整的游戏定时器,但我的游戏是基于射击外星人,我希望在外星人射击之前每波的时间限制。另外,我如何为用户获取自动进入的输入?(例如,要射击,你必须按P键,但在游戏中,你必须键入P然后回车)。
#Main Code
print("An Alien has appeared! They are shooting in 5 seconds!")
#MAIN TIMER START
start = time.time()
decision = input("Will you shoot (P) or deflect (O)?")
if input == "P":
decision = shoot
elif input == "p":
decision = shoot
elif input == "O":
decision = deflect
elif input == "o":
decision = deflect重新启动()
发布于 2019-05-03 16:41:21
这应该可以做到:
from threading import Timer
timeout = 10
t = Timer(timeout, print, ["\n" + 'Sorry, times up'])
t.start()
decision = input("Will you shoot (P) or deflect (O)?")
if input == "P":
decision = "shoot"
t.cancel()
elif input == "p":
decision = "shoot"
t.cancel()
elif input == "O":
decision = "deflect"
t.cancel()
elif input == "o":
decision = "deflect"
t.cancel()发布于 2019-05-03 17:12:42
这是你的问题的一个可能的解决方案。
import sys
from select import select
timeout_sec = 5
available_decisions = ['o', 'p']
print("An Alien has appeared! They are shooting in {} seconds!".format(timeout_sec))
print("Will you shoot (P) or deflect (O)?")
if select( [sys.stdin], [], [], timeout_sec ):
user_input = sys.stdin.readline().strip()
user_input = user_input.lower()
if user_input in available_decisions:
print("Your choice:", user_input)
if user_input == "p":
decision = 'shoot'
else:
decision = 'deflect'
else:
print("You're dead!!")
print("Action: {}".format(decision))您可以阅读模块'sys‘和'select’here和here。
如果你有更多的输入选择,我会使用ENUM。如果输入不正确(数字或其他字符),我也没有输出任何警告,所以您可以多做一点工作。
https://stackoverflow.com/questions/55966008
复制相似问题