How to make countdown timer in Python without input? - python

Iv'e been trying to create a countdown timer for a game in python however i'm not sure how to code it without including the input question for the time at the beginning of the code.
So far the code looks like this
import time
import datetime
# Create class that acts as a countdown
def countdown(s):
# Calculate the total number of seconds
total_seconds = s
# While loop that checks if total_seconds reaches zero
# If not zero, decrement total time by one second
while total_seconds > 0:
# Timer represents time left on countdown
timer = datetime.timedelta(seconds = total_seconds)
# Prints the time left on the timer
print(timer, end="\r")
# Delays the program one second
time.sleep(1)
# Reduces total time by one second
total_seconds -= 1
print("You have been caught.")
# Inputs for hours, minutes, seconds on timer
s = input("Enter the time in seconds: ")
countdown(int(s))
exit()
I want to make the code so it has an automatic countdown for 10 seconds as soon as the user presses enter. Any ideas?

If I understand your question correctly you just want the user to press the enter key instead of actually inputing a number? then you can just hard code the time value and call the function with that value, while using an empty input call to wait for a keypress.
input("Press enter to continue...")
countdown(10)
exit()
here you're not storing the value from input anywhere and just using the input function to block until the user presses enter.

You could do it this way:
import time
def countdown(time_sec):
while time_sec:
minutes, secs = divmod(time_sec, 60)
time_format = f'{minutes}:{secs}'
print(time_format, end='\r')
time.sleep(1)
time_sec -= 1
print("stop")
countdown(5)

Related

script to hold down the space bar and press keys every 10 seconds, with one key to close the loop

i want create a script can hold down the space bar and press a key every 10 seconds, with one another key to close the loop but I made a mistake somewhere and I don't know how to fix it.
import keyboard
import time
time.sleep(8)
timer = 0
while True:
try:
while timer < 10:
time.sleep(0.1)
timer += 0.1
keyboard.press('space')
keyboard.press('z')
timer = 0
if keyboard.is_pressed('q'):
break
except:
break
I dont understand why if I press q, it won't stop the loop.

How can I write a loop to make the timer run every two seconds

I have a question on how I am able to set the timer so that every time it exits the loop it sets the time back to 2 seconds. The problem is that the first time the sound works after 2 seconds, the next times it is executed immediately. Thank you very much in advance for any advice.
This is my code:
time = 2
while time > 0:
timer = datetime.timedelta(seconds=time)
time -= 1
duration = 1000
freq = 440
winsound.Beep(freq, duration)
I am not sure if you meant that, but for me it seems like you just want to wait 2 seconds before executing the next steps. You can do that like so:
import time
while True:
time.sleep(2) # waits 2 seconds
winsound.Beep(440, 1000)
Anyways I don't recommend you to use a plain infinite loop, without a break statement. Therefore I recommend you to add one, like down below.
import time
while True:
time.sleep(2) # waits 2 seconds
winsound.Beep(440, 1000)
if True: # break on a specific statment
break
Edit: As CrazyChucky mentioned in the comments, this approach should work fine in most of the cases, but it can end up being more than two seconds sometimes. Therefore you should work with timedeltas or take a look at scheduler.
To be more accurate as possible use:
import time
timer = 0
step = 2
t0 = time.time()
while True:
timer = time.time() - t0
wait = step - timer
time.sleep(wait)
print(time.time())
winsound.Beep(freq, duration)
t0 = time.time()
This script take in count the execution time of script lines for your computer.
You just have to reinitialize the time at the end of the loop
time = 2
while True:
timer = datetime.timedelta(seconds=time)
time -= 1
duration = 1000
freq = 440
if time == 0:
time = 2
break
winsound.Beep(freq, duration)

Problems with python alarm at specified hours

