所以,我正在制作一个程序,程序以随机颜色制作250个点并将它们打印在窗口上。但他们无法互相接触。
这是我的代码
from graphics import *
from random import *
import math
def main():
win = GraphWin("Dots", 1100, 650)
dots = []
points = []
for x in range(0,250):
drawCircle(win, dots, points)
checkOverLap(dots, points)
drawAllCircles(win, dots)
def drawCircle(win, array, points):
p1 = randint(15,1085)
p2 = randint(15,635)
dot = Circle(Point(p1, p2), 15)
r = lambda: randint(0,255)
dot.setFill('#%02X%02X%02X' % (r(),r(),r()))
array.append(dot)
points.append(Point(p1, p2))
def checkOverLap(array, points):
count = 0
for x in range(0, 250):
for y in range(0, 250):
if x != y:
if math.hypot(points[y].getX() - points[x].getX(), points[y].getY() - points[x].getY()) < 30:
dist = math.hypot(points[y].getX() - points[x].getX(), points[y].getY() - points[x].getY())
newCircle = Circle(Point(points[x].getX() + (abs(dist - 31)), points[x].getY() + (abs(dist - 31))), 15)
r = lambda: randint(0,255)
newCircle.setFill('#%02X%02X%02X' % (r(),r(),r()))
array[x] = newCircle
def drawAllCircles(win, array):
for x in range(0, 250):
array[x].draw(win)
main()
任何帮助都会很棒!
谢谢!
答案 0 :(得分:1)
我没有Windows电脑,所以我会给你最好的答案。
尝试选择圆圈坐标的随机数,然后循环绘制已绘制的圆圈,看看在这些坐标处绘制的圆圈是否会触及任何其他圆圈。使用while
循环,您可以继续选择随机坐标,直到它们不接触任何其他坐标:
circles = list_of_circles_drawn
radius = radius_of_circles;
x = random.randint(1, 1000)
y = random.randint(1, 1000)
while any([math.sqrt(math.pow(math.fabs(x-c.x), 2)+math.pow(math.fabs(y-c.y), 2)) < radius for c in circles]):
x = random.randint(1, 1000)
y = random.randint(1, 1000)
答案 1 :(得分:1)
from graphics import *
from random import *
import math
def main():
win = GraphWin("Dots", 1100, 650)
dots = []
for x in xrange(250):
#Create a random circle
circle = getdrawCircle(15, 635, 15, 1085, 15, 15)
#Repeat while overlap with other circles
while checkOverLap(circle, dots):
#Create a new random circle
circle = getdrawCircle(15, 635, 15, 1085, 15, 15)
#The new circle isn't overlap, then append to list dots
dots.append(circle)
drawAllCircles(win, dots)
def getdrawCircle(min_height, max_height, min_width, max_width, min_radius, max_radius):
x = randint(min_height, max_height)
y = randint(min_width, max_width)
dot = Circle(Point(y, x), randint(min_radius, max_radius))
r = lambda: randint(0,255)
dot.setFill('#%02X%02X%02X' % (r(),r(),r()))
return dot
#If circle overlap with circles in array then return True
def checkOverLap(circle, array):
for circle_cmp in array:
dist = math.hypot(circle.getCenter().getX() - circle_cmp.getCenter().getX(),
circle.getCenter().getY() - circle_cmp.getCenter().getY())
if dist < circle.getRadius() + circle_cmp.getRadius():
return True
return False
def drawAllCircles(win, array):
for x in range(0, 250):
array[x].draw(win)
main()