用python随机画多个圆_Python 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()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值