I have recently started working with python, and am fairly new to the subject. Currently, I am working on a project that will simulate keyboard presses depending on specific pixel values on the screen. Basically, if "such pixel" is colored "such color", then click/press. However, my code has a bug. Sometimes, it runs perfectly fine, but then randomly stops running. Other times, it doesn't run at all. In both cases, an error appears (below code). Here is my current code:
import random
import time
import keyboard
import pyautogui
import win32api
import win32con
from pyautogui import *
from pynput.keyboard import Key, Controller
simulate = Controller()
def click(x, y):
win32api.SetCursorPos((x, y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
def jump():
simulate.press(Key.up)
simulate.release(Key.up)
click(650, 540)
print("Jumped!")
def duck():
simulate.press(Key.down)
simulate.release(Key.down)
print("Ducked!")
def restart():
click(950, 500)
def switch():
simulate.press(Key.alt)
simulate.press(Key.tab)
simulate.release(Key.alt)
simulate.release(Key.tab)
def play():
while not keyboard.is_pressed('a'):
if pyautogui.pixel(660, 540)[0] != 247:
jump()
if pyautogui.pixel(950, 500)[0] == 83:
restart()
switch()
play()
switch()
And here is the console:
Traceback (most recent call last):
File "C:...\main.py", line 59, in <module>
play()
File "C:...\main.py", line 51, in play
if pyautogui.pixel(660, 540)[0] != 247:
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\pyscreeze\__init__.py", line 584, in pixel
return (r, g, b)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\contextlib.py", line 124, in __exit__
next(self.gen)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\pyscreeze\__init__.py", line 113, in __win32_openDC
raise WindowsError("windll.user32.ReleaseDC failed : return 0")
OSError: windll.user32.ReleaseDC failed : return 0
Process finished with exit code 1
Why does this code only work sometimes, and then randomly stop? Is it an issue with downloads or imports, or something else? If you could help, that would be greatly appreciated. Thank you!