I'm trying to make a "alarm" for my classes and it does that when a certain hour comes it does something (in this case it just prints, and i will change that when the code works) and it repeats until next alarm.The problem here is that when i run the code 1 min before it prints it's time , and then it reaches the alarm time and it still prints the same and not not yet.
I want the code to keep running after the if statements. Here's the code:
from datetime import datetime
import time
now = datetime.now()
current_time = now.strftime("%H:%M")
today = now.strftime("%A")
cn = "22:14"
ing ="21:23"
day = {0:"Monday", 1:"Tuesday", 2:"Wednesday"
, 3:"Thursday", 4:"Friday", 5:"Saturday", 6:"Sunday"}
def mday():
if (today == day[0]) and (current_time == cn):
print("its time")
time.sleep(1)
mday()
else:
print("not yet")
time.sleep(1)
mday()
mday()
The main problem with your code (why it does not work at all), is that you do not update the values of the today and current_time variables. That you sleep for one second in each call to mday() does not affect these variables. You need to update them right at the entry to mday.
The second problem is that you have infinite recursion here. Infinite loops run forever, which is what you want, I guess. Infinite recursion, on the other hand, simply uses up the stack, and crashes you application. You would need to convert the recursive function mday to one with an infinite loop. To do that, place all the if statement from inside mday inside a forever loop: (while True:), and
also remove the two recursive calls from the end of the branches. You can also take the sleep calls out of the if - remove one of them, and place the other after the the content of the else block:
from datetime import datetime
import time
cn = "22:14"
ing ="21:23"
day = {
0:"Monday",
1:"Tuesday",
2:"Wednesday",
3:"Thursday",
4:"Friday",
5:"Saturday",
6:"Sunday"
}
def mday():
while True:
# Update current time values
now = datetime.now()
current_time = now.strftime("%H:%M")
today = now.strftime("%A")
# Print alarm/no-alarm message
if (today == day[0]) and (current_time == cn):
print("its time")
else:
print("not yet")
time.sleep(1)
mday()
There are many ways this code can be optimized, but the above will produce roughly the result you want.

How do you use KeyboardInterrupt without a try statement

I am trying to make a basic wage timer for my brother who just got a job... What I wanted to have was a while loop running the code waiting for someone to press enter (or some other key) ends the loop and give the current wage. I was hoping to KeyboardInterrupt but if there is an easier way to do it I would love to hear about it. How could I do this?
a keyboard interrupt is generated only when someone hits ctrl-C or similar.
it sounds like your plan was to have code something like:
from time import sleep
wage = 0
try:
while True:
wage = wage + hourly_rate
sleep(60 * 60) # an hour in seconds
except KeyboardInterrupt:
print('you earned', wage)
and then have someone hit ctrl-C? which would work with a try/except. but if you want someone just to hit the return key then instead of adding things up, do some maths:
from time import time
start = time() # time in seconds from some arbitrary date in 1970 (it's a standard)
input('hit return to get your wage!')
end = time()
elapsed = end - start # time that has passed in seconds between start and end
wage = hourly_rate * elapsed / (60 * 60) # convert from hourly
print('you earned', wage)
the first version is a bit optimistic as it adds each hour at the start. the second is more accurate.
ps congrats to your brother!

What's the proper way to write a game loop in Python?

I'm trying to write a python game loop that hopefully takes into account FPS. What is the correct way to call the loop? Some of the possibilities I've considered are below. I'm trying not to use a library like pygame.
1.
while True:
mainLoop()
2.
def mainLoop():
# run some game code
time.sleep(Interval)
mainLoop()
3.
def mainLoop():
# run some game code
threading.timer(Interval, mainLoop).start()
4.
Use sched.scheduler?
If I understood correctly you want to base your game logic on a time delta.
Try getting a time delta between every frame and then have your objects move with respect to that time delta.
import time
while True:
# dt is the time delta in seconds (float).
currentTime = time.time()
dt = currentTime - lastFrameTime
lastFrameTime = currentTime
game_logic(dt)
def game_logic(dt):
# Where speed might be a vector. E.g speed.x = 1 means
# you will move by 1 unit per second on x's direction.
plane.position += speed * dt;
If you also want to limit your frames per second, an easy way would be sleeping the appropriate amount of time after every update.
FPS = 60
while True:
sleepTime = 1./FPS - (currentTime - lastFrameTime)
if sleepTime > 0:
time.sleep(sleepTime)
Be aware thought that this will only work if your hardware is more than fast enough for your game. For more information about game loops check this.
PS) Sorry for the Javaish variable names... Just took a break from some Java coding.

Categories

Resources