python - 如何在 Pygame 中的两个随机生成的点之间每 20 个像素绘制一个圆圈?

标签 python pygame

我正在做的作业问题如下:

"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/

相关文章:

python - 如何使角色成为图像 pygame

python - 在 python 3 中子类化文件对象(以扩展打开和关闭操作)

python - 在 Elasticsearch 中删除索引时出错

python - plumbum.commands.processes.ProcessExecutionError : for commands which return null

python - 如何将 python 和 pygame 放在闪存驱动器上?

python - 如何在 Pygame 中模糊曲面的边缘?

python - 为什么 pygame.midi 不能在 Macos 上运行,而 pygame.mixer 可以

python - 如何在Python中设置一个计时器来验证用户名?

python - 为什么这些图像 gridspec 子图的高度略有不同?

python - 在pygame中使背景横向移动