I'm a python starter and need some help on a quiz like game.
This is my code:
import time
from threading import Timer
import random as rnd
q = ["q1", "q2", "q3"]
a = ["a1 b1 c1", "a2 b2 c2", "a3 b3 c3"]
ca = ["b", "c", "b"]
points = 0
rand_q = rnd.randint(0, len(q) - 1) # Choosing random question
print(q[rand_q] + "\n" + a[rand_q] + "\n") # Asking question and showing answers
time.sleep(0.5) # Little pause between prompts
t = Timer(10, print, ['Time is up!']) # Setting up timer
t.start() # Start timer
start = time.time() # Start of time check
answer = input("You have 10 seconds to choose the correct answer.\n") # User input
if answer is ca[rand_q]: # Check if answer is correct
print("Correct answer!")
points = (points + round(10 - time.time() + start, 1)) * 10 # Calculate points
else:
print("Wrong answer!")
t.cancel() # Stop timer
print("Points:", points)
input("Press ENTER to quit")
del q[rand_q] # Removing the question
del a[rand_q] # Removing the answer
del ca[rand_q] # Removing the correct answer
When I run this I can answer questions and get points, but whenver i wait out the timer I get a prompt saying the time is up, but I can still fill in and answer the question.
I want the input to stop working after the 10 seconds, but I can't seem to make this work. Is there any way I can make the timer timeout all previous inputs on top of the "Time is up" prompt.
I've seen more posts like this but they seem outdated and I didn't get them to work.
EDIT: the sleep command doesn't work. It prints a line saying it's too late but you can still enter an answer after. Same for the threading timer. I want to terminate the input command after 10 seconds, but there seems to be no solution for windows.
The problem is that python's input function is blocking, which means the next line of code will not be executed until the user enters some data. A non blocking input is something that a lot of people have been asking for, but the best solution would be for you to create a separate thread and ask the question on there. This question has sort of been answered in this post
This solution will work except the user will still have to press enter at some point to progress:
import time
import threading
fail = False
def time_expired():
print("Too slow!")
fail = True
time = threading.Timer(10, time_expired)
time.start()
prompt = input("You have 10 seconds to choose the correct answer.\n")
if prompt != None and not fail:
print("You answered the question in time!")
time.cancel()
You can do what you intend to do, but it gets very complicated.
Related
This question already has answers here:
How to repeatedly execute a function every x seconds?
(22 answers)
Closed 5 days ago.
I'm very new to python, and I'm trying to make a sort of idle game. I'm having a little bit of trouble optimizing a function I wrote that flashes "ON" and then "OFF" every time a second passes.
While it works fine, it checks to see if a second has passed so many times that it peaks my CPU. The code is below:
import time
def timer():
oldtime = int(time.time())
#grabs the time on initiation
while True:
if oldtime < int(time.time()):
return 'ON'
#flashes on
return 'OFF'
#makes everything that checks if it's on only proc once
oldtime += int(time.time()) - oldtime
#makes oldtime advance one second ahead of time.time(),
#even if more than one second passes at a time
timer()
while timer() == "ON":
print('lorem ipsum')
#output: lorem ipsum every second and a peaking CPU
How would one go about optimizing something like this?
Here I have written a while loop that calls a function that will check the previous state of a variable and depending on whether it was ON or OFF it will sleep for 1 second and change to the other state.
import time
def repeat():
isOn = True
if(isOn):
time.sleep(1)
isOn = False
return 'OFF'
if(isOn != True):
time.sleep(1)
isOn = True
return 'ON'
while True:
#You could always take the return value of repeat() to do something else
#in your code
repeat()
I'm not sure if this is actually what you want as I feel like you are likely looking to do "something else" in the pause.
However, looking at your code, I think this will give you the result you are currently working towards. The key to not using up resources is to sleep()
import time
def timer():
time.sleep(1)
return ["On ", "Off"][int(time.time() % 2)]
while True:
print(timer(), end="\r", flush=True)
I am creating a sort of a game where the player has to guess a word within a given time limit everything is working accept i dont know how do i run a timer and take input at the same time that too in a loop.
I tried some code but it took input then ran the timer and asked input again so one happened after the other and not simultaneously
How do i fix it
Here is what i tried
import time
def countdown(seconds):
while seconds > 0:
seconds -= 1
time.sleep(1)
seconds = 6
while seconds > 0:
input = ("guess word : ")
countdown(6)
^^ that is only a fraction of my code
Full code here - https://sourceb.in/QYk1D9O2ZT
so I just started learning python like today in the morning, and I decided to make a timer, and below is my code
while True:
import time
#=========================================================================================
true=0
while (true==0):
a=int(input("how many minutes? "))
if a>59 or a<0:
print("please type a number between 0 and 60")
true=0
else:
true=1
#==========================================================================================
while (true==1):
b=int(input("how many seconds? "))
if b>59 or b<0:
print("please type a number between 0 and 60")
true=1
else:
true=2
#====================displaying the minutes and seconds====================================================================
while (true==2):
timen = 60*a + b
while timen > 0:
sec=int(timen%60)
min=timen-timen%60
finmin=int(min/60)
print(str(finmin) + ':'+str(sec))
time.sleep(1)
timen = timen - 1
true=3
#====================the looping mechanism====================================================================
while (true==3):
c=input("time's up, press \"a\" start a new timer, press anything other key to exit this program.")
if c!="a":
break
that was my code, and I don't know which part of it doesn't work, because the output just stops at the photo. the program stops here, I am new to python and it is probably some stupid mistake that noobs make, but is anybody available to offer some help please?:
Welcome to the timer.
how many minutes? 5
how many seconds? 9
my error message
When I show the letter "A" I want a countdown to start from 4. While the countdown is running I want to be able to create a new letter. When I type a new letter, the first countdown should be aborted and the countdown of the new letter should start from 4. How can I do this?
import time
import copy
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
print('FINISH!!')
sign = input ("Enter text: ")
copySign = copy.deepcopy(sign)
if sign == copySign:
countdown(int(4))
The problem here is interesting and tricky
What I can think of is that you can use threading library to run two separate functions as threads which run simultaneously
In this way you'll not only be able to run a countdown, but also check if user is typing a new letter or not.
I have taken an excerpt from my code where the problem still happens. I believe this is because of my slow_type function but while the dialogue is being "slow typed" my input will take any values typed during the "slow_type" even before the input shows up. I want the input to only be able to be typed in once the slow_type function is finished. How would I do this?
import time
import sys
def slow_type(line, speed):#You input the dialogue and speed(smaller = faster)
for l in line:
sys.stdout.write(l)
sys.stdout.flush()
time.sleep(speed)
time.sleep(.5)
NL1 = "Huh, I see you finally came. "
NL2 = "You know I sent you that message a long time ago.\n"
NL3 = "But I guess you are here now, and that's what matters. "
NL4 = "So...\n"
NL5 = "\n\t\t\t\tAre you ready?\n\n"
slow_type(NL1, .05)
slow_type(NL2, .05)
slow_type(NL3, .05)
slow_type(NL4, .2)
slow_type(NL5, .05)
print("\t\t1:Yes, I am. 2:Who are you? 3:No, I am leaving.\n")
first_choice = input("\t\t\t\t ").lower()
I am using Windows 10 cmd.