Trouble with inputs and sleep.time() - python

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

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.

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

Related

A timer for the rocket lift off

i would like to have a countdown for my rocket to life off but i just cant make it decrease the number it only stays the same can someone help me?
print("program is writen by someone")
name = input("program is runned by")
print(name,",if you are a pilot of the project please type pilot for the next question. If you are other please type your reason/role for u being here")
x = input("what is your reason for u being here")
if x == 'pilot':
print (name,"ok wlecome to the crew")
h = input ("is the hatch closed? please answer closed or no")
if h == 'closed':
import time as t
second = int(input ("very good please enter the needed for the countdown"))
for i in range(second):
print (str(second - 1)+ "second remaining \n")
t.sleep(1)
print ("time is up")
else:
print ("please check if the hatch is close")
else:
y = input("are you 600meters away from the spacecraft?")
if y == 'yes':
print ("have a nice time watching the show")
else:
print("please stand back untill u are 600 meter away from the aircraft")
You're not using the loop variable and printing the same second-1 value every time. You can use a decreasing range, e.g.:
for i in range(second, 0, -1):
print(f'{i} seconds remaining')
time.sleep(1)
or simply a while-loop:
while second:
print(f'{second} seconds remaining')
second -= 1
time.sleep(1)
(Notice that time.sleep() is called inside the loop body)

Why does it keep saying "Syntax error" when I use multiple "if" loops?

