用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()
總結
以上是生活随笔為你收集整理的用python随机画多个圆_Python Pygame随机绘制不重叠的圆圈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么说甜点是缓解压力的良药?
- 下一篇: python语法错误概述_Python