[英]TypeError when changing colors in pygame
So I'm experimenting in pygame and wrote some code for a rectangle that slowly changes color 所以我在pygame中进行实验,并为逐渐改变颜色的矩形编写了一些代码
a = 4
b = 3
c = 2
#some irrelevant code later
if color[0]+a < 255:
color[0] += a
else:
a *= -1
if color[1]+b < 255:
color[1] += b
else:
b *= -1
if color[2]+c < 255:
color[2] += c
else:
c *= -1
a, b, and c as the speed of change for red, green, and, blue. a,b和c是红色,绿色和蓝色的变化速度。
The problem is that for some reason it will give me a TypeError: Invalid color argument after a few seconds of the program running, usually when the color is very blue. 问题是由于某种原因,它会在程序运行几秒钟后(通常是非常蓝色的情况下)给我一个TypeError:无效的color参数。 I don't see any reason an invalid color argument would appear.
我看不到任何会出现无效颜色参数的原因。
I would expect a ValueError
instead of a TypeError
, but it looks like what's happening is that if we take a = 4
and work with color[0]
我期望有一个
ValueError
而不是TypeError
,但是看起来发生的是如果我们取a = 4
并使用color[0]
color[0]
== 250, so gets changed to 254
color[0]
== 250,因此更改为254
color[0]
== 254, so stays the same, a
gets changed to -4
color[0]
== 254,因此保持不变,将a
更改为-4
color[0]
== 254, so gets changed to 250
color[0]
== 254,因此更改为250
4
.... 4
.... And I'm not sure -4 is a valid colour... 而且我不确定-4是不是有效的颜色...
maybe look at using 也许看看使用
>>> from itertools import izip, cycle
>>> a = range(0, 20, 4) + range(20, 0, -4)
>>> b = range(0, 20, 3) + range(20, 0, -3)
>>> c = range(0, 20, 2) + range(20, 0, -2)
>>> test = izip(cycle(a), cycle(b), cycle(c))
>>> for i in range(30):
print next(test)
(0, 0, 0)
(4, 3, 2)
(8, 6, 4)
(12, 9, 6)
(16, 12, 8)
(20, 15, 10)
(16, 18, 12)
(12, 20, 14)
(8, 17, 16)
(4, 14, 18)
(0, 11, 20)
(4, 8, 18)
(8, 5, 16)
(12, 2, 14)
(16, 0, 12)
(20, 3, 10)
(16, 6, 8)
(12, 9, 6)
(8, 12, 4)
(4, 15, 2)
(0, 18, 0)
(4, 20, 2)
(8, 17, 4)
(12, 14, 6)
(16, 11, 8)
(20, 8, 10)
(16, 5, 12)
(12, 2, 14)
(8, 0, 16)
(4, 3, 18)
You are eventually getting to -ve colours. 您最终将获得-ve颜色。 You reverse the direction if the colour gets too high, but not if the colour gets too low.
如果颜色太高,则反转方向,但如果颜色太低,则不反转方向。 Check to make sure it is also greater than 0.
检查以确保它也大于0。
if 0 < color[0]+a < 255:
color[0] += a
else:
a *= -1
Since you are getting a TypeError, somewhere else in your code (maybe far away from where the TypeError
actually occurs!), you are redefining color
. 由于您收到TypeError,因此在代码的其他地方(可能与
TypeError
实际发生的地方相距很远!),您正在重新定义color
。 For example, something like 例如,类似
color = 'blue'
There is a Color class 有一个颜色课
from pygame.locals import Color
def color_rand(c):
try:
c.r += random.randint(0,10)
except ValueError:
c.r = 0
bg = Color(0,0,0)
bg = color_rand(bg)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.