如何添加不要求用户输入输入的时间限制?

时间:2019-05-03 08:29:21

标签: python

我正在为学校编码“挑战”编写一个很小的,不太出色的游戏,我需要为某个动作设置一个时限,同时引入一个按键来进入系统。我有一个完整的游戏计时器,但是我的游戏是基于射击外星人的,所以我希望在外星人回弹之前每波都有时间限制。另外,如何获得输入以自动为用户输入? (例如,要射击,您必须按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

restart()

2 个答案:

答案 0 :(得分:0)

这应该做到:

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()

答案 1 :(得分:0)

这是解决您问题的可能方法。

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'herehere的信息。

如果您有更多输入选择,我会使用ENUM。如果输入不正确(数字或其他字符),我也不会输出任何警告,因此您可以进行更多操作。