This question already has answers here:
How to set time limit on raw_input
(7 answers)
Closed 6 years ago.
I have created a mathematical quiz game that prints and equation to the user like, 5 + 3 = ?, and waits for the result. If the answer is right the user wins if not the user loses. I want to extend the game and add a feature that places a time limit of 3 seconds for the user to answer, if he don't the he loses.
At the beggining I tried using the time module and the time.sleep() function but this also delayed the whole program's logic.
Here is an idea with pseudo code:
if (answer = wrong || time = 0)
lost...
if you want to check if the user took to long when he answered you can use the time module to calculate the diffrence:
start_time = time.time()
show_question()
answer = get_answer()
end_time = time.time()
if (answer = wrong || end_time - start_time > 3)
lose()
if you want the user to loose when 3 seconds as passed (without waiting for them to input a answer) you will have to use threading, like this:
timer = threading.Timer(3, lose)
show_question()
answer = get_answer()
timer.cancel()
if (answer = wrong)
lose()
Related
This question already has an answer here:
perf_counter is returning wrong time
(1 answer)
Closed 5 months ago.
I'm trying to learn multi_threading in python but when I try to print time.perf_counter() in order to see how much time the Main Threading takes to run the program which is in charge the output is a huge number (614691.9609577), but it should not even be 2 seconds. Can you explain the reason of this problem?
Thanks
import threading
import time
def have_breakfast():
time.sleep(3)
print("You had breakfast")
def make_bed():
time.sleep(4)
print("You made your bed")
def study():
time.sleep(5)
print("You finish studying")
x = threading.Thread(target = have_breakfast, args = ())
x.start()
y = threading.Thread(target = make_bed, args = ())
y.start()
z = threading.Thread(target = study, args = ())
z.start()
x.join()
print(threading.active_count())
print(threading.enumerate())
print(time.perf_counter())
From here:
time.perf_counter():
Return the value (in fractional seconds) of a performance counter,
i.e. a clock with the highest available resolution to measure a short
duration. It does include time elapsed during sleep and is
system-wide. The reference point of the returned value is undefined,
so that only the difference between the results of two calls is valid.
Use perf_counter_ns() to avoid the precision loss caused by the float
type.
New in version 3.3.
Changed in version 3.10: On Windows, the function is now system-wide.
In your case if you want to measure time you need to subtract two time intervals. E.g.:
t1_start = time.perf_counter()
# your code...
t2_stop = time.perf_counter()
print("Elapsed time: ", t2_stop - t1_start)
This question already has answers here:
How to create a python loop that allows other code to run as well
(3 answers)
How do I get input at the same time while constantly increasing a value in python?
(1 answer)
Closed 1 year ago.
I'm trying to make a program that makes you lose "energy" for a game.
I made it so when you press enter you gain "energy":
if question == '':
print("press enter to gain energy")
while True:
energyup = input()
if energyup == "":
energy += energygain
print(energy)
I also want to make it so you lose energy every 0.5 seconds. I don't know how to do this.
I tried adding:
while True:
energy -= energyloss
print(energy)
time.sleep(1)
to the bottom of the program, but that makes you lose energy WAY too fast and I don't know if there is a way to make 1 line of code sleep while everything else continues (I'm using time.sleep which affects the whole program) and on top of that it makes the energy gaining system just not work.
Sorry if this is a dumb question I just started learning programing and this is my first question on this site.
Instead of time.sleep, just check if it has been 0.5 seconds past the last time energy was lost:
prev_time = time.time()
while True:
# rest of the game loop
curr_time = time.time()
if curr_time - prev_time > 0.5:
energy -= energyloss
prev_time = curr_time
This lets the rest of the game loop code to run concurrently.
You need to use threads. Thread A is responsible for consumption, and thread B listens for input
energy = 0
energyloss = 1
energygain = 1
lock = threading.Lock()
def consumption():
global energy
while 1:
with lock:
energy -= energyloss
time.sleep(0.5)
print(energy)
threading.Thread(target=consumption).start()
Use threading.Lock to ensure thread safety
You also need to call with lock when increasing energy
I see solution with threading which might be helpful but from your problem statement, I believe you only need to have a function that will provide the diff between the total energy accumulated and the one lost with time.
To do so, you may start a timer at the beginning and create a function that will use the current time minus the execution time to calculate the energy lost each time.
The below might be enough for you case:
import time
energy_gain_constant = 5
energy_loss_constant = -2
total_energy_gain = 0
start_time = time.time()
def print_total_energy():
print(total_energy_gain + int((time.time() - start_time) / 0.5) * energy_loss_constant)
print("press enter to gain energy")
while True:
energyup = input()
if energyup == "":
total_energy_gain += energy_gain_constant
print_total_energy()
Adding debug logs into the method that prints how it will behave:
def print_total_energy():
total_energy_lost = int((time.time() - start_time) / 0.5) * energy_loss_constant
print(f'Total execution time: {time.time() - start_time}')
print(f'Total energy lost: {total_energy_lost}')
print(f'Total energy gained: {total_energy_gain}')
print(f'Total Energy: {total_energy_gain + total_energy_lost}')
Output:
Total execution time: 12.982820272445679
Total energy lost: -50
Total energy gained: 65
Total Energy: 15
This question already has answers here:
How to repeatedly execute a function every x seconds?
(22 answers)
Closed 4 years ago.
I want to write a Python program that will sample a sensor at a fixed sampling rate. Is there any elegant way of doing this?
Currently, I am using the time.time and time.sleep commands to enforce this manually. While this does work, it is creating a small drift. Also, it seems to be a not very nice way of doing so, and I hope there is a more pythonic way of doing this:
def mock_signal(x):
# Just a random number as the sensor signal
return np.random.random()*x
def sampling(fs=1, x=1):
T = 1/fs # sampling period
t_ground = time.time()
while True:
t_start = time.time()
y = mock_signal(x)
print('%.5f | Sensor Value %.2f' % (t_start - t_ground, y))
t_duration = time.time()
# Sleeping for the remaining period
time.sleep(T - (t_duration-t_start))
Ideally, I would like to have a function or class that would sample the sensor (basically call the 'mock_signal' function) and append the new sample to a list or array. The latest entry in said array should than be accessible by a call similar to the multiprocessings Connection.recv()
Thanks in advance :)
May you can try something like that.
import threading
t_ground = time.time()
def sampling():
t_ground = time.time()
threading.Timer(T, sampling).start()
t_start = time.time()
y = mock_signal(1)
print('%.5f | Sensor Value %.2f' % (t_start - t_ground, y))
It's just an example. You need to change it to your need.
This question already has answers here:
How do I get the current time?
(54 answers)
Closed 6 years ago.
I would like to know a way to time between two points in a program. In my situation I will ask the user 10 questions and after display the time it took for them to answer the question (example code below). How would i do this through something like import time ?
Example code:
timer.start
question1 = input("What is your favorite game ?")
timer.end
print(timer.time)
^
The timer.x thing is going to be replaced with your suggestions.
import time
s=time.time()
question1 = input("What is your favorite game ?")
e=time.time()
print(e-s)
time.time() Returns the time in seconds since the epoch as a floating point number.
How about this?
from datetime import datetime
start = datetime.now()
question1 = input("What is your favorite game ?")
end = datetime.now()
print(str(end - start))
This question already has answers here:
How to set time limit on raw_input
(7 answers)
Closed 9 years ago.
I want to have a time limit in order to enter the input in the following code. In other words, there should be a timer tracking the time and if it exceeds the limit, the code should print out a message like "Game over" automatically without hitting any key. it is a sort of pop-up.
def human(player, panel):
print print_panel(panel)
print 'Your Turn! , Hint: "23" means go to row No.2 column No.3/nYou got 1 min to move.'
start_time = time.time()
end_time = start_time + 60
while True :
move = raw_input('> ')
if move and check(int(move), player, panel):
return int(move)
else:
if (time.time() < end_time):
print 'Wrong move >> please try again.'
else:
print "Game over"
return panel, score(BLACK, panel)
break
the other question is almost the same but the answer is not what I am looking for. I want the code to return a message when the time is over without hitting "ENTER".
The simplest way is to use the curses module. You'll want to set nodelay(1), and poll for input. http://docs.python.org/2/howto/curses.html#user-input