我在尝试产生在python中不重叠的圆时遇到一些困难。我已经尝试了pylab和matplotlib,但无济于事。我觉得这与我的逻辑/算法有关,我需要一些帮助来找出问题所在。 (PS请原谅我格式化错误的问题。这是我第一次使用StackOverFlow。)预先感谢。
Python Pygame randomly draw non overlapping circles
我已经看到了此链接,但看不到出什么问题了!
from pylab import *
from scipy.spatial import distance
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
fig, ax = plt.subplots()
list1 = [[0,0,0]]
def generatecircle():
stuff1 = 0
stuff2 = 20
while stuff1 <stuff2:
x = random.random()
y = random.random()
r = 0.05
shouldprint = True
for i in list1:
print("****")
print(x)
print(i)
print(list1)
if notincircle(x,y,r , i[0],i[1],i[2]):
shouldprint = True
else:
shouldprint = False
if shouldprint:
list1.append([x,y,r])
circle = Circle((x,y), radius = r, facecolor = 'red')
ax.add_patch(circle)
stuff1 += 1
try:
list1.remove([0,0,0])
except:
pass
def notincircle(x1,y1,r1,x2,y2,r2):
dist = math.sqrt( ((x2-x1)**2) + ((y2-y1)**2) )
if dist >= (r1 + r2):
return True
else:
return False
generatecircle()
plt.show()
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))
list1 = [[0,0,0]]
def generatecircle():
stuff1 = 0
stuff2 = 20
shouldprint = True
while stuff1 <stuff2:
x = random.randint(0,width)
y = random.randint(0,height)
r = 50
for i in list1:
print("****")
print(x)
print(i)
print(list1)
if notincircle(x,y,r , i[0],i[1],i[2]):
shouldprint = True
else:
shouldprint = False
if shouldprint:
print("Print!")
list1.append([x,y,r])
#circle = Circle((x,y), radius = r, facecolor = 'red')
pygame.draw.circle(screen, red, (x,y), r, tick)
pygame.display.update()
stuff1 += 1
try:
list1.remove([0,0,0])
except:
pass
def notincircle(x1,y1,r1,x2,y2,r2):
dist = math.sqrt( ((x2-x1)**2) + ((y2-y1)**2) )
if dist >= (r1 + r2):
return True
else:
return False
generatecircle()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
圆圈仍然重叠!
答案 0 :(得分:0)
问题出在您的代码shouldprint
中的变量。如果它找到一个重叠的圆,则无论最后一次测试的圆是什么,它都应该为False。
for i in list1:
print("****")
print(x)
print(i)
print(list1)
# Should print will now be false if even 1 circle is found
if not notincircle(x,y,r , i[0],i[1],i[2]):
shouldprint = False
在测试单个圆之前,您还需要使shouldprint
从True开始,因此您希望在while循环中将其重置。
# shouldprint = True # This should be deleted
while stuff1 < stuff2:
x = random.randint(0,width)
y = random.randint(0,height)
r = 50
shouldprint = True # Moved should print here
最后,您可以只返回布尔结果的值。您无需说“如果为true,则返回true”。
if dist >= (r1 + r2):
return True
else:
return False
可以转换为
return dist >= (r1 + r2)