我正在做的作业问题如下:
"Draw two randomly placed radius 10 circles on the screen then draw radius 2 circles every twenty pixels from the center of one to the center of the other."
我随机生成两个半径为 10 的圆没有问题,但我不知道如何在它们之间绘制半径为 2 的圆。
我已经尝试在它们之间简单地画一条线,如果有办法沿着那条线画出我的点,我绝对可以做到。我查找了类似的问题,其中很多都提到了 Bresenham's line algorithm但我怀疑这是答案,因为它看起来非常先进。
这是我目前针对该问题的代码:
import pygame
from random import randint
linecolour = 0,0,0
bgcolour = 255, 255, 255
width = 600
height = 600
screen = pygame.display.set_mode((width, height))
running = 1
x = []
y = []
for i in range (2):
x.append(randint(0,600))
y.append(randint(0,600))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT: # or other types of events
done = True
screen.fill(bgcolour)
for i,j in zip(x,y):
pygame.draw.circle(screen,linecolour,(i,j),10)
pygame.draw.circle(screen,linecolour,(i,j),2)
pygame.display.flip()
最佳答案
计算从一个点到另一个点的方向向量:
dir = x[1]-x[0], y[1]-y[0]
计算Euclidean distance点之间。请注意,您必须导入数学
:
dist = math.sqrt(dir[0]*dir[0] + dir[1]*dir[1])
或者如@MadPhysicist的回答中指出的那样
dist = math.hypot(*dir)
要绘制的点数是int(dist)//20
。循环计算直线上的点:
for i in range(int(dist) // 20):
px = int(x[0] + dir[0] * i*20/dist)
py = int(y[0] + dir[1] * i*20/dist)
绘制小点的代码可能如下所示:
done = False
while not done:
# [...]
dir = x[1]-x[0], y[1]-y[0]
dist = math.hypot(*dir)
for i in range(1, int(dist) // 20 + 1):
pt = int(x[0] + dir[0] * i*20/dist), int(y[0] + dir[1] *i*20/dist)
pygame.draw.circle(screen, linecolour, pt, 2)
关于python - 如何在 Pygame 中的两个随机生成的点之间每 20 个像素绘制一个圆圈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56245338/