I'm trying to make a countdown timer like little script. I want it to look like this:
0 years left until your event.
0 months left until your event.
10 days left until your event.
234 hours left until your event.
14020 minutes left until your event.
841166 seconds left until your event.
As you can see it's not a "normal" countdown. I want it to be like this, total amount of seconds, total amount of minutes left etc. Now I'm running into trouble trying to make it actually count-down. Just the seconds are working fine, I'm using this piece of code for that:
def secondsLeft(eventDate):
while secondsUntil:
toPrint = "%s seconds left until your event." %(secondsUntil)
print(toPrint, end='\r')
time.sleep(1)
secondsUntil -= 1
However, when trying to do the same for the minutes, replacing with time.sleep(60) it's not printing out the seconds anymore!
I think it has to do with the while loop. However, I don't know what to do about it... Any help in the right direction is appreciated!!
If you wait a minute the whole program will be stopped for a minute. It can't decrease the seconds. What you want to do is, keep waiting only a second per while interation and add this line mins, secs = divmod(secondsUntil, 60). You can print mins for the minutesUntil
Related
What I want to achieve here is that when I press * the program should wait for 17 seconds before doing anything else and if I don't press anything it can continue pressing the ] key every 11 seconds. The problem here is that if I were to press the * while we are in any time.sleep period, the press of the key will not go through.
import pyautogui
import time
import keyboard
while not keyboard.is_pressed('*'):
if keyboard.is_pressed('*'):
time.sleep(17)
else:
time.sleep(11)
pyautogui.press(']')
There are a lot of ways to accomplish this.
One of the simpler (but certainly not best) ways is to sleep in shorter increments (say 0.1 sec) to wake up periodically and poll the keyboard. You would track in a variable the system time at which point you are done "waiting" and break out of your loop at that point.
This works for me
import pyautogui
import time
import keyboard
last_star_press = 0 # initialize variable to keep track of time of last * press
while True:
if keyboard.is_pressed('*'):
last_star_press = time.time() # update time of last * press
time.sleep(17)
else:
if time.time() - last_star_press >= 11:
pyautogui.press(']')
last_star_press = time.time() # update time of last key press
time.sleep(1) # add a small delay to reduce CPU usage
I am at a very beginner level with Python and I have a simple project for myself. My goal is to build a simple timer with only two functions using tkinter and python. The first button starts the countdown timer at 30 seconds. And the second button stops it. However, I would like each additional press of the first button to add an additional 30 seconds to whatever time is currently left on the countdown clock. The first two elements have proven not too difficult using this prior thread, but adding additional time to the active timer is something I cannot reach.
Essentially, the goal is to recreate the functionality of the "+30 seconds" button on a microwave, with an updating display, where the initial press both adds 30 seconds and starts the timer, each subsequent press adds an additional 30 seconds to the countdown timer, and the second button stops the timer.
Here's what I've been using for the basic timer logic.
def countdown(t=30):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
print('Done!')
The problem is a little bit more complex than it appears for the following reasons:
If you are not using any library for parallel events, then, the function countdown() will block the main loop and you will not be able to do anything (including click the button again to add more time) while the countdown is running
If you want to add time with the same button, you have to check if there's already a countdown print on screen, if you don't check it, for each click a new clock will appear.
I suggest to use asyncio lib as follow:
import asyncio
# Create a global variable for the time
secs = 0
#This function adds +30secs
def addTime():
global secs
secs+=30
#This is the func that gather the addTime function and the async clock
async def timerAction():
#This "while" is used to simulate multiple cliks on your button.
# If you implement this as a callback delete the "while"
while True:
j = 0 #Counter if a clock is already running
addTime() #Add time
for task in asyncio.all_tasks(): #This loop checks if there's a countdown already running
if task.get_name()=='countdown':
j+=1
if j == 0: #If no running countdown, j==0, and fires the countdown
taskCountdown = asyncio.create_task(countdown(), name='countdown')
await asyncio.sleep(10) #Wait 10secs between each call to the func (each call simulate a click)
async def countdown():
global secs
while secs>0:
mins, secs = divmod(secs, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
await asyncio.sleep(1)
secs -= 1
print('Done!')
asyncio.run(timerAction())
Output:
On the fisrt call:
00:30
after 10secs:
00:50
after 10secs:
01:10
and so on...
This is my code
It performs keep_click_attendance_link() enter code here function until JustBefore time is reached
and then at EndTime it performs the leave_the_meeting() function
import pyautogui
import time
import pause
import datetime
import schedule
YEAR = 2020
MONTH = 11
DATE = 6
HOUR = 13
MINUTES = 3
SECONDS = 15
now = datetime.datetime.now()
EndTime = now.replace(hour=HOUR, minute=MINUTES, second=SECONDS, microsecond=0)
JustBefore= now.replace(hour=HOUR, minute=MINUTES-1, second=SECONDS, microsecond=0)
def leave_the_meeting():
pyautogui.click(1198, 1072)
time.sleep(3)
pyautogui.click(1443, 998)
time.sleep(1)
pyautogui.click(1398, 933)
def click_attendance_link():
pyautogui.click(1665, 674)
time.sleep(9)
def keep_click_attendance_link():
while datetime.datetime.now() < JustBefore:
click_attendance_link()
# Sleep for 60 secs before trying again
time.sleep(9)
keep_click_attendance_link()
while datetime.datetime.now() < EndTime:
# Sleep for 1 sec intervals:
time.sleep(1)
# eventually Leave the meeting at Endtime
leave_the_meeting()
So what I want is it to stop the function keep_click_attendance_link() when the attendance link is clicked. The teacher sends the link at any random time, so I had to program it to continuously click at that spot until 1 minute before the EndTime which is JustBefore. The meeting is on zoom client not on the web browser.
First of all, don't skip lesson.
Secondly, to do what you intend to do, for educational purpose only, you will need a mechanism to detect whether the button has appeared yet. Since you can't directly communicate with the zoom client, you will need to detect pixel by pixel in the screen and analyze whether the color of that pixel/area is the color for the attendance button.
To do that, you will need to find the color code for your button first. It can be simply done by screen capture and put that in any image processing software, even Paint. After you have your color, you can use Pillow module to analyze that particular spot, more on that here.
After the checking mechanism is done, you can integrate that into your code and stop the function execution once the button has been detected.
def check_attendance_link_presence():
# check it here
pass
def keep_click_attendance_link():
clicked = False
while datetime.datetime.now() < JustBefore and not clicked:
presence = check_attendance_link_presence()
if presence:
click_attendance_link()
clicked = True
# Sleep for 60 secs before trying again
time.sleep(60)
p.s. I intentionally not to include the code for the presence checking here for the sake of encouraging you to spend time learning it while you are "taking a break" from your lessons.
Maybe: Define a variable something like clicked = False, and in the attendance function set it to True. Then modify the While in the other function with an and clicked == False. So your while cycle only loops till the clicked flag is False, but after it clicked the attendance, it'll change to True, and the cycle stops.
I think it would be more elegant with callbacks tough.
I took a computer science course this year (grade 10) and the final project is to make a game. For my game I want to add a hunger element where you start with 0 hunger and every minute you hunger goes up by 1 (in the game you buy food items to make your hunger go back down, but I will add that later). If your hunger reaches all the way to 10 (this would be after 11 minutes). You “die” and lose all your game progress - the program crashes (pygame.quit())
Can anyone help me with this doing this, I’m not really sure as I am extremely new to coding.
Thanks!
Have you tried generating any code for it yet? It is not really fair to ask people to give you code for your assessment without doing some real research and trying to get some code working for yourself first. Maybe update your question with anything you have attempted towards this question, to give a better explanation for what you are really needing help with? If you have not started yet, here is some guidance to get you started:
First of all you will need something that would generate a time counter for you, so you know when a minute passes. Check out: Countdown timer in Pygame for guidance on generating a timer and how to get how many seconds have passed. There is also a link in that question to the pygame timer documentation that would be very helpful.
Then, you just need to set up a "hunger" variable that gets added to every time 60 seconds have been reached. And once it hits 10, then have the game over method initiated.
Check out
http://www.pygame.org/docs/ref/time.html#pygame.time.get_ticks
Heres some code to get you going..
import pygame
run_app = True
time_passed = 0
COUNTER = 60 # Set to 60 seconds / 1 minute.
pygame.init()
start_ticks=pygame.time.get_ticks()
# Begin game loop.
while run_app:
# Convert to seconds.
time = (pygame.time.get_ticks()) / 1000
# True every 60 seconds / 1 minute.
if time > (time_passed + COUNTER):
time_passed = time
print("Do something here regarding hunger, Increase by 1")
I'm creating a game and at the "start" screen I want it to pop up a picture after 45 seconds of not starting the game saying "Are you not going to play?"
However, I am completely lost at what to do, so if anyone have any clue on how to help that would be really appreciated.
You probably have a timer for your game, like this:
pygame.time.Clock.tick(fps)
Each time your main loop runs, it ticks your fps, so your game could run smoothly.
Now, just add a variable, called, say, tick_counter
Now, in your code, do something like this:
fps = 25
tick_counter = 0
while RUNNING:
#Do stuff, check for if close window, etc
pygame.time.Clock.tick(fps)
tick_counter += 1
if tick_counter >= 1125: #45 seconds if you are doing 25 fps. If your fps is different, just calculate it: 45 seconds = 45*fps
#Pop up the picture!
You can set a timer and an event on the event queue. This answer shows how to do that. How can I detect if the user has double-clicked in pygame?