Python随机颜色闪烁在物体上

2024-09-29 19:36:41 发布

您现在位置:Python中文网/ 问答频道 /正文

以下函数定义矩形、它们的x/y位置、宽度和高度以及颜色。我希望每次都随机选择颜色。在

def things(thingx, thingy, thingw, thingh, color):
    rand_color = (random.randrange(0,255),random.randrange(0,255),random.randrange(0,255))
    pygame.draw.rect(gameDisplay, rand_color, [thingx, thingy, thingw, thingh])

当前代码导致程序在每种不同的颜色中闪烁。即使我将rand_的颜色改为在黑色和白色之间进行选择,矩形也会在黑色和白色之间闪烁。这是怎么回事?在


Tags: 函数宽度定义颜色randomcolor黑色矩形
2条回答

对于您发布的代码,您可以得到的最佳答案是,每次循环迭代时都会重新评估rand_color,从而导致分配不同的颜色。在

我的建议是只在初始化对象时调用random函数,并且该对象应该是一个类:

class thing(width, height):
    def __init__(width, height):
        self.width = width
        self.height = height
        self.color = <random color logic>
    def getHeight(): return self.height
    def getWidth(): return self.width
    def getColor(): return self.color

如果要重用矩形,将它们存储为可以调用其属性的类是一种更好的结构。一个矩形类应该知道它自己的宽度/高度/颜色,而其他东西则会跟踪它的位置。在

如果需要更多帮助,请发布更多代码。在

正如我在评论中所说,每次调用函数时都会生成不同的颜色,而闪烁问题可能是由于调用太频繁而导致的。您可以通过将rand_color设为全局变量并在函数调用之前在函数外部定义它的值来解决这个问题。在

然而,我认为John Rodger's answer中使用类的思想是一个好主意,但它的实现方式不同,并试图利用面向对象编程而不是重新发明整个轮子。下面是我的意思的一个可运行的例子。每次运行它时,它都会生成一个随机着色的矩形来表示一个Thing对象,并且这个颜色不会随着显示器的更新而改变或闪烁。在

import pygame, sys
from pygame.locals import *
import random

FPS = 30  # frames per second
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

class Thing(pygame.Rect):
    def __init__(self, *args, **kwargs):
        super(Thing, self).__init__(*args, **kwargs)  # init Rect base class
        # define additional attributes
        self.color = tuple(random.randrange(0, 256) for _ in range(3))
        self.x_speed, self.y_speed = 5, 5  # how fast it moves

    def draw(self, surface, width=0):
        pygame.draw.rect(surface, self.color, self, width)

def main():
    pygame.init()
    fpsclock = pygame.time.Clock()
    pygame.key.set_repeat(250)  # enable keyboard repeat for held down keys
    gameDisplay = pygame.display.set_mode((500,400), 0,32)
    gameDisplay.fill(WHITE)

    thingx,thingy, thingw,thingh = 200,150, 100,50
    thing = Thing(thingx, thingy, thingw, thingh)  # create an instance

    while True:  # display update loop
        gameDisplay.fill(WHITE)

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_DOWN:
                    thing.y += thing.y_speed
                elif event.key == K_UP:
                    thing.y -= thing.y_speed
                elif event.key == K_RIGHT:
                    thing.x += thing.x_speed
                elif event.key == K_LEFT:
                    thing.x -= thing.x_speed

        thing.draw(gameDisplay)  # display at current position
        pygame.display.update()
        fpsclock.tick(FPS)

main()

相关问题 更多 >

    热门问题