我试图制作一个基于文本的小游戏,但我遇到了一个while循环的问题。我现在已经实验了好几个小时!如果你能帮助我,我将非常感激。感谢您阅读:D
我基本上想要它,以便用户必须在计时器用完之前按下按钮,如果他没有及时做到,那么熊就会吃掉它。 :&#39)
这是我的代码:
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
答案 0 :(得分:0)
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
答案 1 :(得分:0)
在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")
为了解决这个问题,你可以使用类似于下面代码的东西,这是一个有效的例子。我们可以通过使用Timer查看播放器是否已输入任何内容,如果他还没有捕获异常并继续执行程序流程,那么我们就可以完成程序流程的中断。
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)
因为你可以看到我们可以通过使用计时器来计算玩家的持续时间来等待我们的玩家输入一个值的问题,然后继续从没有输入发送中捕获异常,最后继续我们的计划。