【问题标题】:How do give every circle a random color in pygame?如何在pygame中给每个圆圈一个随机颜色?
【发布时间】:2020-09-17 00:46:47
【问题描述】:

在这个程序中,我想要一个更大的可移动圆圈和许多彩色的小圆圈。然而,当我运行程序时,所有的小圆圈都是相同的颜色,我无法弄清楚如何随机给它们每个不同的颜色。我该如何解决这个问题?

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

【问题讨论】:

  • 每个答案旁边都有一个✔勾号,如果它适合您,您可以接受答案并通过✅检查勾号来批准它,提前致谢

标签: python pygame draw


【解决方案1】:

在主循环中,您使用的是永远不会改变的i。使用 enumerate 在遍历位置集合时返回索引。

试试这个代码:

for i,locate in enumerate(locations):
    pg.draw.circle(screen, (small_color[i]), locate, 5)

【讨论】:

    【解决方案2】:

    确保在第一行导入 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 上做了一个 repo 并做了一些更改, 圆点是彩色的,新圆点的颜色是随机的,每次吃掉一个圆点球就会变大。

    https://github.com/peymanmajidi/Ball-And-Dots-Game__Pygame

    【讨论】:

      猜你喜欢
      • 2012-11-21
      • 2019-04-13
      • 1970-01-01
      • 2013-12-19
      • 2013-10-24
      • 1970-01-01
      • 2012-11-13
      • 2014-04-09
      • 1970-01-01
      相关资源
      最近更新 更多