简体   繁体   中英

python turtle graphics iterating through color index throwing an error

I've just started with pythons Turtle graphics module, and I'm running into an issue not with Turtle itself I don't think, but my algorithm styling. I'm using the window.colormode(255) which is awesome and working great when I iterate from red to blue in my program, incrementing the blue variable and decrementing the red variable once every loop.

I'm running into a problem with my filter that should reverse the order of the color incrementor/decrementor (i want to go from blue back to red once r = 0 and b = 255):

Here's the code to draw:

counter = 1
firstlength = 1
secondlength = 1
thirdlength = 1
fourthlength = 1
fifthlength = 1
colorList = [255,0,0] # r g b
f = 0 # index for colorlist
for i in listOfTurtles:
    i = turtle.Turtle()
    i.pencolor(colorList[0], colorList[1], colorList[2])
    i.speed(0) # no turn animations
    i.left(counter)
    i.forward(firstlength)
    i.left(15)
    i.forward(secondlength)
    i.left(15)
    i.forward(thirdlength)
    i.left(15)
    i.forward(fourthlength)
    i.left(15)
    i.forward(fifthlength)
    counter += 1
    firstlength += .1
    secondlength += .11
    thirdlength += .12
    fourthlength += .13
    fifthlength += .14

Here's the problem with iterating through the pen color (using an answer below):

blueUp = True
    if blueUp == True:
        colorList[0] -= 1
        colorList[2] += 1
        if colorList[0] <= 1:
            blueUp = False
    else:
        colorList[0] += 1
        colorList[2] -= 1
        if colorList[2] <= 0:
            blueUp = True

however, this filter I've set up isn't flipping the color incrementor/decrementor when it needs to; thus resulting in a "bad color sequence error: (-1, 0, 256)

So I know its incrementing my blue 1 digit too high, and my red one too low on the first pass and then erroring out, but I'm unsure how to fix it. I've played with the > values and made them higher (to catch around 5 or 250) but I'm not getting results.

I'm totally open to a completely different way to write this, as I'm sure I've thought up the worst possible way to solve this issue.

For starters, you should probably change this:

if blueUp == False:
    if colorsList[2] > 0:

to this:

if blueUp == False:
    if colorList[2] > 1:

I'm an idiot. My bool variable was local to my outer for statement, the one iterating through my i's. every loop it would reset the value of blueUp and force the index down again by 1. Resolved the issue by moving my bool outside my outer for loop.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM