Warm tip: This article is reproduced from stackoverflow.com, please click
pygame python

How to draw a set amount of circles at random positions on a screen in pygame?

发布于 2020-09-10 08:37:55

I'm trying to draw x amount of circles in random positions on a screen, which have no intersections. My expected results: x amount of circles are drawn to random positions on the screen. like in this beautiful diagram I drew in paint Like this beautifl paint pciture

Actual results: I get one circle being drawn at a new random position every time the program loops.

Code I have tried so far:

import pygame
import random

def draw_food(screen,color,x,y,radius):
    '''This function draws/creates the food sprite, The screen variable tells the food what screen to be drawn to. the color variable sets the color the radius variable sets how large of a circle the food will be.'''
    pygame.draw.circle(screen,green,(x,y),radius)

pygame.init()
width = 800
height = 600
screen = pygame.display.set_mode((width,height))
white = (255, 255, 255)
green = (0, 255, 0)
running = True

# main program loop
while running:
    # Did the user click the window close button?
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Fill the background with white
    screen.fill((white))

    # Draw the food
    draw_food(screen,green,random.randint(0,width),random.randint(0,height),20)

    # Flip the display
    pygame.display.flip()

I did look at other similar questions but all the ones I could find were for a different Programing language or to different to be useful. I am also a beginner at python and pygame.

Questioner
Nova 4026
Viewed
16
hippozhipos 2020-06-08 07:43

Its only drawing one circle because thats exactly what your code says. To have multiple circles at random positions you can can generate and store the random position values outside of your loop so it dosent change every frame. Something like this.

sizes = []
noOfCircles = 20
for i in range(noOfCircles):
    size.append([random.randint(0, screenWidth), random.randint(0, screenHeight))

Then in your main loop, you can draw the circle using for loop. Notice in your code, it only draws one circle because you dont use any kind of loop.

for i in range(20):
    pygame.draw.circle(screen,green,(sizes[i][0], sizes[i][1]),radius)

This approach works but i not really the best way to do it. The way its usually done is using classes. So make a class for circle like this.

class Circle:
    def __init__(self):
         #You can initialise the position to a random value
         self.pos = [random.randint(0, screenWidth), random.randint(0, screenHeight)]
         self.color = green
         self.radius = 10

    def draw(self):
         pygame.draw.circle(screen, self.color, (self.size[0], self.size[1]), self.radius)

The you can make a list that hold a bunch of cirlces.

circles = []
for i in range(20):
    circles.append(Circle())

Then in your main loop, you can draw the circles.

while True: for circle in circles: circle.draw()

Here is the complete example code.

import pygame, random, math

win = pygame.display
display = win.set_mode((1200, 600))

class Circle:
    def __init__(self):
         #You can initialise the size to a random value
         self.pos = [random.randint(0, 1200), random.randint(0, 600)]
         self.color = (0,255, 0)
         self.radius = 10

    def draw(self):
         pygame.draw.circle(display, self.color, (self.pos[0], self.pos[1]), self.radius)


circles = []

for i in range(20):
    circles.append(Circle())

def checkIntersection(c1, c2):
    dx = c1.pos[0] - c2.pos[0]
    dy = c1.pos[1] - c2.pos[1]
    d = math.hypot(dx, dy)
    if d < c1.radius + c2.radius:
        return True
    return False


for i in range(19):
    while checkIntersection(circles[i], circles[i + 1]):
        circles[i].pos = random.randint(0, 1200), random.randint(0, 600)

while True:
    display.fill((255, 255, 255))
    pygame.event.get()
    for circle in circles:
        circle.draw()
    win.flip()

Edit: So, to check to intersection, you can just see if any of the circles collide and if they do just generate a new set of random numbers. This insures that thers never intersection. I updated the example code with this implemented.