如何在 pygame 中给每个圆圈随机颜色?
How do give every circle a random color in pygame?
在这个程序中,我想要一个更大的可移动圆圈和许多五颜六色的小圆圈。但是,当我 运行 程序时,所有较小的圆圈都是相同的颜色,我无法弄清楚如何随机给它们每个不同的颜色。我该如何解决这个问题?
import pygame as pg
import random as rd
pg.init()
screen = pg.display.set_mode((800, 600))
p_1_x = 200
p_1_y = 200
p_1_change_x = 0
def p_1(x, y):
player_1 = pg.draw.circle(screen, (2, 2, 0), (x, y), 15)
locations = []
small_color = []
for i in range(50):
red = rd.randint(0, 220)
blue = rd.randint(0, 220)
green = rd.randint(0, 220)
x = rd.randint(100, 700)
y = rd.randint(100, 500)
locations.append((x, y))
small_color.append((red, blue, green))
while True:
screen.fill((255, 255, 255))
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
if event.type == pg.KEYDOWN:
if event.key == pg.K_RIGHT:
p_1_change_x = 1
if event.key == pg.K_LEFT:
p_1_change_x = -1
if event.type == pg.KEYUP:
if event.key == pg.K_RIGHT or pg.K_LEFT:
p_1_change_x = 0
p_1_x += p_1_change_x
p_1(p_1_x, p_1_y)
for locate in locations:
pg.draw.circle(screen, (small_color[i]), locate, 5)
pg.display.update()
在主循环中,您使用的是 i
,它永远不会改变。在遍历位置集合时使用 enumerate 到 return 索引。
试试这个代码:
for i,locate in enumerate(locations):
pg.draw.circle(screen, (small_color[i]), locate, 5)
确保在第一行导入 random
库:
import random as rd
这是一个生成随机颜色的简单函数:
def random_color():
r = rd.randint(0, 255)
g = rd.randint(0, 255)
b = rd.randint(0, 255)
return (r, g, b)
因此您可以在需要时调用它:
color = random_color()
draw.circle(screen, color, (x, y), SIZE)
Github 回购
我在 GitHub 中做了一个回购并做了一些修改,
圆点是彩色的,新圆点的颜色是随机的,球每吃一个圆点就会变大。
在这个程序中,我想要一个更大的可移动圆圈和许多五颜六色的小圆圈。但是,当我 运行 程序时,所有较小的圆圈都是相同的颜色,我无法弄清楚如何随机给它们每个不同的颜色。我该如何解决这个问题?
import pygame as pg
import random as rd
pg.init()
screen = pg.display.set_mode((800, 600))
p_1_x = 200
p_1_y = 200
p_1_change_x = 0
def p_1(x, y):
player_1 = pg.draw.circle(screen, (2, 2, 0), (x, y), 15)
locations = []
small_color = []
for i in range(50):
red = rd.randint(0, 220)
blue = rd.randint(0, 220)
green = rd.randint(0, 220)
x = rd.randint(100, 700)
y = rd.randint(100, 500)
locations.append((x, y))
small_color.append((red, blue, green))
while True:
screen.fill((255, 255, 255))
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
if event.type == pg.KEYDOWN:
if event.key == pg.K_RIGHT:
p_1_change_x = 1
if event.key == pg.K_LEFT:
p_1_change_x = -1
if event.type == pg.KEYUP:
if event.key == pg.K_RIGHT or pg.K_LEFT:
p_1_change_x = 0
p_1_x += p_1_change_x
p_1(p_1_x, p_1_y)
for locate in locations:
pg.draw.circle(screen, (small_color[i]), locate, 5)
pg.display.update()
在主循环中,您使用的是 i
,它永远不会改变。在遍历位置集合时使用 enumerate 到 return 索引。
试试这个代码:
for i,locate in enumerate(locations):
pg.draw.circle(screen, (small_color[i]), locate, 5)
确保在第一行导入 random
库:
import random as rd
这是一个生成随机颜色的简单函数:
def random_color():
r = rd.randint(0, 255)
g = rd.randint(0, 255)
b = rd.randint(0, 255)
return (r, g, b)
因此您可以在需要时调用它:
color = random_color()
draw.circle(screen, color, (x, y), SIZE)
Github 回购
我在 GitHub 中做了一个回购并做了一些修改, 圆点是彩色的,新圆点的颜色是随机的,球每吃一个圆点就会变大。