Python Pygame随机绘制非重叠的圆圈



我对python很陌生,似乎缺少一些东西。
我想在pygame显示器上随机绘制圆圈,但前提是圆圈不相互重叠。
我相信我必须找到所有圆心之间的距离,并且只有在距离大于circle radius * 2时才绘制它。

尝试了很多不同的东西,但没有成功,我总是得到相同的结果 - 画的圆重叠。

#!/usr/bin/env python
import pygame, random, math
red = (255, 0, 0)
width = 800
height = 600
circle_num = 10
tick = 2
speed = 5
pygame.init()
screen = pygame.display.set_mode((width, height))
class circle():
    def __init__(self):
        self.x = random.randint(0,width)
        self.y = random.randint(0,height)
        self.r = 100
    def new(self):
        pygame.draw.circle(screen, red, (self.x,self.y), self.r, tick)
c = []
for i in range(circle_num):
    c.append('c'+str(i))
    c[i] = circle()
    for j in range(len(c)):
        dist = int(math.hypot(c[i].x - c[j].x, c[i].y - c[j].y))
        if dist > int(c[i].r*2 + c[j].r*2):
            c[j].new()
            pygame.display.update()
        else:
            continue
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

您没有检查所有其他圆圈。我添加了一个变量shouldprint如果任何其他圆圈太近,该变量将设置为 false。

import pygame, random, math
red = (255, 0, 0)
width = 800
height = 600
circle_num = 20
tick = 2
speed = 5
pygame.init()
screen = pygame.display.set_mode((width, height))
class circle():
    def __init__(self):
        self.x = random.randint(0,width)
        self.y = random.randint(0,height)
        self.r = 100
    def new(self):
        pygame.draw.circle(screen, red, (self.x,self.y), self.r, tick)
c = []
for i in range(circle_num):
    c.append('c'+str(i))
    c[i] = circle()
    shouldprint = True
    for j in range(len(c)):
        if i != j:
            dist = int(math.hypot(c[i].x - c[j].x, c[i].y - c[j].y))
            if dist < int(c[i].r*2):
                shouldprint = False
    if shouldprint:
        c[i].new()
        pygame.display.update()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

for循环已更改为while循环。它将继续尝试生成圆圈,直到达到目标数字。首先生成一个圆。然后,它使用此答案中的公式检查它是否与任何现有圆相交。

它遍历每个现有的圆(存储在列表circles中),并使用公式执行检查。 如果公式的计算结果为任何迭代的Trueany() 将返回True。如果它True,则表示它找到了一个交叉点。因此,它继续到下一次迭代以再次尝试使用新圆。

circles = []
while len(circles) < circle_num:
    new = circle()
    if any(pow(c.r - new.r, 2) <=
           pow(c.x - new.x, 2) + pow(c.y - new.y, 2) <=
           pow(c.r + new.r, 2)
       for c in circles):
        continue
    circles.append(new)
    new.new()
    pygame.display.update()

最新更新