I am making a bot that makes the chrome dinosaur jump every time it sees a cactus.
The RGB for the cactus is (83,83,83)
I made a specific coordinate for my code to look at, and check if the RGB of that pixel matches the cactus (jump_place)
However, when I run it, it works for about 2 seconds, and then gives me this error:
Traceback (most recent call last):
File "c:\Users\dofia\OneDrive\Desktop\coding VS\Other Projects\DINO BOT\tempCodeRunnerFile.py", line 29, in <module>
if pyautogui.pixel(810, 635)[0] == 83:
File "C:\Users\dofia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pyscreeze\__init__.py", line 584, in pixel
return (r, g, b)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.496.0_x64__qbz5n2kfra8p0\lib\contextlib.py", line 124, in __exit__
next(self.gen)
File "C:\Users\dofia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\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
Here is my code:
from pyautogui import *
import pyautogui
import time
import keyboard
import random
time.sleep(3)
replay = (1127,591)
jump_place = (866,630)
def restart():
pyautogui.click(replay)
def jump():
pyautogui.keyDown('space')
time.sleep(0.5)
print("Jump!")
pyautogui.keyUp('space')
restart()
while keyboard.is_pressed('p') == False:
if pyautogui.pixel(810, 635)[0] == 83:
jump()
Is there anything I am doing wrong?
The link to the dinosaur game is: http://www.trex-game.skipser.com/
Related
Hey i am trying to locate an image but get this error on why i use the value as (any,any,250,250) but doesnt show the error when i use(any,any,350(more than 350),250(more than 250))
here is my code
`
from pyautogui import *
import pyautogui
import time
import keyboard
import random
import win32api, win32con
import cv2
import numpy as np
PlayerOnRight = False
PlayerOnFullRight = False
PlayerOnFullLeft = False
PlayerOnLeft = False
PlayerOnMiddle = False
while 1:
if PlayerOnMiddle == True and pyautogui.locateOnScreen('player.png', region=(1080,600,800,200), confidence=0.7) != None:
print("Right Side")
time.sleep(0.5)
if pyautogui.locateOnScreen('player.png', region=(825,800,250,250), confidence=0.3) !=None:
print("Left Side")
time.sleep(0.5)
`
here is the error
`Traceback (most recent call last):
File "C:\Users\Admin\Desktop\Pyhton_bot\test.py", line 20, in <module>
if pyautogui.locateOnScreen('player.png', region=(825,800,250,250), confidence=0.3) !=None:
File "C:\Python310\lib\site-packages\pyautogui\__init__.py", line 175, in wrapper
return wrappedFunction(*args, **kwargs)
File "C:\Python310\lib\site-packages\pyautogui\__init__.py", line 213, in locateOnScreen
return pyscreeze.locateOnScreen(*args, **kwargs)
File "C:\Python310\lib\site-packages\pyscreeze\__init__.py", line 373, in locateOnScreen
retVal = locate(image, screenshotIm, **kwargs)
File "C:\Python310\lib\site-packages\pyscreeze\__init__.py", line 353, in locate
points = tuple(locateAll(needleImage, haystackImage, **kwargs))
File "C:\Python310\lib\site-packages\pyscreeze\__init__.py", line 219, in _locateAll_opencv
raise ValueError('needle dimension(s) exceed the haystack image or region dimensions')
ValueError: needle dimension(s) exceed the haystack image or region dimensions
`
i expted it to work noramlly to locate image and pint the given text but got this error
please help me fix this
Because the region has to be bigger than your player.png image. Either crop your player.png image or increase the region size
This question already has answers here:
"non-integer arg 1 for randrange()" in python libary
(3 answers)
Closed 1 year ago.
so the randint is causing a problem, everything else works, but when I try to randomize the time.sleep interval it just spouts errors. I'm pretty new to coding so I don't quite understand the error. (Error is below the code)
from pyautogui import *
from time import sleep
import keyboard
import win32api, win32con
import random
def autoclick():
while keyboard.is_pressed('r') == True:
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
sleep(0.01)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
cpsmin = 0.10 / 1.25 # NUO KIEK CLICKU
cpsmax = 0.12 / 1.25 # IKI KIEK CLICKU
randomizeclicks = random.randint(cpsmin, cpsmax)
sleep(randomizeclicks)
print('RUNNING')
while keyboard.is_pressed('z') == False:
if keyboard.is_pressed('r') == True:
autoclick()
sleep(0.5)
The error code:
Traceback (most recent call last):
File "d:\_Python_Projects\autoclicker.py", line 24, in <module>
autoclick()
File "d:\_Python_Projects\autoclicker.py", line 17, in autoclick
randomizeclicks = random.randint(cpsmin, cpsmax)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\random.py", line 339, in randint
return self.randrange(a, b+1)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\random.py", line 303, in randrange
raise ValueError("non-integer arg 1 for randrange()")
ValueError: non-integer arg 1 for randrange()
you are passing floats while only integers are allowed as input for randint
I'm really new to python and I don't even know if the title of this python question is even right. Anyways I'm facing an error code that I have been trying to find a fix for in the last couple of hours. The error goes like this: raise RuntimeError("threads can only be started once").
Now I googled the error and I got a couple of solutions. I tried a couple of them and none of them seem to work. I know that you cannot use the start function for more than one time, But how else am I supposed to get my script to work again?
import pyautogui, requests, pyperclip
from pynput import mouse, keyboard
from tkinter import filedialog
url = "https://poxgur.com/"
file_path = filedialog.asksaveasfilename(defaultextension='.png')
def on_click(x, y, button, pressed):
global currentMouseX, currentMouseY
if pressed:
currentMouseX, currentMouseY = x, y
if not pressed:
mouse_listener.stop()
im = pyautogui.screenshot(region=(
currentMouseX, currentMouseY, abs(currentMouseX - x), abs(currentMouseY - y)))
im.save(file_path)
print(file_path)
files = {"file": open(file_path, "rb")}
r = requests.post(url + "api.php", files=files)
pyperclip.copy(url + r.text + ".png")
# os.remove(file_path)
mouse_listener.stop()
return False
mouse_listener = mouse.Listener(on_click=on_click)
def on_scroll_lock_release(key):
if key == keyboard.Key.scroll_lock:
if not mouse_listener.is_alive():
mouse_listener.start()
with keyboard.Listener(on_release=on_scroll_lock_release) as listener:
listener.join()
The error meesage:
Unhandled exception in listener callback
Traceback (most recent call last):
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\pynput\_util\__init__.py", line 162, in inner
return f(self, *args, **kwargs)
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\pynput\keyboard\_win32.py", line 283, in _process
self.on_release(key)
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\pynput\_util\__init__.py", line 78, in inner
if f(*args) is False:
File "C:/Users/marti/Documents/PythonProjects/Acutal Projects/The 100 Projects/Screenshot2.0.py", line 33, in on_scroll_lock_release
mouse_listener.start()
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\threading.py", line 848, in start
raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once
Traceback (most recent call last):
File "C:/Users/marti/Documents/PythonProjects/Acutal Projects/The 100 Projects/Screenshot2.0.py", line 37, in <module>
listener.join()
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\pynput\_util\__init__.py", line 210, in join
six.reraise(exc_type, exc_value, exc_traceback)
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\six.py", line 702, in reraise
raise value.with_traceback(tb)
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\pynput\_util\__init__.py", line 162, in inner
return f(self, *args, **kwargs)
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\pynput\keyboard\_win32.py", line 283, in _process
self.on_release(key)
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\site-packages\pynput\_util\__init__.py", line 78, in inner
if f(*args) is False:
File "C:/Users/marti/Documents/PythonProjects/Acutal Projects/The 100 Projects/Screenshot2.0.py", line 33, in on_scroll_lock_release
mouse_listener.start()
File "C:\Users\marti\anaconda3\envs\The 100 Projects\lib\threading.py", line 848, in start
raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once
Process finished with exit code 1
A possible solution would be to intialize a new Listener each time before starting the Listener.
You could re-code your solution in the following way:
mouse_listener = mouse.Listener(on_click=on_click)
def on_scroll_lock_release(key):
if key == keyboard.Key.scroll_lock:
if not mouse_listener.is_alive():
mouse_listener = mouse.Listener(on_click=on_click)
mouse_listener.start()
I'm trying to run the following code,
from pykinect import nui
from pykinect.nui import JointId
from pykinect.nui import SkeletonTrackingState
from pykinect.nui import TransformSmoothParameters
with nui.Runtime() as kinect:
kinect.skeleton_frame_ready+=skeleton_frame_ready
kinect.skeleton_engine.enable=True
while True:
frame= kinect.skeleton_engine.get_next_frame()
for skeleton in frame.SkeletonData:
def skeleton_fram_raedy(skeleton_frame):
for index,data in enumerate(skeleton):
if skeleton.eTrackingState==nui.SkeletonTrackingState.TRACKED:
head=data.SkeletonPositions[JointId.Head]
print head
but Kinect shuts down and gives the following error:
Traceback (most recent call last):
File "C:\Users\sayyed javed ahmed\Desktop\Humaira\Practice Codes-Python\skeletonnew.py", line 5, in <module>
with nui.Runtime() as kinect:
File "C:\Python27\lib\site-packages\pykinect\nui\__init__.py", line 126, in __init__
self.camera = Camera(self)
File "C:\Python27\lib\site-packages\pykinect\nui\__init__.py", line 352, in __init__
self.elevation_angle
File "C:\Python27\lib\site-packages\pykinect\nui\__init__.py", line 359, in get_elevation_angle
return self.runtime._nui.NuiCameraElevationGetAngle()
File "C:\Python27\lib\site-packages\pykinect\nui\_interop.py", line 200, in NuiCameraElevationGetAngle
_NuiInstance._NuiCameraElevationGetAngle(self, ctypes.byref(res))
File "_ctypes/callproc.c", line 950, in GetResult
WindowsError: [Error -2147024883] The data is invalid
I'm new to PyKinect so any help is appreciated! Thanks!
Firstly, there are typos in your code. You're assigning a callback to skeleton_frame_ready function in kinect.skeleton_frame_ready+=skeleton_frame_ready, but have defined it as def skeleton_fram_raedy(skeleton_frame).
Secondly, I think your indentation is off, you have a function definition in a for loop in a while loop:
while True:
frame= kinect.skeleton_engine.get_next_frame()
for skeleton in frame.SkeletonData:
def skeleton_fram_raedy(skeleton_frame):
...
Try something like this:
from pykinect import nui
from pykinect.nui import JointId
from pykinect.nui import SkeletonTrackingState
from pykinect.nui import TransformSmoothParameters
def skeleton_frame_ready(skeleton_frame):
for skeleton in frame.SkeletonData:
if skeleton.eTrackingState==nui.SkeletonTrackingState.TRACKED:
for index,data in enumerate(skeleton):
head=data.SkeletonPositions[JointId.Head]
print head
with nui.Runtime() as kinect:
kinect.skeleton_frame_ready+=skeleton_frame_ready
kinect.skeleton_engine.enable=True
while True:
frame= kinect.skeleton_engine.get_next_frame()
Thirdly, the error indicates that invalid argument is passed to nui for the kinect camera angle. Not sure why that is. You could try setting the elevation angle to 0 right after initializing nui:
with nui.Runtime() as kinect:
kinect.camera.elevation_angle = 0
kinect.skeleton_frame_ready+=skeleton_frame_ready
*Nanpy allows for a Raspi to have an Arduino slave through python
Right now I'm having extreme difficulty in using the nanpy Servo package, and I cant get it to run correctly. I'm using it to make a robot that is wirelessly controlled from a computer, this is what I have for code:
from nanpy import (ArduinoApi, SerialManager)
import pygame
from nanpy import Servo
import time
pygame.init()
a=0
d=0
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("Console")
try :
connection = SerialManager()
ard = ArduinoApi(connection = connection)
run = True
except:
print("Connection Failed!")
servoA = Servo(2)
servoD = Servo(4)
while run :
for event in pygame.event.get():
keys = pygame.key.get_pressed()
# if (event.type==pygame.KEYDOWN):
if keys[pygame.K_s] and keys[pygame.K_a]:
a=a-1
servoA.write(a)
elif keys[pygame.K_s] and keys[pygame.K_d]:
d=d-1
servoD.write(d)
elif keys[pygame.K_w]:
a=a+1
d=d+1
servoD.write(d)
servoA.write(a)
elif keys[pygame.K_s]:
a=a-1
d=d-1
servoD.write(d)
servoA.write(a)
elif keys[pygame.K_d]:
d=d+1
servoD.write(d)
elif keys[pygame.K_a]:
a=a+1
servoA.write(a)
elif keys[pygame.K_t]:
run=False
pygame.quit()
This is the error the python shell throws:
Traceback (most recent call last):
File "/home/pi/Desktop/nanpy/RobotCode.py", line 28, in <module>
servoA = Servo(2)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/servo.py", line 9, in __init__
self.id = self.call('new', pin)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 150, in call
return _call(self.namespace, self.id, args, self.connection)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 47, in _call
ret = return_value(connection)
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/arduinoboard.py", line 18, in return_value
return serial_manager.readline().replace('\r\n', '')
File "/usr/local/lib/python3.4/dist-packages/nanpy-0.9.6-py3.4.egg/nanpy/serialmanager.py", line 101, in readline
raise SerialManagerError('Serial timeout!')
nanpy.serialmanager.SerialManagerError: Serial timeout!
How can I fix this, and/or what am I doing wrong?
You need to specify the port of the Arduino. So could you try:
connection = SerialManager(device='/dev/ttyACM0')
or whatever port you are using.
update the configuration file to use the servo and upload it to arduino using the IDE then run this program.
you can find the cfg.h file in nanpy-firmware/nanpy folder.