Kodewick
Start learning →

Python Turtle Snowflake

A Koch snowflake: every edge folds out a little point, and every point folds out smaller ones. Change the level and watch it grow finer.

Python Turtle Snowflake
The full code (60 lines)
import turtle
import random

screen = turtle.Screen()
screen.bgcolor("#0f2a4a")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)


def koch(length, level):
    # one edge: cut in three, the middle third folded out into a point
    if level == 0:
        t.forward(length)
        return
    for turn in [60, -120, 60, 0]:
        koch(length / 3, level - 1)
        t.left(turn)


def crystal(x, y, size):
    # a small snowflake: six arms, each with a pair of twigs
    t.penup()
    t.goto(x, y)
    t.pendown()
    for arm in range(6):
        t.forward(size * 0.6)
        t.left(45)
        t.forward(size * 0.3)
        t.backward(size * 0.3)
        t.right(90)
        t.forward(size * 0.3)
        t.backward(size * 0.3)
        t.left(45)
        t.forward(size * 0.4)
        t.backward(size)
        t.right(60)


# small snowflakes around
t.pencolor("white")
t.pensize(2)
for i in range(16):
    crystal(random.randint(-280, 280), random.randint(-260, 260), random.randint(10, 22))

# the big snowflake in the middle: three Koch curves
size = 300
level = 4
t.penup()
t.goto(-size / 2, size * 0.29)
t.setheading(0)
t.pendown()
t.pencolor("white")
t.fillcolor("#cfe8ff")
t.pensize(1)
t.begin_fill()
for side in range(3):
    koch(size, level)
    t.right(120)
t.end_fill()

How it is drawn

The Koch curve: cut an edge in three and fold the middle third out into the point of a triangle. koch(length, level) treats each third as an edge and folds it the same way — recursion.

for turn in [60, -120, 60, 0] are the turns between the four pieces of an edge: left 60, right 120, left 60.

Three Koch curves with a right turn of 120 after each make the snowflake; begin_fill() and end_fill() around them fill it light blue.

Each level multiplies the pieces by four: level 4 is 3 × 256 = 768 lines, level 5 is 3,072.

Questions

What is level 0?

At level 0 nothing is folded: the three edges are a plain triangle. Count up from 0 and watch it change.

Why does a high level take so long?

Every level multiplies the lines by four: level 7 is over 40,000 lines. This page lets you go up to 5.

Try another