Python: script gets stuck on Keyboard.wait() - python

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()

Related

Python: Turn on / off switch to start / stop loop instantly

import time
import pyautogui
from pyautogui import *
import keyboard
from PIL import ImageGrab
import os
import win32api, win32con
import cv2
import pyperclip
from pynput.keyboard import Key, Listener
import pytesseract
##1340,182, 1777, 213
test = 0
def alertf1(c):
global test
while c == 1:
if keyboard.is_pressed('f1'): # if key 'f1' is pressed
print('f1 has been pressed')
c = 0
time.sleep(0.1)
test = test + 1
break
else:
print('checking if anything is destroyed')
time.sleep(1)
if pyautogui.locateOnScreen('destroy2.png', region=(1340,182, 1777, 230)):
print('something got destroyed!')
time.sleep(0.1)
pyautogui.keyDown('ctrl')
time.sleep(0.1)
pyautogui.keyDown('tab')
pyautogui.keyUp('ctrl')
pyautogui.keyUp('tab')
time.sleep(0.5)
for char in '#':
pyperclip.copy(char)
pyautogui.hotkey('ctrl', 'v', interval=0.1)
time.sleep(0.1)
pyautogui.write('everyone Enemies/Red Logs! Something has been destroyed.')
time.sleep(0.1)
pyautogui.press('enter')
time.sleep(5)
pyautogui.click(x=1860, y=50)
time.sleep(5)
else:
if keyboard.is_pressed('f1'): # if key 'f1' is pressed
print('f1 has been pressed')
c = 0
time.sleep(0.1)
test = test + 1
break
def on_press(key):
global test
if test > 0 and key == Key.f1:
c = 0
if key == Key.f1 and test == 0:
print('before alert f1 pressed')
time.sleep(0.1)
test = test + 1
alertf1(1)
if key == Key.f1 and test > 1:
test = 0
with Listener(on_press=on_press) as listener:
listener.join()
def main():
while True:
time.sleep(0.1)
print('on press going now')
on_press(key)
if __name__ == '__main__':
main()
my issue is that i want the turn on / off switch to use hte same key
and i can't think of a way to distinguish between when I press the key and when the program is simply on loop.
like F1 will start function alert, which will loop eternally, until I press F1, issue is that, if keyboard.is_pressed('f1'): isn't a great solution
because if code is somewhere else it wont recognize i pressed f1

How to restart a turtle graphics program back to the beginning?

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

How to stop or pause pyautogui at any moment that I want?

