(PYTHON) Randint spouting errors [duplicate] - python

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

Related

Cant locate image on pyautogui

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

Bot crashing from pyautogui

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/

Python: IndexError: list index out of range happens in some case only

I have been making a programme about a tic-tac-toe game which requires two players take turn to input like the coordinate of the board, like (r1,c1)->(r2,c2)->(r3,c3)-> …, in which r is the row and c is the column and the board look like
0 1 2
3 4 5
6 7 8
The programme I typed:
board=[0,1,2,3,4,5,6,7,8]
def show():
print(str(board[0])+str(board[1])+str(board[2]))
print(str(board[3])+str(board[4])+str(board[5]))
print(str(board[6])+str(board[7])+str(board[8]))
def check(char,spot1,spot2,spot3):
if board[spot1]==char and board[spot2]==char and board[spot3]==char:
return True
def checkAll(char):
if check(char,0,1,2):
return True
if check(char,3,4,5):
return True
if check(char,6,7,8):
return True
if check(char,0,3,6):
return True
if check(char,1,4,7):
return True
if check(char,2,5,8):
return True
if check(char,0,4,8):
return True
if check(char,2,4,6):
return True
else:
return False
def ChangeSpotInputToAList(spotInput):
spotafter=[]
for i in spotInput:
if i=="(0,0)":
spotafter.append(0)
if i=="(0,1)":
spotafter.append(1)
if i=="(0,2)":
spotafter.append(2)
if i=="(1,0)":
spotafter.append(3)
if i=="(1,1)":
spotafter.append(4)
if i=="(1,2)":
spotafter.append(5)
if i=="(2,0)":
spotafter.append(6)
if i=="(2,1)":
spotafter.append(7)
if i=="(2,2)":
spotafter.append(8)
return spotafter
i=0
spotInput=input().split("->")
spotafter=ChangeSpotInputToAList(spotInput)
for x in spotafter:
show()
if spotafter[x]%2==0:
print("X-->",x)
spot=x
i+=1
char="X"
board[spot]=char
if i==9:
show()
print("Winner: None")
break
if checkAll(char):
show()
print("Winner:",char)
break
if spotafter[x]%2==1:
print("O-->",x)
spot=x
i+=1
char="O"
board[spot]=char
if i==9:
show()
print("Winner: None")
break
if checkAll(char):
show()
print("Winner:",char)
break
I have tried some input but one of them keeps making an error, which is (2,2)->(0,0)->(1,1)->(0,2)->(1,0)->(0,1), and the programme shows:
012
345
678
Traceback (most recent call last):
File "thisishardlol.py", line 55, in <module>
if spotafter[x]%2==0:
IndexError: list index out of range
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
from apport.fileutils import likely_packaged, get_recent_crashes
File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
from apport.report import Report
File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
import apport.fileutils
File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
from apport.packaging_impl import impl as packaging
File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 24, in <module>
import apt
File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'
Original exception was:
Traceback (most recent call last):
File "thisishardlol.py", line 55, in <module>
if spotafter[x]%2==0:
IndexError: list index out of range
Does anyone know where am I wrong? Any help would be very greatly appreciated!
Let's run through a scenario.
spotInput=input().split("->")
spotafter=ChangeSpotInputToAList(spotInput)
If I input (2,2)->(2,2) then spotafter = [8,8]
Now I enter my for loop:
for x in spotafter:
show()
if spotafter[x]%2==0:
In my first loop x = 8 and im trying to get spotafter[8], which doesnt exist (spotafter only has 2 elements).
I cant help much more since I dont know your goal, but thats why you're getting the IndexError.

How do I pickle pyEphem objects for multiprocessing?

