So I have a code I'm working on to automatically play my alarms at the times I specify. It also is playing some city sounds to help me sleep and while playing those sounds I can't get the while loop to end to have the alarm sound to play.
I tried to bring the while loop into the alarm function I've created but that didn't work but I'm fairly certain it has something to do with my while loops. But I'm thinking a fresh pair of eyes might do this code some good.
'''
Title: This is an alarm that perfectly lines up with my sleep schedule
Author: Riley Carpenter
'''
from pygame import mixer
import time
import os
import sys
import random
snoozeorstop = " "
Currenttime = time.ctime()
Hours1 = int(Currenttime[11:13])
Minutes1 = int(Currenttime[14:16])
Seconds = int(Currenttime[17:19])
optionalsongs = ["Pink Floyd Time.wav","Alarm2.wav","Alarm3.wav","Alarm4.wav","Alarm5.wav","Alarm6.wav","Alarm7.wav","Alarm8.wav","Alarm9.wav","Alarm10.wav","Alarm11.wav"]
phrases = ["Wake up Riley!!!!","It's time to wake up it's time to wake up","HEEEEYYY WAKE UP","RILEY RILEY RILEY WAKE UP","1 2 3 4 5 6 7 8 9 it is time to wake up","Riley more alarms are to come UNLESS you get up","OH WHEN SHALL I SEE JESUS you wanna not hear this again? Wake up","I'm so tired of telling you to wake up just wake up","A friend of the devil is somehow who doesn't wake up","Babe babe bae wake up"]
def playsound(soundfile):
mixer.init()
mixer.music.load(soundfile)
mixer.music.play(-1)
def stopsound():
mixer.music.stop()
def alarm(hour,minute):
print("")
print("")
print(random.choice(phrases))
if Hours1 == hour and Minutes1 == minute:
stopsound()
playsound(random.choice(optionalsongs))
print("")
snoozeorstop = input("Do you want to stop the song? ")
if snoozeorstop == "stop":
stopsound()
citysounds = input("Do you want to play the soothing sounds of the city? ")
if citysounds == "y" or citysounds == "Yes" or citysounds == "Y" or citysounds == "yes":
playsound("Citys Night ambience sounds.wav")
else:
playsound("Beginningsound.wav")
amount = 0
print("This is how many second has passed since this alarm was turned on")
while Hours1 != 5 and Minutes1 != 0:
Currenttime = time.ctime()
print(amount)
Hours1 = int(Currenttime[11:13])
Minutes1 = int(Currenttime[14:16])
Seconds = int(Currenttime[17:19])
amount += 1
time.sleep(1)
alarm(5,00)
alarm(5,5)
alarm(5,10)
alarm(5,15)
alarm(5,20)
alarm(5,25)
alarm(5,30)
alarm(5,35)
alarm(5,40)
alarm(5,45)
alarm(5,50)
alarm(5,55)
alarm(6,00)
alarm(6,5)
alarm(6,10)
alarm(6,15)
alarm(6,20)
alarm(6,25)
Since the while loop is central to your program, why not write that piece of code first. When that works as intended you can add songlists etc.
As for checking for the time when the alarm should go off you might want to check out the datetime module which makes time calculations much easier. For example:
import datetime, time
start = datetime.datetime.now()
alarm = start + datetime.timedelta(seconds=5) # Set alarm time 5 seconds from now
while True:
now = datetime.datetime.now() # When is this?
print(now.strftime("%H:%M:%S")) # Print human readable time
if now > alarm: # Have I passed the alarm time?
print('Alarm') # Sound the alarm
break # Leave this loop
time.sleep(1)
Related
Good evening,
I want keyboard input with visible timer (time to respond)
My code
import time
import sys
def initial_startup(t):
print('Do you want to continue?')
global input
input = input("Answer yes or no only:" + " ").lower()
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
if input == "yes" or input == "yup":
print("\n\nThanks script is now starting\n\n")
else:
pass
if input == "no" or input == "nope":
print("\nOk as you wish, I'm stopping...\n")
sys.exit(1)
if timer == "00:01":
print("Timeout! try again")
sys.exit(1)
t = 4
initial_startup(int(t))
I'm trying to get keyboard input with timeout and also want to show time below answer yes or no:
Prints timer after input ..
Want this output.
Output:
Do you want to continue?
Answer yes or no:
You have {timer} time left...
If input then continue else sys.exit which is already in code.
Thank you so much for helping to improve this newbie!
To do this you need to move with cursor in the terminal depending on the operating system you are using, it is very tiring and it is not very solid to use the terminal in that way (a static stdout would be easier and safer), what I would do it is an output of this kind obviously you have to use a multithread programming to be able to use the file descriptor simultaneously
import time
import sys
import threading
import time
import sys
def get_input(t):
global stop_threads
while True:
input_cmd = input().lower()
if input_cmd == "yes" or input_cmd == "yup":
print("\n\nThanks script is now starting\n\n")
break
elif input_cmd == "no" or input_cmd == "nope":
print("\nOk as you wish, I'm stopping...\n")
break
stop_threads = True
def initial_startup(t):
print('Do you want to continue?')
t1 = threading.Thread(target=get_input, args=(t,), daemon=True)
t1.start()
while t:
global stop_timeout
global stop_threads
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
prompt = "You have %s time left... Answer yes or no only: " % timer
print(prompt)
sys.stdout.write("\x1b[1A") # cursor up one line
sys.stdout.write("\x1b[2K") # delete the last line
if stop_threads:
sys.exit(1)
time.sleep(1)
t -= 1
if timer == "00:01":
sys.stdout.write("\x1b[2K") # delete the last line
print("Timeout! try again")
sys.exit(1)
stop_threads = False
stop_timeout = False
t = 4
initial_startup(int(t))
Output
Do you want to continue?
You have 00:02 time left... Answer yes or no only:
Ok as you wish, I'm stopping...
Do you want to continue?
You have 00:02 time left... Answer yes or no only:
Timeout! try again
Do you want to continue?
You have 00:05 time left... Answer yes or no only:
Thanks script is now starting
while 1:
wat=water()
if wat==10:
print("water condition")
mixer.music.load("water.mp3")
mixer.music.play()
first=input("Drank?Y/N")
if first.lower()=="y":
with open("HealthLog.txt","a") as water1:
Content=f"Drank water at [{getdate()}] \n"
water1.write(Content)
else:
pass
Is there any way to wait for a couple of minutes and if no input is provided, then take the value "n" as input for the first variable?
Guess by default it will wait indefinitely. I tried using a timer function, but it cannot record any input.
What I am trying to do is to track my activities, so if I drink water I say y--> this records my activity and writes it to a file.
All help will be greatly appreciated
Here is how you can use a combination of pyautogui.typewrite, threading.Thread and time.sleep:
from pyautogui import typewrite
from threading import Thread
from time import sleep
a = ''
def t():
sleep(5)
if not a: # If by 5 seconds a still equals to '', as in, the user haven't overwritten the original yet
typewrite('n')
typewrite(['enter'])
T = Thread(target=t)
T.start()
a = input()
b = input() # Test it on b, nothing will happen
Here is the code implemented into your code:
from pyautogui import typewrite
from threading import Thread
from time import sleep
while 1:
wat = water()
if wat == 10:
print("water condition")
mixer.music.load("water.mp3")
mixer.music.play()
first = 'waiting...'
def t():
sleep(5)
if first == 'waiting...':
typewrite('n')
typewrite(['enter'])
T = Thread(target=t)
T.start()
first = input("Drank?Y/N")
if first.lower() == "y":
with open("HealthLog.txt","a") as water1:
Content=f"Drank water at [{getdate()}] \n"
water1.write(Content)
else:
pass
import time
print("The timer on this project Will start")
#Ask To Begin
start = input('Would you like to begin learning now? (yes / no):')
if start == 'yes':
timeloop = True
#variable to keep the time
Sec = 0
Min = 0
#Begin process
timeloop = start
while timeloop:
Sec +=1
print(str(Min) + " Mins " + str(Sec) + " Sec ")
time.sleep(1)
if Sec == 60:
Sec = 0
Min +=1
print(str(Min) + " Minute ")
This is my timer program so far but I am not sure How I can get it to stop once it starts in the command prompt?. I want to be able to press X and have the code pause. Or perhaps press Y and then it resumes, and Z just closes the program all together, but I have no idea as to how.
time.sleep actually stop the execution of the current process the code is running on. If you want to keep time and still make the process responsive, you may want to use a thread to keep time and install the keyboard package to use keyboard.is_pressed()!
This article is really good:
https://realpython.com/intro-to-python-threading/#what-is-a-thread
I have just gotten into python and am trying to create a quiz game. I would like to add a countdown timer of 2 minutes to my quiz so when the timer reaches zero the questions stop and says you are out of time. I also tried to do this with a stopwatch but couldn't figure out how to terminate play so if you know how to do that it would be just as good.
Note: I am NOT using pygame. Many other users have asked in previous threads.
This is the code I gathered from the other documents but it doesn't stop once it reaches 2 mins or 0 mins.
def countdown():
t = 60
while t:
mins, secs = divmod(t, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
t -= 1
print("You're out of time!\n")
sys.exit ("goodbye")
def main_game():
count_thread = threading.Thread(None, countdown)
question_4 = ("question 1?")
option_4 = (" a. 1 \n b. 5 \n c. 3 \n d. 7")
print(question_4)
print(option_4)
answer_4 = input (">")
if answer_4.lower()== "b":
score = score + 100
else:
print("Incorrect")
import time
start1 = time.time()
if start1 >= 120:
import sys
sys.exit
question_a = ("question?")
option_a = (" a. 7 \n b. 8 \n c. 2 \n d. 1")
print(question_a)
print(option_a)
answer_a = input (">")
if answer_a.lower()== "b":
score = score + 100
else:
print("Incorrect")
###rest of questions
end1 = time.time()
Both codes are two different versions I have tried. Both codes don't work. The bottom code times the play but it doesn't stop at the 2 minute mark.
Any help, advice, or feedback would be appreciated!
Since you use Pygame.
The simplest code you may have should (by good codding standards) include pygame.quit(). Like this:
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
while True: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Followed by Python sys.exit function.
Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.
You can make the quiz game w/o explicit use of Python threads, but If you plan to use Python threads you can start by checking the quick and dirty example from here.
Hope this helps. You already can find quizzes in pygame online and possible modify that.
I would like to have my program reference the current time in Python.
But my program keeps printing and referencing a timestamp. I am using Python3.5.3.
import time
timenow = time.strftime("%X")
awake = "06:00:00" # turn on the lights at 6am
sleep = "22:00:00" # turn off the lights at 10pm
while True:
print (timenow) # print the current time
if awake <= timenow:
print ("Lights On")
elif timenow >= sleep:
print ("Lights Off")
My current output is...
21:55:46
Lights On
21:55:46
Lights On
21:55:46
Lights On
This might work as well.
If you are referencing time as date part that can be represented an int. I guess its better to compare numbers in this case rather then strings (as in your example).
import datetime
on = 6
off = 22
while True:
ctime = datetime.datetime.now()
status = 'Lights On' if on < ctime.hour < off else 'Lights Off'
print('{}: {}'.format(ctime.strftime('%X'), status))
I think you just need to move 1 line into the while loop:
import time
awake = "06:00:00" # turn on the lights at 6am
sleep = "22:00:00" # turn off the lights at 10pm
while True:
timenow = time.strftime("%X") #moved this line into the while loop
print (timenow) # print the current time
if awake <= timenow:
print ("Lights On")
elif timenow >= sleep:
print ("Lights Off")
The output should now look like:
Lights On
08:50:22
Lights On
08:50:23
Lights On
08:50:24
In the question, timenow gets set and is never updated. So move that into the while loop flow so it gets created each time. Just as good programing practice you may also want to toss a pause in there so it's just not hammering the CPU in the loop. You could put this at the end of the while loop and it will wait 1 second before looping again:
....
elif timenow >= sleep:
print ("Lights Off")
time.sleep(1)