0

I'm writing a small not-so-great game for a school coding "challenge" and I need to set a time limit on a certain action whilst introducing a press key to enter system. I have a full game timer, but my game is based on shooting aliens and I want a time limit for each wave before the alien shoots back. Also how can I get an input to auto-enter for the user? (e.g. to shoot, you have to press P, but in-game you have to type P then enter).

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

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • You code will not work because you have the variable `input` that you test does not exist. To avoid issues with case, you can use `.upper()` on your variable so you only have to test for "P" and "O". – Guimoute May 03 '19 at 08:49

2 Answers2

0

this should do it:

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

Here is a possible solution to your problem.

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

You can read about the modules 'sys' and 'select' here and here.

If you have more input choices I would use ENUM. I also didn't output any warning if the input is incorrect (number or other character), so you can work on it a little bit more.

Raphael
  • 959
  • 7
  • 21