2017-10-12 108 views
2

我對python很陌生,似乎缺少一些東西。
我想在pygame顯示屏上隨機繪製圓圈,但前提是圓圈彼此不重疊。
我相信我必須找到所有圓心之間的距離,並且只有在距離大於circle radius * 2時才能繪製它。Python Pygame隨機抽取非重疊圓

我已經嘗試了許多不同的事情,但都沒有成功,我總是得到相同的結果 - 畫圈重疊。

#!/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() 

回答

1

您沒有檢查所有其他的圈子。我添加了一個變量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

謝謝是的,我現在看到我錯過了什麼。 – SirAleXbox

1

for環已更改爲一個while循環。它將繼續嘗試生成圈子,直到達到目標號碼。首先生成一個圓。然後,它使用this答案檢查它是否與任何現有圓相交。

它遍歷每個現有的圓(存儲在列表circles中)並使用公式執行檢查。 any()返回True如果公式評估爲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() 
+0

謝謝。它的工作原理與我的完全不同。將研究它並從中學習 – SirAleXbox