简体   繁体   中英

How would I go about making it so that each new generation of triangles in this koch snowflake is a different color? (Python + Turtle)

So I have this program that generates a hexagonal koch snowflake using these two main functions:

def mvmt(length):

if length <= 10:
    voldemort.forward(length)
else:
    mvmt(length/3)
    voldemort.right(60)
    mvmt(length/3)
    voldemort.left(120)
    mvmt(length/3)
    voldemort.right(60)
    mvmt(length/3)


def whole(length = 300):
    voldemort.hideturtle()
    voldemort.penup()
    voldemort.goto(-300,-255)
    voldemort.pendown()
    voldemort.begin_fill()
    mvmt(length)
    voldemort.left(60)
    mvmt(length)
    voldemort.left(60)
    mvmt(length)
    voldemort.left(60)
    mvmt(length)
    voldemort.left(60)
    mvmt(length)
    voldemort.left(60)
    mvmt(length)
    voldemort.end_fill() 

How do I make it so that each new set of triangles added through the iterative process is a new color?

I'd rather not use meticulous processes of changing the fill color, then running "voldemort.beginfill()" and "voldemort.endfill()". Help is highly appreciated. NOTE This is written in python using the Turtle Module.

One way to do it is to clone the turtle inside mvmt() , so you have an independent one that you can fill without interfering with the filling of the outer one.

To make that work recursively, you have to pass the current turtle as a parameter to mvmt() .

That's what I changed your code to:

#!/usr/bin/env python

from __future__ import division

import colorsys
import turtle

def mvmt(original, length):
    if length >= 10:
        fraction = length / 3
        h, s, v = colorsys.rgb_to_hsv(*original.fillcolor())

        clone = original.clone()
        clone.fillcolor(colorsys.hsv_to_rgb(h + 1/6, s, v))
        clone.begin_fill()
        mvmt(clone, fraction)
        clone.right(60)
        mvmt(clone, fraction)
        clone.left(120)
        mvmt(clone, fraction)
        clone.right(60)
        mvmt(clone, fraction)
        clone.end_fill()

    original.forward(length)

def whole(length = 300):
    voldemort = turtle.Turtle()
    voldemort.speed(0)
    voldemort.hideturtle()
    voldemort.penup()
    voldemort.goto(-200,-255)
    voldemort.pendown()

    voldemort.fillcolor((1.0, 0.5, 0.5))
    voldemort.begin_fill()
    mvmt(voldemort, length)
    voldemort.left(60)
    mvmt(voldemort, length)
    voldemort.left(60)
    mvmt(voldemort, length)
    voldemort.left(60)
    mvmt(voldemort, length)
    voldemort.left(60)
    mvmt(voldemort, length)
    voldemort.left(60)
    mvmt(voldemort, length)
    voldemort.end_fill()

turtle.delay(0)
turtle.speed(0)

whole()
turtle.exitonclick()

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