我正在研究一个函数,该函数接受距常规图形中心的像素长度和边数。 例如:
draw_figure(r=200, side_count=4) : It would draw quadrilateral
draw_figure(r=100, side_count=8) : It would draw an octagon
我试图列出所有距中心半径相同的坐标,获取一个随机坐标,并根据长度获取其余坐标,但是我无法弄清楚。
from time import sleep
import subprocess
import pyautogui
from math import cos, radians, sqrt
from random import choice
def draw_figure(side_count, r):
# Open mspaint and move the cursorto the center.
subprocess.Popen("mspaint", shell=True)
sleep(1)
x, y = pyautogui.size()
pyautogui.moveTo(x/2, y/2)
# Define cos of alpha value in center and side_len of figure
a = 360/side_count
cos_a = cos(radians(a))
side_len = round(sqrt(2*(r**2) - 2*r*cos_a), 3)
# Get every x/y pair on screen inside a set
all_points = set()
for x_cord in list(range(x)):
for y_cord in list(range(y)):
all_points.add((x_cord, y_cord))
# Create points list with all x/y tuples that all are at same
# distance from center by r count of pixels
points = []
for point in all_points:
try:
R = round(sqrt((point[0] - x/2)**2 + (point[1] -
y/2)**2), 3)
if R == r:
points.append(point)
except ValueError:
pass
# Pick a random coordinate and find x/y of side points
r_point = choice(points)
square_vectors = []
pyautogui.moveTo(r_point)
for point in points:
try:
test_len = round(sqrt((r_point[0] - point[0])**2 +
(r_point[1] - point[1])**2), 3)
if test_len == side_len:
vector = tuple([point[0] - r_point[0],
point[1] - r_point[1]])
square_vectors.append(vector)
except ValueError:
pass
for vector in square_vectors:
pyautogui.dragRel(vector)
return square_vectors
示例:
A________B O is center of square
| \ | OA = r
| O \ |
D|___ \_|C