Soo i am a pupil, and i am quite new to coding. I want to make an app that starts a timer when a game starts (specifically the game Valorant), which i get by searching if the process of the game is running. Then i get notifications by the app every 30 minutes. Finally, when i close the game, the app is supposed to pause the timer and tell me how long i was playing. When i close the game, though, the timer does not stop, and i have discovered that the app never understands that the process has stopped running, even though i use a while loop. This is the code: Thank u in advance!
from win10toast import ToastNotifier
import psutil
import time
import schedule
def show_name():
game = "VALORANT-Win64-Shipping.exe" in (i.name() for i in psutil.process_iter())
if game == True:
def timer():
game = "VALORANT-Win64-Shipping.exe" in (i.name() for i in psutil.process_iter())
m = 0
s = 0
while game == True:
time.sleep(1)
s += 1
print(m , s)
if s == 59:
m +=1
s = 0
if m == 30:
toast = ToastNotifier()
toast.show_toast("Hello!", "You have been playing for 30 minutes", duration=20)
elif m == 60:
toast = ToastNotifier()
toast.show_toast("Hello!", "You have been playing for an hour", duration=20)
elif m == 90:
toast = ToastNotifier()
toast.show_toast("Hello!", "You have been playing for 1 hour and 30 minutes", duration=20)
elif m == 120:
toast = ToastNotifier()
toast.show_toast("Hello!", "You have been playing for 2 hours", duration=20)
else:
toast = ToastNotifier()
toast.show_toast("Hello!", "You have played for " + str(m) + " minutes and " + str(s) + " seconds!", duration=20)
schedule.every(4).seconds.do(timer)
schedule.every(4).seconds.do(show_name)
while 1:
schedule.run_pending()
time.sleep(1)
The reason why the while loop won't break is you don't change the game variable within the while loop. It means if the game is True at the beginning, while game == True is the same as while True loop. You need to revalidate the game in every iteration.
try While"VALORANT-Win64-Shipping.exe" in (i.name() for i in psutil.process_iter()):
BTW, You can directly write While game: instead of While game == True
Related
def timer():
for t in reversed(range(1, 11)):
sleep(1)
print(t)
if foundAllLetters == True:
break
if remaining_attempts == 0:
break
if t == 1:
sleep(1)
print('TIMES UP!')
t1 = Thread(target=timer)
t1.start()
while True:
displayBoard(hang, missedLetters, correctLetters, secretWord)
guess = getGuess(missedLetters + correctLetters)
A short context is I am coding a hangman game. What is going my way is that the timer and loop occurs simultaneously. What is not going my way is that I'm unable to stop the loop and restart the game once the timer is up. gameIsDone = True <- will restart my hangman game. I can't identify what variable to use with it.
I have tried to put gameIsDone = True right under print('TIMES UP!') but nothing happened. I have also tried and added t = 1 in my while loop under else statement, nothing happened.
I am new to python but might have accidentally picked an intermediate activity for my project :\
Does anyone know how to restart the program like, for example, when a player reaches 5 points, after the text "Player a Wins" it will give a certain amount of time delay and then directly restart the game from 0 0. i created the score thingy but got stuck on restarting the program once it reaches 5 points?
I have imported turtle as game in the beginning.
if (scoreboard_a > 4):
win.write("Player A WINS!", font=textfont2)
game.reset()
elif (scoreboard_b > 4):
win.write("Player B WINS!", font=textfont2)
game.reset()
You can restart the whole program like this:
import os
import sys
import time
time.sleep(2)
os.execl(sys.executable, sys.executable, *sys.argv)
Or, you can reset the score(s) and other elements, like:
time.sleep(2)
# reset variables
You can use a while loop; put all your code, expect maybe not the imports, into a while loop:
import turtle
from time import sleep
while True:
# All your game code here
scoreboard_a = 0
scoreboard_b = 0
if (scoreboard_a > 4):
win.write("Player A WINS!", font=textfont2)
elif (scoreboard_b > 4):
win.write("Player B WINS!", font=textfont2)
sleep(2)
If your game is already in a while loop, use break when the game ends:
import turtle
from time import sleep
while True:
# All your game code here
scoreboard_a = 0
scoreboard_b = 0
while True:
# All your game code here
if (scoreboard_a > 4):
win.write("Player A WINS!", font=textfont2)
sleep(2)
break
elif (scoreboard_b > 4):
win.write("Player B WINS!", font=textfont2)
sleep(2)
break
here's my code:
import time
import datetime
from playsound import playsound
print("pls use the 24 hour time scale")
alarmHour = int(input("what time do you want to wake up? "))
alarmMin = int(input("what min do you want to wake up at? "))
while True:
if(alarmHour == datetime.datetime.now().hour and
alarmMin == datetime.datetime.now().minute):
while True:
playsound("D:/Soul and Mind - E's Jammy Jams.mp3")
print("time for some coffee sleepy head")
break
else:
print("i'm not there yet")
time.sleep(10)
it's just a simple alarm clock that when it hit's a certain time it plays a sound.
and untill then every 10sec it prints "i'm not there yet" and i want to make a count down to the alarm. right next to the ("i'm not there yet"). how can i do that?
You could do it with a simple math calculation.
while True:
if(alarmHour == datetime.datetime.now().hour and
alarmMin == datetime.datetime.now().minute):
while True:
playsound("D:/Soul and Mind - E's Jammy Jams.mp3")
print("time for some coffee sleepy head")
break
else:
hoursLeft = alarmHour - datetime.datetime.now().hour
if hoursLeft <= 0:
hoursLeft += 24
minsLeft = alarmMin - datetime.datetime.now().minute
if minsLeft < 0:
minsLeft += 60
print (f'{hoursLeft}h{minsLeft}m left till the alarm')
Hello so I have a small snippet of code from my larger code that is meant for displaying the health bar of an enemy in a game but for some reason, the loop is continuing even after I think it should stop, is there something I'm missing or doing wrong?
import pygame, sys
import time
import random
import os
import sqlite3
import os.path
damage_done = 1
random_monster_health = random.randint(7,10)
alive = True
print (random_monster_health)
while alive == True:
mob_health = random_monster_health - damage_done
print ("mob health is {}" .format(mob_health))
if mob_health != 0:
percent_damage_done = mob_health / int(random_monster_health)
how_much_health_bar = 1180 * (percent_damage_done)
else:
pass
random_monster_health = mob_health
print(random_monster_health)
if mob_health != 0:
print("the monster is still alive")
pass
else:
alive == False
print ("the monster is dead")
pass
print("the loop has ended")
else:
alive == False
print ("the monster is dead")
pass
This part is wrong. Your are comparing alive with False
It should be
else:
alive = False
print ("the monster is dead")
Sidenote: You dont need to use pass in every single if statement.
Sorry if I just did something stupid, I have never used pygame before.
I'm trying to make pygame play morse code by looking at a string and playing the sound accordingly, although when I run it, it only plays the short beep 3 times and the long beep once. is this because multiple beeps are playing at the same time? can someone help, because I have no experience whatsoever with pygame.
Here is my code:
from pygame import mixer
import os
import time
CURR_DIR = os.path.dirname(os.path.realpath(__file__))
mixer.init()
l = ".... . .-.. ---"
h = list(l)
print(h)
def play(CURR_DIR, l):
for i in l:
if i == ".":
mixer.music.load(CURR_DIR + "\short beep.mp3")
mixer.music.set_volume(0.7)
mixer.music.play()
print(".")
elif i == "-":
mixer.music.load(CURR_DIR + "\long beep.mp3")
mixer.music.set_volume(0.7)
mixer.music.play()
print("-")
elif i == " ":
time.sleep(1)
print(" ")
play(CURR_DIR, l)
You have to wait until the music has finished playing with pygame.mixer.music.get_busy(). e.g.:
import os
import pygame
CURR_DIR = os.path.dirname(os.path.realpath(__file__))
pygame.mixer.init()
clock = pygame.time.Clock()
l = ".... . .-.. ---"
i = 0
pause = False
pause_end = 0
run = True
while run:
clock.tick(100)
if pause:
if pygame.time.get_ticks() > pause_end:
pause = False
elif not pygame.mixer.music.get_busy():
if i < len(l):
if l[i] == ".":
pygame.mixer.music.load(CURR_DIR + "/short beep.mp3")
pygame.mixer.music.play(0)
print(".")
elif l[i] == "-":
pygame.mixer.music.load(CURR_DIR + "/long beep.mp3")
pygame.mixer.music.play(0)
print("_")
elif l[i] == " ":
pause_end = pygame.time.get_ticks() + 1000
pause = True
print(" ")
i += 1
else:
run = False
pygame.quit()
exit()
I think I found a solution that does what you are trying to do in another SO question. It requires pygame.mixer.Channel and its set_endevent() function.
https://stackoverflow.com/a/61068408/11620108
In their example:
horn = pygame.mixer.Sound( 'car-horn2.ogg' ) # converted from MP3 to OGG
quack = pygame.mixer.Sound( 'duck-quack.ogg' )
ca_ching = pygame.mixer.Sound( 'cash-register.ogg' )
bark = pygame.mixer.Sound( 'dog-bark.ogg' )
ding = pygame.mixer.Sound( 'single-ding.ogg' )
gobble = pygame.mixer.Sound( 'turkey-gobble.ogg' )
You could assign a variable for each sound. For the pause, you can use your long beep with the volume set to 0.
Example:
morse_dot = pygame.mixer.Sound('short_beep.mp3')
morse_dash = pygame.mixer.Sound('long_beep.mp3')
morse_pause = pygame.mixer.Sound('long_beep.mp3')
morse_pause.set_volume(0)
You could then convert a morse code string into a list of the corresponding sounds by their variable name:
sound_list =[]
for c in morse_code:
if c == ".":
sound_list.append(morse_dot)
elif c == "-":
sound_list.append(morse_dash)
elif c == " ":
sound_list.append(morse_pause)
and play it using the advice found in the other SO answer.