Skip to main content
 首页 » 编程设计

python之如何使对象在 Python 中不接触

2024年10月25日11Renyi-Fan

所以,我正在编写一个程序,该程序以随机​​颜色生成 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() 

任何帮助都会很棒!

谢谢!

请您参考如下方法:

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()