Python Pygame randomly draw non overlapping circles

后端 未结 2 846
名媛妹妹
名媛妹妹 2021-01-22 18:04

Im very new to python and seem to be missing something.
I want to randomly draw circles on a pygame display but only if the circles don\'t overlap each other.
I believe

2条回答
  •  礼貌的吻别
    2021-01-22 18:26

    You did not check against all other circles. I added a variable shouldprint which gets set to false if any other circle is too close.

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

提交回复
热议问题