Python Pygame randomly draw non overlapping circles

后端 未结 2 847
名媛妹妹
名媛妹妹 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:44

    The for loop has been changed to a while loop. It will keep trying to generate circles until the target number is reached. A circle is first generated. Then, it checks if it intersects with any existing circle using the formula from this answer.

    It iterates through every existing circle (store in the list circles) and performs the check using the formula. any() returns True if the formula evaluates to True for any iteration. If it's True, it means it found an intersection. Thus, it continues to the next iteration to try again with a new circle.

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

提交回复
热议问题