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
Related
So it just breaks when holding down while holding down SHIFT ALT or CTRL While the function is running, When It does break I do try tapping SHIFT ALT and CTRL to see if they are stuck down and they aren't so I'm all out of ideas.
import time
import pyautogui
import random
def feint():
number = random.randint(1,4)
print('1')
if number == 1:
pyautogui.keyDown('LEFT')
pyautogui.mouseDown()
pyautogui.keyUp('LEFT')
time.sleep(0.1)
pyautogui.keyDown('ctrl')
pyautogui.keyUp('ctrl')
pyautogui.mouseUp()
if number == 2:
#ETC
The feint2() Is just the same code twice with already used options out of play and the attack is the same as the feint() without the pyautogui.keyDown('ctrl') pyautogui.keyUp('ctrl')
import pyautogui
import random
import feinter
from attacker import attack
import keyboard
pyautogui.FAILSAFE = False
def feintmarco():
number = random.randint(1,2)
if number == 1:
feinter.feint()
print('0')
attack()
if number == 2:
feinter.feint2()
print('0')
attack()
keyboard.add_hotkey('Num -', feintmarco)
keyboard.wait()
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
I want to write a bot that will simulate mouse movements when user is away for more than 5 minutes and stay put when user takes control i.e. moves the mouse.
I have written following code as a part of the program.
Here is the link to my old program which clicks at given points periodically. The problem with this program is I have to start the program when I want to go somewhere and after returning close the program in order to resume working.
Here is the one of the module I wrote for the new program which detects whether mouse is moving or not.
import win32api
from time import sleep
print("starting engine.")
count = 0
while(True):
savedpos = win32api.GetCursorPos()
if count>20*5:
break
sleep(1)
curpos = win32api.GetCursorPos()
if savedpos == curpos:
savedpos = curpos
print("Mouse is steady.")
else:
print("Mouse is moving.")
count += 1
I wont be writing the code but I have the Idea to solve the problem
you use pyautogui.position() to keep checking the position and if it doesnt change position for 300 seconds you move it
I wrote following code referring other Stackoverflow posts.
This code waits 4 minutes for mouse being steady. Whenever mouse is moved, timer is reset to zero.
import win32api
from time import sleep
import pyautogui as gui
print("starting engine.")
count = 0
savedpos = win32api.GetCursorPos()
def actions():
print(gui.size())
while True:
#toast.show_toast("ROBOT V2 !", "Robot is active.", threaded=False, icon_path=None, duration=2)
gui.click()
gui.press('home')
gui.moveTo(541, 142, 0.25) # Money Transfer dropdown
gui.click()
sleep(0.5)
gui.moveTo(541, 172, 0.25) # Money Transfer link
gui.click()
sleep(5)
cond()
def cond():
count = 0
while True:
savedpos = win32api.GetCursorPos()
sleep(0.5)
curpos = win32api.GetCursorPos()
if savedpos == curpos:
savedpos = curpos
print("Mouse is steady. Elapsed time: ", (count+1)/2, " seconds.")
count += 1
if count >= 480: # if count is greater than 60 it means timeout will occur after mouse is steady for more than
# 240 seconds i.e. 4 minutes. (approx.)
print("User away for more than 4 minutes, taking control of the system.")
actions()
break
else:
pass
else:
print("Mouse is moving.")
count = 0
cond()
Im trying to move my Cursor every three seconds and if it went too far, reset it to its original location. I want the program to stop after I press any key on the keyboard.
It doesnt seem to work though... what could I be missing? This is what I came up with:
import win32api, win32con, time, sys, msvcrt
global z
z=10
def kbfunc():
#this is boolean for whether the keyboard has bene hit
x = msvcrt.kbhit()
if x:
sys.exit
else:
ret = False
return ret
def move(x,y):
win32api.mouse_event(win32con.MOUSEEVENTF_MOVE | win32con.MOUSEEVENTF_ABSOLUTE, int(x/1920*65535.0), int(y/1080*65535.0))
while True:
move(960,540+z)
time.sleep(3)
if z>100:
move(960,540)
z += -100
z + 10
kbfunc()
First, you need to install the keyboard module:
pip3 install keyboard
And than add it to your loop:
import keyboard
while True:
move(960,540+z)
time.sleep(3)
if z>100:
move(960,540)
z += -100
z + 10
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
I would guess that msvcrt.kbhit() does not store previous hits. It only tells you if a key is hit at the current moment in time. You can loop checking for keyboard hits. If no hits before 3 seconds, return:
import time
import msvcrt
import sys
def kbfunc(max_time=3):
start = time.time()
while not msvcrt.kbhit():
end = time.time()
if end - start >= max_time:
break
else:
sys.exit()
After trying around with the given answers, the finished solution looks like this:
global z
z=10
def move():
mouse.move(10, 10, absolute=False, duration=1)
def moveback():
mouse.move(-10, -10, absolute=False, duration=1)
while True:
move()
time.sleep(3)
moveback()
if keyboard.is_pressed('q'): # if key 'q' is pressed
break # finishing the loop
everything works except the next song doesn't play after the first is finished.
import os, random
from pygame import mixer
from pynput import keyboard
startup = 0
pause = 0
volume = 0.5
def Picker():
global startup
global volume
startup += 1
if startup > 1:
ThisSong = random.choice(os.listdir("C:\\Users\\...\\Music"))
NextSong = random.choice(os.listdir("C:\\Users\\...\\Music"))
ThisSong = NextSong
if ThisSong != NextSong:
mixer.init()
mixer.music.load("C:\\Users\\...\\Music" + ThisSong)
mixer.music.play(0)
mixer.music.set_volume(volume)
while mixer.music.get_busy():
def on_press(key):
global pause
global volume
if key == keyboard.KeyCode(char='-'):
volume -= 0.1
if volume < 0.1:
volume = 0.1
mixer.music.set_volume(volume)
if key == keyboard.KeyCode(char='='):
volume += 0.1
if volume > 1:
volume = 1
mixer.music.set_volume(volume)
if key == keyboard.KeyCode(char='['):
pause += 1
if pause == 1:
mixer.music.pause()
pause = 2
if pause == 3:
mixer.music.unpause()
pause = 0
with keyboard.Listener(on_press=on_press) as listener: listener.join()
else:
Picker()
else:
pass
Picker()
Picker()
screenshot of code
I can't get it to work, i'm very new to python so i'm probably missing something
obvious
Before starting: Thx #JGreenwell for copying the code.
Ok, so first, I’ll help you clean your code.
Things that are wrong
Having all that ThisSong and NextSong things: It won’t get saved when you restart Picker(). Either just have ThisSong, or place the ThisSong and NextSong assignment with the volume and pause variables:
.
pause = 0 # this is a problem! Next point
volume = 0.5
ThisSong = random.choice(...)
NextSong = random.choice(...)
The pause variable should be a boolean (True/False) and the pausing code should be like this:
.
pause = not pause
if pause:
# pause
else:
# unpause
Also, it would ideally be called paused
on_press and the Listener declaration should be outside the while loop, because otherwise they just keep being declared every time it loops. Then you should import time and put time.sleep(500) or something like that in the while loop, so that it doesn’t check every fraction of second.
As for the next song not playing, I don’t really know, but I’d suggest entering Picker() in the shell after the program has run (python -i script.py from CMD, IDLE leaves you in a shell by default). I would also suggest really following recommendation #3 as having them in the loop may break the loop and stop it from finishing. Most importantly, I would ask you to debug your code by adding print in every step of your code:
print(1)
if something:
print(2)
etc...
And seeing where it blocks
P.S.: The random dots are because you can’t have code in lists, so I had to exit the list.
Working solution, incase anyone else has the same problem as me in the future :)
from pygame import mixer
from pynput import keyboard
import threading
import random
import os
paused = 0
def player():
song = random.choice(os.listdir("C:\\users\\...\\desktop\\music"))
mixer.init()
mixer.music.load("C:\\users\\...\\desktop\\music\\" + song)
mixer.music.play(0)
while mixer.music.get_busy():
pass
else:
player()
def main():
t = threading.Thread(target = player, name = 'thread1', args = ())
t.start()
main()
def on_press(key):
global paused
if key == keyboard.KeyCode(char='['):
paused = not paused
if paused:
mixer.music.pause()
else:
mixer.music.unpause()
with keyboard.Listener(on_press=on_press) as listener: listener.join()