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

标签 python random pygame

我对 python 很陌生,似乎缺少一些东西。
我想在 pygame 显示上随机绘制圆圈,但前提是圆圈不相互重叠。
我相信我必须找到所有圆心之间的距离,并且只有在距离大于圆半径 * 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()

关于Python Pygame随机绘制不重叠的圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46702987/

相关文章:

python - 在 Python 中创建游戏配置/选项 (config.cfg) 文件

python - PyGame 中的中文 unicode 字体

python - 如何通过第二个值将第二低的列表查找到嵌套列表中?

python - 在 Python 中随机化句子

python - 使用随机运算符将两个数字相加

python - 如何在 Python 中高效地生成具有随机斜率和截距的直线?

python - 生成随机 10 位数文件名并创建文件的代码

python - 在 PyGame 中从较小的图像构建背景图像

python - 如何通过PyGithub将分支 merge 到master

python - 为什么 `*args` 的值很奇怪?