【问题标题】:How do I add a time limit which doesn't require the user to enter the input? [duplicate]如何添加不需要用户输入的时间限制? [复制]
【发布时间】:2019-09-21 18:37:29
【问题描述】:

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

重启()

【问题讨论】:

  • 您的代码将无法工作,因为您测试的变量input 不存在。为避免大小写问题,您可以在变量上使用.upper(),这样您只需测试“P”和“O”。

标签: python


【解决方案1】:

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

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。如果输入不正确(数字或其他字符),我也没有输出任何警告,所以你可以多做一点。

【讨论】:

    【解决方案2】:

    应该这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 2021-06-19
      • 2017-11-06
      相关资源
      最近更新 更多