I want to make a python script that clicks every point inside a 200px x 200px square. I'm using a library that's called pyautogui and I tried to do it, but it didn't work as fine as I would like. Mouse only clicks in the middle of the screen. How can I fix that?
Here is a photo of the square and then there is the code that I actually have.
200px x 200px square
Code:
import pyautogui
import time
time.sleep(5)
exit_key = KeyCode(char='e')
pyautogui.FAILSAFE = False
x=700
y=400
for i in range(500):
if x <= 900 and y <= 400:
x= x + 1
pyautogui.click(x,y)
time.sleep(0.001)
else:
x = 700
y = 460
if x <= 900 and y <= 460:
x= x + 140
pyautogui.click(x,y)
time.sleep(0.001)
else:
x = 700
y = 520
if x <= 900 and y <= 520:
x= x + 1
pyautogui.click(x,y)
time.sleep(0.001)
else:
x = 700
y = 580
if x <= 900 and y <= 580:
x= x + 1
pyautogui.click(x,y)
time.sleep(0.001)
else:
x = 700
y = 600
if x <= 900 and y <=600:
x= x + 1
pyautogui.click(x,y)
time.sleep(0.001)
else:
print("finish")
PD: I know that my code is very weird, I put the if and the else conditions because I want to be sure that the program clicks by a horizontal mode, no in digonal, I'm new programming jeje.
A much simpler approach might be what you need. Create arrays of your x and y values, then a pair of for loops will build every point in your 200x200 rectangle and you can click at that point.
xs = range(700,700+200)
ys = range(400,400+200)
for x in xs:
for y in ys:
pyautogui.click(x,y)
Related
I was trying to recreate Conway's Game of Life in python using Tkinter, but I got stuck while checking for the neighbors. I can't seem to find the solution to my problem.
If a cell is alive it is stored using numpy, 0 for the dead cells and 1 for the living cells. The function "get_neighbours" checks if the cell is not in a corner or next to a side and it returns the ammount of neighbours each cell has. The function "recalculate" basically makes a new board with 0s and 1s which then replaces the original board and redraws everything. But when compared to an already existing game the progress is different.
import tkinter as tk
import numpy as np
win = tk.Tk()
WIDTH = 500
HEIGHT = 500
vs = 10
absvs = vs
cells = np.zeros((WIDTH//vs, HEIGHT//vs), dtype=int)
cells_new = np.zeros((WIDTH//vs, HEIGHT//vs), dtype=int)
def get_neighbours(x, y):
total = 0
if x > 0:
total += cells[x - 1, y]
if x > 0 and y > 0:
total += cells[x - 1, y - 1]
if y > 0:
total += cells[x, y - 1]
if x > 0 and y < (HEIGHT // absvs - 1):
total += cells[x - 1, y + 1]
if x < (WIDTH // absvs - 1):
total += cells[x + 1, y]
if x < (WIDTH // absvs - 1) and y < (HEIGHT // absvs - 1):
total += cells[x + 1, y + 1]
if y < (HEIGHT // absvs - 1):
total += cells[x, y + 1]
if x > 0 and y < (HEIGHT // absvs - 1):
total += cells[x - 1, y + 1]
return total
def recalculate():
global cells, cells_new
for y in range(HEIGHT//absvs):
for x in range(WIDTH//absvs):
temp = get_neighbours(x, y)
if (temp == 2 and cells[x, y] == 1) or (temp == 3 and cells[x, y] == 1):
cells_new[x, y] = 1
elif temp == 3 and cells[x, y] == 0:
cells_new[x, y] = 1
elif temp < 2 or temp > 3:
cells_new[x, y] = 0
cells = cells_new
canvas.delete("all")
create_stage()
redraw_cell()
def slider_changer(e):
global vs
canvas.delete("all")
vs = w.get()
create_stage()
redraw_cell()
def create_cell(e):
global cells
tx = e.x // vs
ty = e.y // vs
x = tx * vs
y = ty * vs
canvas.create_rectangle(x, y, x + vs, y + vs, fill="gray")
cells[tx, ty] = 1
print(get_neighbours(tx, ty))
def redraw_cell():
for x in range(WIDTH//vs):
for y in range(HEIGHT//vs):
if cells[x, y] == 1:
canvas.create_rectangle(x * vs, y * vs, x * vs + vs, y * vs + vs, fill="gray")
def create_stage():
for x in range(WIDTH//vs):
canvas.create_line(x*vs, 0, x*vs, HEIGHT)
for y in range(HEIGHT//vs):
canvas.create_line(0, y*vs, WIDTH, y*vs)
canvas = tk.Canvas(width = WIDTH, height = HEIGHT, bg = "white")
canvas.pack()
w = tk.Scale(win, from_=10, to=50, orient="horizontal", command = slider_changer, length = 500)
w.pack()
w2 = tk.Button(win, text = "PRESS ME!!!", command = recalculate)
w2.pack()
create_stage()
canvas.bind("<Button-1>", create_cell)
win.mainloop()
There are these issues in your code:
In get_neighbours the last if block is the same as the fourth if block, and so there is a neighbor that is counted twice and another neighbor that isn't counted at all (the one at x + 1 and y - 1). So replace this:
if x > 0 and y < (HEIGHT // absvs - 1):
total += cells[x - 1, y + 1]
with:
if x < (WIDTH // absvs - 1) and y > 0:
total += cells[x + 1, y - 1]
In recalculate the assignment to cells at the end is making you lose one of the two arrays. Now both cells and new_cells reference the very same array1. This means the next iteration will not be calculated correctly. Instead, you should copy the content of cells_new into cells. So replace:
cells = cells_new
with:
cells = cells_new.copy()
In recalculate the if...elif..elif construct (inside the double loop) does not deal with the case where temp == 2 and cells[x, y] == 1 and so cells_new[x, y] might not be reset to 0 when it should. In fact, the last part of this construct should not have a condition; it should be a catch-all for all states that the previous checks did not deal with. So replace:
elif temp < 2 or temp > 3:
cells_new[x, y] = 0
with:
else:
cells_new[x, y] = 0
1 It is not helping that several websites, including https://www.geeksforgeeks.org/how-to-copy-numpy-array-into-another-array/ and https://www.askpython.com/python-modules/numpy/numpy-copy, wrongly assert that an assignment of one numpy array to another makes a copy. That is not true.
The loop is not running at all.
I'm just new to python and I have no idea what I did wrong.
x = float(input("Enter a number: "))
y = x * 0.5
while True:
y = 0.5 * (y + (x/y))
y_square = y * y
if -0.001 < y_square < 0.001:
break
print("Square root:",y_square)
Your loop does run, but it never stops.
Two issues:
if -0.001 < y_square < 0.001: surely you don't expect the square to be that small? It needs to be close to x, not close to zero. So change that to:
if -0.001 < y_square - x < 0.001:
The output should not be about y_square. You are not interested in the square, since that is what the user provided. You want to output the root, which is y:
print("Square root:", y)
In a game I'm writing with Pygame, I have a 2D point (x,y) in a box from (0,0) to (1,1) (perfect square with side length 1).
I want to calculate the euclidean distance from the point to the box boundary in a direction alpha, where alpha is an azimuth direction measured in radians counter-clockwise, starting from alpha=0 as the x-axis direction.
I wrote a python code that calculates this distance, but I'm not sure it's the most efficient/cleanest way:
import numpy as np
def get_distance_to_boundary(x, y, angle):
cos_angle, sin_angle = np.cos(angle), np.sin(angle)
if cos_angle == 0:
return y if sin_angle < 0 else 1 - y
if sin_angle == 0:
return x if cos_angle < 0 else 1 - x
x_target = 1 if cos_angle > 0 else 0
y_target = y + (x_target - x) * np.tan(angle)
if y_target > 1:
return np.fabs((1 - y) / sin_angle)
if y_target < 0:
return np.fabs(y / sin_angle)
return np.sqrt((x_target - x) ** 2 + (y_target - y) ** 2)
Any idea for a better approach?
Illustration:
This method is a little more efficient/cleaner because you don't need tan, fabs, sqrt or **2:
def distance(x,y,angle):
cos_angle, sin_angle = np.cos(angle), np.sin(angle)
if cos_angle == 0:
return y if sin_angle < 0 else 1 - y
if sin_angle == 0:
return x if cos_angle < 0 else 1 - x
distance_EW = (1-x)/cos_angle if cos_angle>0 else -x/cos_angle
distance_NS = (1-y)/sin_angle if sin_angle>0 else -y/sin_angle
return min(distance_EW, distance_NS)
I define distance_EW as the distance in the case where the target is on the East wall (if cos_angle>0) or on the West wall (if cos_angle<0). Similarly, define distance_NS for the North or South wall.
...
WARNING: My distance function will sometimes produce different results than your function because of rounding errors!! This is especially problematic when your starting point is at the border of the box and angle is close to a multiple of π/2.
I would suggest you set some sort of tolerance like if abs(sin_angle) < 1e-12:, instead of if sin_angle == 0:. That way, sin_angle = np.sin(np.pi) will be accepted in the if condition, even though it is not exactly equal to 0 (because np.sin(np.pi) is 1.2e-16 with python).
I have created a random walk scenario where it takes one step in a random direction for a specific number of times. The one thing that I have run in to is that sometimes it will go off of the graphics window that I have set up and I can no longer see where it is at.
Here is the code:
from random import *
from graphics import *
from math import *
def walker():
win = GraphWin('Random Walk', 800, 800)
win.setCoords(-50, -50, 50, 50)
center = Point(0, 0)
x = center.getX()
y = center.getY()
while True:
try:
steps = int(input('How many steps do you want to take? (Positive integer only) '))
if steps > 0:
break
else:
print('Please enter a positive number')
except ValueError:
print('ERROR... Try again')
for i in range(steps):
angle = random() * 2 * pi
newX = x + cos(angle)
newY = y + sin(angle)
newpoint = Point(newX, newY).draw(win)
Line(Point(x, y), newpoint).draw(win)
x = newX
y = newY
walker()
My question is, Is there a way that I can set parameters on the graphics window so that the walker can not go outside the window? And if it tries to, it would just turn around and try another direction?
Try defining upper and lower bounds for x and y. Then use a while loop that keeps trying random points until the next one is in bounds.
from random import *
from graphics import *
from math import *
def walker():
win = GraphWin('Random Walk', 800, 800)
win.setCoords(-50, -50, 50, 50)
center = Point(0, 0)
x = center.getX()
y = center.getY()
while True:
try:
steps = int(input('How many steps do you want to take? (Positive integer only) '))
if steps > 0:
break
else:
print('Please enter a positive number')
except ValueError:
print('ERROR... Try again')
# set upper and lower bounds for next point
upper_X_bound = 50.0
lower_X_bound = -50.0
upper_Y_bound = 50.0
lower_Y_bound = -50.0
for i in range(steps):
point_drawn = 0 # initialize point not drawn yet
while point_drawn == 0: # do until point is drawn
drawpoint = 1 # assume in bounds
angle = random() * 2 * pi
newX = x + cos(angle)
newY = y + sin(angle)
if newX > upper_X_bound or newX < lower_X_bound:
drawpoint = 0 # do not draw, x out of bounds
if newY > upper_Y_bound or newY < lower_Y_bound:
drawpoint = 0 # do not draw, y out of bounds
if drawpoint == 1: # only draw points that are in bounds
newpoint = Point(newX, newY).draw(win)
Line(Point(x, y), newpoint).draw(win)
x = newX
y = newY
point_drawn = 1 # set this to exit while loop
walker()
I am a beginner with python and I wrote this code to make bouncing ball with python turtle it works but have some errors like the ball disappearing
import turtle
turtle.shape("circle")
xdir = 1
x = 1
y = 1
ydir = 1
while True:
x = x + 3 * xdir
y = y + 3 * ydir
turtle.goto(x , y)
if x >= turtle.window_width():
xdir = -1
if x <= -turtle.window_width():
xdir = 1
if y >= turtle.window_height():
ydir = -1
if y <= -turtle.window_height():
ydir = 1
turtle.penup()
turtle.mainloop()
Although your approach to the problem works (my rework):
import turtle
turtle.shape("circle")
turtle.penup()
x, y = 0, 0
xdir, ydir = 3, 3
xlimit, ylimit = turtle.window_width() / 2, turtle.window_height() / 2
while True:
x = x + xdir
y = y + ydir
if not -xlimit < x < xlimit:
xdir = -xdir
if not -ylimit < y < ylimit:
ydir = -ydir
turtle.goto(x, y)
turtle.mainloop()
In the long run, it's the wrong approach to take. In this case, due to the infinite loop while True, the mainloop() method is never called so no other turtle event handlers are active. For example, if we wanted to use exitonclick() instead of mainloop(), it wouldn't work. Instead consider:
import turtle
turtle.shape("circle")
turtle.penup()
x, y = 0, 0
xdir, ydir = 3, 3
xlimit, ylimit = turtle.window_width() / 2, turtle.window_height() / 2
def move():
global x, y, xdir, ydir
x = x + xdir
y = y + ydir
if not -xlimit < x < xlimit:
xdir = -xdir
if not -ylimit < y < ylimit:
ydir = -ydir
turtle.goto(x, y)
turtle.ontimer(move, 5)
turtle.ontimer(move, 5)
turtle.exitonclick()
Here we've turned control back over to the mainloop and the motion is on an event timer. Other turtle events can execute so exitonclick() works. Just something to think about going forward before you program yourself, and your turtle, into a corner.
You need window_width()/2 and window_height()/2 to keep inside window.
ie.
if x >= turtle.window_width()/2:
xdir = -1
if x <= -turtle.window_width()/2:
xdir = 1
if y >= turtle.window_height()/2:
ydir = -1
if y <= -turtle.window_height()/2:
ydir = 1
You should put
turtle.penup()
Before the while loop to make your code better and a little bit faster. It is almost a bug!
You can bounce your wall, if you want to bounce it from upper wall, the screen width is 800 and length is 600
from turtle import turtle
turtle=Turtle()
def move(self)://This will move your ball in diagonal direction
x_dir=self.xcor()+self.x
y_dir=self.ycor()+self.y
self.goto(x_dir,y_dir)
def bounce(self)://This will bounce back
self.y *=-1
turtle.bounce()
This code is running because I did it with inheritance. You need to create a class then inherit all the properties and then create two methods there and then call those functions in the main class.