So I'm experimenting in pygame and wrote some code for a rectangle that slowly changes color
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.
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. 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]
color[0]
== 250, so gets changed to 254
color[0]
== 254, so stays the same, a
gets changed to -4
color[0]
== 254, so gets changed to 250
4
.... And I'm not sure -4 is a valid colour...
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. 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.
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
. 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.