I am trying to calculate some values of satellites, the data-generation takes quite long so I want to implement this using multiprocessing.
The problem is that I get this error from pyEphem, TypeError: can't pickle ephem.EarthSatellite objects. The pyEphem objects are not used in the functions that I want to parallelize.
This is an example file of my code (minimized).
This is my main file:
main.py
import ephem
import numpy
import math
import multiprocessing as mp
from SampleSats import Sats
GPS_Satellites = []
SFrames = 1
TLE = ["GPS BIIR-3 (PRN 11)",
"1 25933U 99055A 18090.43292845 -.00000054 00000-0 00000+0 0 9994",
"2 25933 51.8367 65.0783 0165007 100.2058 316.9161 2.00568927135407"]
# PRN TLE file from CelesTrak
GPS_Satellites.append(Sats(TLE))
Position = ephem.Observer()
Position.date = '2018/3/31 00:00' # 1st January 2018 at 00:00 UTC
Position.lon, Position.lat = "36.845663", "-37.161123" # Coordinates for desired Position
# Calculate Satellites
for Frames in range(SFrames):
print("Generate Signals for Time: ", Position.date)
for Sats in GPS_Satellites: # par
Sats.compute(Position)
if ((float(repr(Sats.ephemeris.alt)) * 180 / math.pi) < 5) or ( # Calculate angle above horizon
(float(repr(Sats.ephemeris.alt)) * 180 / math.pi) > 90):
Sats.visible = 0
else:
Sats.visible = 1
with mp.Pool() as pool:
for value, obj in zip(pool.map(Sats.genSignal, GPS_Satellites), GPS_Satellites):
obj.Signal = value
Position.date = Position.date + 6*ephem.second # 1 Subframe is 6 seconds long
This is the Sats class that i wrote:
sats.py:
import ephem
import numpy
class Sats:
"""Save Satellites as Objects"""
def __init__(self, tle):
""":param tle: Two Line Element for ephemeris data also used to get PRN Number from name"""
self.ephemeris = ephem.readtle(tle[0], tle[1], tle[2])
self.visible = 1
self.subframes = 0
self.CAseq = [x for x in range(1023)]
self.Out = []
self.Signal = numpy.zeros(int(300*20*1023), dtype=numpy.int8)
def compute(self, pos):
self.ephemeris.compute(pos)
self.Out.append(numpy.arange(0, 299, 1))
self.subframes += 1
def calcData(self, bit, prn):
return (self.Out[self.subframes - 1].item(0)[0][bit] + self.CAseq[prn]) % 2
def genSignal(self):
if(self.visible == 1):
for bit in range(300): # 1 Subframe is 300 Bit long
for x in range(20): # The PRN Sequence reoccurs every ms -> 20 times per pit
for prn in range(1023): # length of the prn sequence
self.Signal[bit*x*prn] = (-1 if (self.calcData(bit, prn))==0 else 1)
else:
self.Signal = numpy.zeros(300*20*1023)
return self.Signal
Traceback:
Traceback (most recent call last):
File "C:/Users/PATH_TO_PROJECT/SampleTest.py", line 33, in <module>
for value, obj in zip(pool.map(Sats.genSignal, GPS_Satellites), GPS_Satellites):
File "C:\Program Files\Python36\lib\multiprocessing\pool.py", line 266, in map
return self._map_async(func, iterable, mapstar, chunksize).get()
File "C:\Program Files\Python36\lib\multiprocessing\pool.py", line 644, in get
raise self._value
File "C:\Program Files\Python36\lib\multiprocessing\pool.py", line 424, in _handle_tasks
put(task)
File "C:\Program Files\Python36\lib\multiprocessing\connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
File "C:\Program Files\Python36\lib\multiprocessing\reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
TypeError: can't pickle ephem.EarthSatellite objects
The reason is something like this... when you try to pickle a function, it can attempt to pickle globals(), so whatever you have in your global namespace is also pickled (just in case your function has a reference to something in globals() -- yes, that's unexpected, but that's how it is). So, an easy fix is to isolate the function you want to pickle in another file -- in this case, put the multiprocessing stuff in one file and the other code in another file... so there's less in globals() for the pickler to struggle with. Another thing that might help is to use multiprocess instead of multiprocessing -- multiprocess uses the dill serializer instead of pickle, so you have a better chance of serializing objects that will be sent across the workers in the Pool.

Randint error in Python?

I'm writing up the code for the RSA algorithm as a project. With those who are familiar woth this encryption system,the function below calculates the value of phi(n). However when I run this, it comes up this error:
Traceback (most recent call last):
File "C:\Python27\RSA.py", line 127, in <module>
phi_n()
File "C:\Python27\RSA.py", line 30, in phi_n
prime_f = prime_list[random.randint(0,length)]
File "C:\Python27\lib\random.py", line 241, in randint
return self.randrange(a, b+1)
File "C:\Python27\lib\random.py", line 217, in randrange
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
ValueError: empty range for randrange() (0,0, 0)
I don't fully understand why this error is coming up. Here is my code for the phi_n function:
def phi_n():
global prime_list
length = len(prime_list) - 1
prime_f = prime_list[random.randint(0,length)]
prime_s = prime_list[random.randint(0,length)]
global pq
n = prime_f * prime_s
global phi_n
phi_n = (prime_f -1) * (prime_s -1)
return phi_n
Comment will be appreciated.
Thanks
The problem is prime_list is empty and therefore length will equal -1 resulting in the call random.randint(0, -1) which is invalid for obvious reasons.

Categories