I am building some macro program using pyautogui.
Unfortunately I am not able to stop for-loop so sometimes it takes too much time until for-loop end.
Is there any way to stop the program at any moment I want? or I just wait until program end.
below is my code
CURRENT_DIR = os.getcwd()
list = os.path.join(CURRENT_DIR,'BOM_list.xlsx')
df = pd.read_excel(list)
for i in df['MLFB'].index:
MLFB = df.loc[i, 'MLFB']
print(MLFB)
a = pyautogui.locateCenterOnScreen('a_material.png')
print(a)
pyautogui.moveTo(a)
pyautogui.moveRel(350, 0)
pyautogui.click()
pyautogui.keyDown('ctrl')
pyautogui.press('a')
pyautogui.keyUp('ctrl')
pyautogui.typewrite(MLFB)
b = pyautogui.locateCenterOnScreen('b_execute.png')
print(b)
pyautogui.moveTo(b)
pyautogui.click()
time.sleep(2.5)
pyautogui.keyDown('alt')
pyautogui.press('y')
pyautogui.press('t')
pyautogui.press('a')
pyautogui.press('i')
pyautogui.keyUp('alt')
time.sleep(2)
pyautogui.press('down')
pyautogui.typewrite(['enter'])
time.sleep(2)
c = pyautogui.locateCenterOnScreen('c_Directory.png')
pyautogui.moveTo(c)
pyautogui.moveRel(350, 0)
pyautogui.click()
pyautogui.keyDown('ctrl')
pyautogui.press('a')
pyautogui.keyUp('ctrl')
pyautogui.typewrite(CURRENT_DIR)
pyautogui.click()
time.sleep(1.5)
d = pyautogui.locateCenterOnScreen('d_Filename.png')
pyautogui.moveTo(d)
pyautogui.moveRel(350, 0)
pyautogui.click()
pyautogui.keyDown('ctrl')
pyautogui.press('left')
pyautogui.keyUp('ctrl')
pyautogui.typewrite(MLFB)
time.sleep(0.5)
pyautogui.typewrite(['enter'])
time.sleep(2)
e = pyautogui.locateCenterOnScreen('e_go_back.png')
pyautogui.moveTo(e)
pyautogui.click()
time.sleep(2)
PyAutoGUI has a built in failsafe to terminate the program at any time. Just move your mouse to the top left corner of your main monitor where your x, y values would be 0, 0.
Typing print(pyautogui.FAILSAFE) should return True, telling us the failsafe is on. You could also disable it if it's getting in the way of your program by setting it to pyautogui.FAILSAFE = False
Looking through your code, you could save some space by using hotkey() when you want to press more than one key at a time:
pyautogui.keyDown('ctrl')
pyautogui.press('a')
pyautogui.keyUp('ctrl')
Is the same as:
pyautogui.hotkey('ctrl', 'a')
You could also check out threading which allows you to run more than one process at a time.
The following code will have an example main program running and when the Esc key is pressed, the main program will pause and the user is prompted if they want to continue or not.
import time
from threading import Thread
from pynput import keyboard
def exit_program():
def on_press(key):
if str(key) == 'Key.esc':
main.status = 'pause'
user_input = input('Program paused, would you like to continue? (y/n) ')
while user_input != 'y' and user_input != 'n':
user_input = input('Incorrect input, try either "y" or "n" ')
if user_input == 'y':
main.status = 'run'
elif user_input == 'n':
main.status = 'exit'
exit()
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
def main():
main.status = 'run'
while True:
print('running')
time.sleep(1)
while main.status == 'pause':
time.sleep(1)
if main.status == 'exit':
print('Main program closing')
break
Thread(target=main).start()
Thread(target=exit_program).start()

How to exit a function because a key was pressed?

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

Python exit code execution after pressing key

I want to make clicker for my game and i don't know how can I exit program after I press a key. I've tried
import sys
screenWidth, screenHeight = pyautogui.size()
currentMouseX, currentMouseY = pyautogui.position()
if keyboard.is_pressed("p"):
sys.exit()
for user in range(0, 1):
pyautogui.moveTo(849, 657) # załóż druzyne
pyautogui.click()
pyautogui.PAUSE = 0.2
pyautogui.typewrite('Bandaelo')
pyautogui.PAUSE = 0.3
pyautogui.moveTo(953, 742) # potwierdź
pyautogui.click()
pyautogui.PAUSE = 0.4
pyautogui.moveTo(948, 656) # potwierdz
pyautogui.click()
and more code like this
but it doesn't work. Can You help me?
This should do the trick, you still need to put your code:
import sys
import pyautogui
def main():
screenWidth, screenHeight = pyautogui.size()
currentMouseX, currentMouseY = pyautogui.position()
try:
while 1:
var = input("enter p to exit: ")
if var == 'p':
break
else:
print('test something')
# put your code here...
# and more code like this
except KeyboardInterrupt:
sys.exit()
raise
if __name__ == '__main__':
main()
You need to import sys object. Then call the exit() method to stop your program.
For your case you can try:
import keyboard
import sys
if keyboard.is_pressed("p"):
sys.exit()
EDIT : I have done a little research and find when writing a multithreaded app, raise SystemExit and sys.exit() both terminates only the running thread. In this case, you can use os._exit() which exits the whole process.
import os
import keyboard
if keyboard.is_pressed('p'):
os._exit(0)

Categories

Resources