输入问题和 sleep.time()

Trouble with inputs and sleep.time()

我正在尝试制作一个基于文本的小游戏,但我在使用 while 循环时遇到了问题。我已经试验了好几个小时了!如果您能帮助我,我将不胜感激。感谢阅读 :D

我基本上想要它,以便用户必须在计时器用完之前按下一个按钮,如果他没有及时按下按钮,那么熊就会吃掉他。 :')

这是我的代码:

import time
cash = 0
def dead():
    print("You are dead!")
    main()
    points = 0
def adventure_1(inventory, cash):
    points = 0
    time1 = 2
    if time1 < 3:
        time.sleep(1)
        time1 -= 1
        bear = input("A bear is near... Hide Quickly! Enter: (C) to CLIMB a Tree")



        #Ran out of time death
        if time1 == 0:
            dead()

        #Climb away from bear
        elif bear == 'c' or 'C':
            print("Your safe from the bear")
            points += 1
            print("You recieved +2 points")#Recieve points
            print("You now have : ",points,"points")
            adventure_2()#continue to adventure 2


        #Invalid input death
        elif bear != 's' or 'S':
            dead()


def adventure_2(inventory, cash):
    points = 2
    time = 5
t_0 = time.time()
bear = input("A bear is near... Hide Quickly! Enter: (C) to CLIMB a Tree")
if abs(t_0 - time.time()) > time_threshold:
    #player has died

在 python 中,输入语句使程序流程等待,直到玩家输入一个值。

if time1 < 3:
        time.sleep(1)
        time1 -= 1
        #line below causes the error
        bear = input("A bear is near... Hide Quickly! Enter: (C) to CLIMB a Tree")

要克服这个问题,您可以使用类似于下面代码的东西,这是一个工作示例。我们可以通过使用计时器查看玩家是否输入任何内容来克服程序流程中的中断,如果他没有输入任何内容,我们会捕获异常并继续程序流程。

from threading import Timer

def input_with_timeout(x):    
    t = Timer(x,time_up) # x is amount of time in seconds
    t.start()
    try:
        answer = input("enter answer : ")
    except Exception:
        print 'pass\n'
        answer = None

    if answer != True:  
        t.cancel()       

def time_up():
    print 'time up...'

input_with_timeout(5) 

因此,如您所见,我们可以解决等待玩家输入值的问题,方法是使用计时器计算玩家花费的时间,然后继续捕获未发送输入的异常,最后,继续我们的计划。