0

I'm trying to make a little text based game, but I am having trouble with a while loop. I have experimented for many hours now! I would much appreciate it if you could kindly help me out. Thank-you for reading :D

I basically want it so that the user has to press a button before the timer runs out, and if he doesn't do it in time then the bear eats him. :')

Here is my code:

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
Sam
  • 11
  • 2

2 Answers2

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
Jeff Mandell
  • 863
  • 7
  • 16
0

In python the input statement makes it so the programs flow waits until the player has entered a value.

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

To over come this you can use something similar to the code below which is a working example. We can over come the break in the program flow by using a Timer to see if the player has inputted anything, if he has not we catch the exception and continue with the programs flow.

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) 

So as you can see we can over come the issue of waiting for our player to input a value by using a timer to count how long the player is taking, then proceeding to catch the exception from no input being sent, and finally, continuing with our program.

Ryan
  • 1,972
  • 2
  • 23
  • 36
  • Okay, I see. Well i'm going to go watch some tutorials on 'threading'. Thank-you for your reply! – Sam Nov 19 '15 at 20:58