以下函数定义矩形、它们的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_的颜色改为在黑色和白色之间进行选择,矩形也会在黑色和白色之间闪烁。这是怎么回事?在
对于您发布的代码,您可以得到的最佳答案是,每次循环迭代时都会重新评估rand_color,从而导致分配不同的颜色。在
我的建议是只在初始化对象时调用random函数,并且该对象应该是一个类:
如果要重用矩形,将它们存储为可以调用其属性的类是一种更好的结构。一个矩形类应该知道它自己的宽度/高度/颜色,而其他东西则会跟踪它的位置。在
如果需要更多帮助,请发布更多代码。在
正如我在评论中所说,每次调用函数时都会生成不同的颜色,而闪烁问题可能是由于调用太频繁而导致的。您可以通过将
rand_color
设为全局变量并在函数调用之前在函数外部定义它的值来解决这个问题。在然而,我认为John Rodger's answer中使用类的思想是一个好主意,但它的实现方式不同,并试图利用面向对象编程而不是重新发明整个轮子。下面是我的意思的一个可运行的例子。每次运行它时,它都会生成一个随机着色的矩形来表示一个
Thing
对象,并且这个颜色不会随着显示器的更新而改变或闪烁。在相关问题 更多 >
编程相关推荐