A timer for the rocket lift off - python

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)

Related

How do I implement a timer on each question asked in a quiz?

I was attempting to create a quiz and one of the criteria is to limit the time available to solve for each question in the quiz. I looked up certain tutorials but some require an input of x seconds for the timer to go off while others looked more like a stopwatch...
I was wondering how do I do like a background timer that ticks down as soon as the question is printed out and skips to the next question if, for example the 30-second period has ended? I'm clueless in the timer function and was having problems to even try to implement them onto my codes. Could someone give out a few pointers so I can sorta progress further in implementing a working timer?
Thank you!
EDITED section below:
The timer that I want to implement onto my coding:
import time
import threading
def atimer():
print("Time's up.")
a_timer = threading.Timer(10.0, atimer)
a_timer.start()
print("")
This is the whole coding that I tried to implement the timer into.
I noticed that when I tried to define qtimer to just print 1 or 2 lines of statements the timer works but I want the timer to stop and go to second question or stop and give the user another attempt to retry the question, so I tried to attach a bunch of codes after the definition and it didn't work. I know I'm most probably doing something wrong here since I'm not quite familiar with time or threading functions. Is there a workaround?
def qtimer():
print("I'm sorry but your time is up for this question.")
print("You may have another attempt if you wish to, with reduced marks allocated.")
response1 = input("Type 'Yes' for another attempt, anything else to skip: ")
if response1 == "Yes":
Answ = input("Which option would you go for this time?: ")
Answ = int(Answ)
if possible[Answ - 1] == qaItem.corrAnsw:
print("Your answer was correct.")
corr += 1
marks += 0.5 * qaItem.diff
else:
print("Your answer was wrong.")
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
else:
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
class A:
def __init__(self, question, correctAnswer, otherAnswers, difficulty, explanation):
self.question = question
self.corrAnsw = correctAnswer
self.otherAnsw = otherAnswers
self.diff = difficulty
self.expl = explanation
qaList = [A("What is COVID-19?", "Coronavirus Disease 2019", ["Wuhan virus", "I don't understand...", "Coronavirus Disease v19"], 1, "Explanation 1"),
A("What describes COVID-19?", "A disease", ["A virus", "A parasite", "A bacteriophage"], 1, "Explanation 2"),
A("What causes COVID-19?", "SARS-CoV-2", ["Coronavirus", "Mimivirus", "Rubeola Virus"], 1, "Explanation 3"),
A("Which of the following is used in COVID-19 treatment?", "Lopinavir / Ritonavir ", ["Midazolam / Triazolam", "Amiodarone", "Phenytoin"], 2, "Explanation 4"),
A("Which of the following receptors is used by COVID-19 to infect human cells?", "ACE-2 Receptors", ["ApoE4 Receptors", "TCR Receptors", "CD28 Receptors"], 3, "Explanation 5")]
corr = 0
marks = 0
random.shuffle(qaList)
for qaItem in qaList:
q_timer = threading.Timer(5.0, qtimer)
q_timer.start()
print(qaItem.question)
print("Possible answers are:")
possible = qaItem.otherAnsw + [qaItem.corrAnsw]
random.shuffle(possible)
count = 0
while count < len(possible):
print(str(count+1) + ": " + possible[count])
count += 1
print("Please enter the number of your answer:")
Answ = input()
Answ = str(Answ)
while not Answ.isdigit():
print("That was not a number. Please enter the number of your answer:")
Answ = input()
Answ = int(Answ)
Answ = int(Answ)
while Answ > 4 or Answ < 1:
print("That number doesn't correspond to any answer. Please enter the number of your answer:")
Answ = input()
Answ = int(Answ)
if possible[Answ-1] == qaItem.corrAnsw:
print("Your answer was correct.")
corr += 1
marks += 1 * qaItem.diff
else:
print("Your answer was wrong.")
response = input("Would you want to try again? If so, input 'Yes' to attempt it again, if not just input whatever!")
if response == "Yes":
Answ = input("Which option would you go for this time?: ")
Answ = int(Answ)
if possible[Answ - 1] == qaItem.corrAnsw:
print("Your answer was correct.")
corr += 1
marks += 0.5 * qaItem.diff
else:
print("Your answer was wrong.")
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
else:
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
print("You answered " + str(corr) + " of " + str(len(qaList)) + " questions correctly.")
print("You have achieved a total score of " + str(marks) + ".")
Even with a timer, the main thread can't proceed past waiting for the user to input a number; so if the user doesn't nothing, the timer function runs, and once it has finished the main thread is still waiting for input at
print("Please enter the number of your answer:")
Answ = input()
You could have a global flag that the timer thread sets to tell the main thread to treat the input received as response1 in the timer code, and also have a flag to tell the timer that an answer was received, and so on, and it quickly becomes rather complicated.
So rather than trying to work around the blocking call to input by communicating between the timer and main thread, take the non-blocking input example from https://stackoverflow.com/a/22085679/1527 and stop the loop early if the time is up.
def timed_input(msg, timeout=10):
kb = KBHit()
print(msg)
end_time = time.time() + timeout
warn_time = 5
result = None
while True:
if kb.kbhit():
c = kb.getch()
if '0' <= c <= '9':
result = int(c)
break
print(c)
if time.time() > end_time:
print('time is up')
break
if time.time() > end_time - warn_time:
print(f'{warn_time}s left')
warn_time = warn_time - 1
kb.set_normal_term()
return result
# Test
if __name__ == "__main__":
result = timed_input('Enter a number between 1 and 4')
if result is None:
print('be quicker next time')
elif 1 <= result <= 4:
print('ok')
else:
print(f'{result} is not between 1 and 4')
Note also that breaking up into smaller functions helps make the code easier to follow, the logic of the test doesn't need to know about the logic of the timeout.

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.

Trouble with inputs and sleep.time()

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

Nothing happens for either input

I have a feeling I've made a silly mistake somewhere but at nearly 2am I just can't see it...
Here's the code in question. It is part of a function:
running = True
while (running):
playerName = input("Please enter your first name \n").title()
print ("You have entered '%s' as your name. Is this correct?"%playerName)
playerNameChoice = input("Enter 'Y' for Yes or 'N' for No.\n").upper()
if(playerNameChoice == "Y"):
break
#The following randomly selects Card 1 for the computer
randomComputerCard = random.choice(availableCards)
if randomComputerCard in (Queen,King,Jack,Ace):
randomComputerCard = 10
else:
randomComputerCard = randomComputerCard
randomComputerCard2 = random.choice(availableCards)
if randomComputerCard2 in (Queen,King,Jack,Ace):
randomComputerCard2 = 10
else:
randomComputerCard2 = randomComputerCard2
print ("%i"%randomComputerCard)
print ("%i"%randomComputerCard2)
print ("TEST OVER")
elif(playerNameChoice == "N"):
continue
During testing when I enter Y when prompted to enter either Y or N nothing happens, it just continues the loop when it should actually break. However when I enter N it does exactly what it's meant to and continues the loop. Sorry if this is a waste of a question, but I actually have no idea what I've done incorrectly.
Thanks in advance as always! :)
EDIT: The variable availableCards has already been defined.
You need to remove the 'break' at line 7. That's causing your code to exit prematurely.

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