我正在尝试在屏幕上没有交点的随机位置上绘制x个圆。 我的预期结果: x数量的圆被绘制到屏幕上的随机位置。就像这张美丽的图,我画了油漆
实际结果:每次程序循环时,我都会在一个新的随机位置绘制一个圆。
到目前为止我尝试过的代码:
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()
我确实也看过其他类似的问题,但我能找到的所有问题都是针对另一种编程语言或有用的。我也是python和pygame的初学者。
它只画了一个圆圈,因为那正是您的代码所说的。要在随机位置上有多个圆,您可以在循环外生成并存储随机位置值,这样它在每一帧中都会发生变化。这样的事情。
sizes = []
noOfCircles = 20
for i in range(noOfCircles):
size.append([random.randint(0, screenWidth), random.randint(0, screenHeight))
然后在主循环中,可以使用for循环绘制圆。请注意,在您的代码中,它仅画一个圆圈,因为您不使用任何循环。
for i in range(20):
pygame.draw.circle(screen,green,(sizes[i][0], sizes[i][1]),radius)
这种方法有效,但我并不是真正做到这一点的最佳方法。通常使用类的方法。因此,像这样为圆形课。
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)
您可以创建一个列表,其中包含一堆圈子。
circles = []
for i in range(20):
circles.append(Circle())
然后,在主循环中,您可以绘制圆圈。
而True:对于圈子中的圈子:circle.draw()
这是完整的示例代码。
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()
编辑:因此,要检查到相交,您可以仅查看是否有任何圆圈发生碰撞,以及它们是否确实生成了一组新的随机数。这确保了他们永远不会相交。我用实现的示例代码进行了更新。
该答案的作用是具有多个圆圈,但是OP在注释中指出,圆圈不应有交集。
更新了答案,使圆圈永不相交。
谢谢,这对我很有帮助,尽管我不完全了解它的工作原理。