Snowflake

The Koch snowflake grows level by level: every line turns into four shorter ones with a spike. Teaches recursion you can see.

Open in Tokbit Level: Expert. Free in the browser, nothing to install, no account needed.

Run the example in Tokbit and step through it: before each step say what will happen and check it in the Variables panel. Then change it your way.

Flowchart

Flowchart of the Snowflake example

Python program

The same program as Python code. In Tokbit you see it when you switch from Diagram to Python above the flowchart.

"""The Koch snowflake level by level. Teaches recursion: a function calls itself and you see what it does."""
# Tokbit screen functions, not in plain Python:
from tokbit import (
    cls, color, background, border, sleep, line, BLACK, WHITE, LIGHT_BLUE,
)

def curve(x1: float, y1: float, x2: float, y2: float, depth: int):
    """A Koch curve from (x1, y1) to (x2, y2): a straight line, or four smaller curves with a spike in the middle."""
    if depth == 0:
        # Depth 0: a straight line, the recursion stops here.
        line(round(x1), round(y1), round(x2), round(y2))
    else:
        # A third of the line along x and y.
        dx: float = (x2 - x1) / 3
        dy: float = (y2 - y1) / 3
        # The spike: out from the middle of the line, at right angles, by a third times 0.866 (sin 60°).
        px: float = x1 + 1.5 * dx + dy * 0.866
        py: float = y1 + 1.5 * dy - dx * 0.866
        # The function calls itself: four parts, each one level shallower.
        curve(x1, y1, x1 + dx, y1 + dy, depth - 1)
        curve(x1 + dx, y1 + dy, px, py, depth - 1)
        curve(px, py, x1 + 2 * dx, y1 + 2 * dy, depth - 1)
        curve(x1 + 2 * dx, y1 + 2 * dy, x2, y2, depth - 1)

background(BLACK)
border(BLACK)
# The snowflake level by level, 0 to 4: on each next level every line turns into four shorter ones with a spike.
for level in range(5):
    cls()
    color(WHITE)
    print("Level", level)
    color(LIGHT_BLUE)
    # The three sides of a triangle, each one a Koch curve.
    curve(160, 13, 235, 143, level)
    curve(235, 143, 85, 143, level)
    curve(85, 143, 160, 13, level)
    sleep(1000)

All examples