I tried to program a "make your own adventure" story with python, and I tried using multiple "if" loops. However, the program keeps saying "syntax error." Can someone tell me why this is happening and state a possible solution?
a = eval(input("Enter 0 to go on the ladder, and 1 to try out you new pair of plunger boots: "))
if a == 1:
print("You put on the boots and climb on the side of the ship. You put one foot forward, then the next, then you try to take a step.")
time.sleep(10)
print("However, the boots won't budge.")
time.sleep(2)
print("MISSION FAIL")
time.sleep(1)
else:
print("You climb up the ladder.")
time.sleep(2)
print("You see a guard at the top armed with an automatic rifle.")
time.sleep(4)
print("You can use the grenade in your pocket, or you can take him out with your pack of C4")
time.sleep(5)
b = eval(input("Enter 0 for grenade, 1 for the pack of C4: ")
if b == 0:
print("You throw the grenade up.")
time.sleep(3)
print("You hear a smack, and you see the grenade coming back down at you.")
time.sleep(4)
print("MISSION FAIL")
print("Mental note: These guards are known for their fast reflexes.")
time.sleep(3.5)
It's a missing ")" on your b = eval(...) line.
should be
b = eval(input(...))
and it's
b = eval(input(...)
Thus, syntax error.

Python Main Loop + Sub Loop with timeout

I would like to achieve the following.
I have a proof of concept I am working.
I have Individual "Named RFID"Cards, then I have "Action RFID Cards".
So I might have cards like this:
Names
John - 12345
Mary - 12346
Actions
Start Work - 111
Finish Work - 222
Lunch - 333
So John Swipes his own card, then swipes an action card, which logs his action.
-Start Script
-Wait for User Card Input
-Once Input Received and Validated
- Wait for Action Card Input
- Start Timer
- Wait until Action Card Input matches a valid Action
- If a match, exit back to the main loop
- If no match, wait for one minute, then exit
-Continue Main Loop
I am reusing code from :
How would I stop a while loop after n amount of time?
import time
timeout = time.time() + 60*5 # 5 minutes from now
while True:
test = 0
if test == 5 or time.time() > timeout:
break
test = test - 1
and a Python Game example which waits and loops forever playing the game
https://dbader.org/blog/python-intro-reacting-to-user-input
My code for testing is as follows (I am not doing a card or action lookup at this point, expecting the user to be 12345 and card to be 54321: (the requirement for four spaces for indent has possibly broken Python Indent)
#
# Guess My Number
#
import random
import time
# Set our game ending flag to False
game_running = True
while game_running:
# Greet the user to our game
print()
print("I'm thinking of a number between 1 and 10, can you guess it?")
# Have the program pick a random number between 1 and 10
#secret_number = random.randint(0, 10)
secret_number = 12345
card_number_list = 54321
# Set the player's guess number to something outside the range
guess_number = -1
# Loop until the player guesses our number
while guess_number != secret_number:
# Get the player's guess from the player
print()
guess = input("Please enter a number: ")
# Does the user want to quit playing?
if guess == "quit":
game_running = False
break
# Otherwise, nope, the player wants to keep going
else:
# Convert the players guess from a string to an integer
guess_number = int(guess)
# Did the player guess the program's number?
if guess_number == secret_number:
print()
print("Hi you have logged on, please swipe Card- if you don't Swipe - will timeout in 1 minute!")
timeout = time.time() + 60*1 # 1 minutes from now
while True:
test = 0
if test == 1 or time.time() > timeout:
card = input("Please enter your card number")
card_number = int(card)
if card_number == card_number_list:
print("Thanks for your card number")
test = 1
break
test = test - 1
# Otherwise, whoops, nope, go around again
else:
print()
print("You need to use your wrist band first...")
# Say goodbye to the player
print()
print("Thanks for playing!")
But instead of exiting, the script waits...
Any feedback appreciated - I have basic python skills and am trying to reuse existing code where possible (with thanks to the creators!).
The python input() function will always wait for response from the keyboard before returning. Take a look at this answer for a technique to accomplish what you want.

The script is not assigning points to the attribute

I'm trying to create a text-based adventure game and all is going well until I encountered a problem with assigning points to attributes. I've been using this website to help with the process but realized that it might be in Python 2. Here's all that I've done so far code:
#Date started: 3/13/2018
#Description: text-based adventure game
import random
import time
def display_intro():
print('It is the end of a 100-year war between good and evil that had \n' +
'killed more than 80% of the total human population. \n')
time.sleep(3)
print('The man who will soon be your father was a brave adventurer who \n' +
'fought for the good and was made famous for his heroism. \n')
time.sleep(3)
print('One day that brave adventurer meet a beautiful woman who he later \n' +
'wed and had you. \n')
time.sleep(3)
def get_gender(gen=None):
while gen == None: # input validation
gen = input('\nYour mother had a [Boy or Girl]: ')
return gen
def get_name(name = None):
while name == None:
name = input("\nAnd they named you: ")
return name
def main():
display_intro()
gender_num = get_gender()
charater_name = get_name()
print("You entered {} {}.".format(gender_num, charater_name))
if __name__ == "__main__":
main()
character_name = get_name()
# Assignning points Main
my_character = {'name': character_name, 'strength': 0, 'wisdom': 0, 'dexterity': 0, 'points': 20}
#This is a sequence establises base stats.
def start_stat():
print("\nThis is the most important part of the intro\n")
time.sleep(3)
print("This decides your future stats and potentially future gameplay.")
time.sleep(4)
print("\nYou have 20 points to put in any of the following category:
Strength, Health, Wisdom, or Dexterity.\n")
def add_charater_points(): # This adds player points in the beginnning
attribute = input("\nWhich attribute do you want to assign it to? ")
if attribute in my_character.keys():
amount = int(input("By how much?"))
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character[attribute] -= amount
else:
print("That attribute doesn't exist!!!")
def print_character():
for attribute in my_character.keys():
print("{} : {}".format(attribute, my_character[attribute]))
playContinue = "no"
while playContinue == "no":
Continue = input("Are you sure you want to continue?\n")
if Continue == "yes" or "Yes" or "y":
playContinue = "yes"
start_stat()
add_charater_points()
else:
display_intro()
gender_num = get_gender()
charater_name = get_name()
running = True
while running:
print("\nYou have {} points left\n".format(my_character['points']))
print("1. Add points\n2. Remove points. \n3. See current attributes. \n4. Exit\n")
choice = input("Choice: ")
if choice == "1":
add_charater_points()
elif choice == "2":
pass
elif choice == "3":
print_character()
elif choice == "4":
running = False
else:
pass
And here's what happens when I run it:
It is the end of a 100-year war between good and evil that had
killed more than 80% of the total human population.
The man who will soon be your father was a brave adventurer who fought for
the good and was made famous for his heroism.
One day that brave adventurer meet a beautiful woman who he later wed and
had you.
Your mother had a [Boy or Girl]: boy
And they named you: Name
You entered boy Name.
And they named you: Name
Are you sure you want to continue?
yes
This is the most important part of the intro
This decides your future stats and potentially future gameplay.
You have 20 points to put in any of the following category: Strength,
Health, Wisdom, or Dexterity.
Which attribute do you want to assign it to? strength
By how much? 20
You have 20 points left
1. Add points
2. Remove points.
3. See current attributes.
4. Exit
Choice: 3
name : Name
strength : 0
wisdom : 0
dexterity : 0
points : 20
You have 20 points left
1. Add points
2. Remove points.
3. See current attributes.
4. Exit
Choice:
Oh, and prompt for the name of the play goes again twice for some reason. Also, what does the my_character.keys() under def add_charater_points() mean? Since I just started to learn to code python, if there are any other tips you guys can give me it would be greatly appreciated.
The last two lines of this snippet
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character[attribute] -= amount
add the character points to the attribute, and immediately subtract them again. I think you might mean
my_character['points'] -= amount
Your repeated prompt is probably because you have a whole lot of code that logically seems to belong in function main() but is coded to run after main() finishes.

python -- Crash when trying to deal with unexpected input

So, I'm just fooling around in python, and I have a little error. The script is supposed to ask for either a 1,2 or 3. My issue is that when the user puts in something other than 1,2 or 3, I get a crash. Like, if the user puts in 4, or ROTFLOLMFAO, it crashes.
EDIT: okay, switched it to int(input()). Still having issues
Here is the code
#IMPORTS
import time
#VARIABLES
current = 1
running = True
string = ""
next = 0
#FUNCTIONS
#MAIN GAME
print("THIS IS A GAME BY LIAM WALTERS. THE NAME OF THIS GAME IS BROTHER")
#while running == True:
if current == 1:
next = 0
time.sleep(0.5)
print("You wake up.")
time.sleep(0.5)
print("")
print("1) Go back to sleep")
print("2) Get out of bed")
print("3) Smash alarm clock")
while next == 0:
next = int(input())
if next == 1:
current = 2
elif next == 2:
current = 3
elif next == 3:
current = 4
else:
print("invalid input")
next = 0
Use raw_input() not input() the latter eval's the input as code.
Also maybe just build a ask function
def ask(question, choices):
print(question)
for k, v in choices.items():
print(str(k)+') '+str(v))
a = None
while a not in choices:
a = raw_input("Choose: ")
return a
untested though
since the input() gives you string value and next is an integer it may be the case that crash happened for you because of that conflict. Try next=int(input()) , i hope it will work for you :)

Categories

Resources