Gosper's fractals

Gosper's fractals of different orders drawn using a L-system

Log in to post a comment.

// Global code will be evaluated once.
const turtle = new Turtle()

const order = 6 // min=4 max=10 step=1
const radius = 80
const maxDepth = 8 // min=0 max=10 step=1
const intermediary = 0; // min=0 max=1 step=1 (No, Yes)

const theta = Math.PI*(order-2)/order
const [cos, sin] = [Math.cos(theta), Math.sin(theta)]
const ratio = 1 / Math.sqrt(5-4*cos)
const angle = Math.atan(sin/(2-cos))*180/Math.PI
const alpha = 360/order
const size = radius*2*Math.sin(alpha*Math.PI/360)

const segment = (depth, max) => {
    const length = size * ratio**depth
    if (depth == max) turtle.forward(length)
    else {
        turtle.left(angle)
        segment(depth+1, max)
        turtle.right(alpha)
        segment(depth+1, max)
        turtle.left(alpha)
        segment(depth+1, max)
        turtle.right(angle)
    }
}
// The walk function will be called until it returns false.
function walk(i) {
    if (intermediary || i == maxDepth) {
        turtle.penup()
        turtle.forward(radius)
        turtle.right(90+alpha/2)
        turtle.pendown()
    
        for (let s = 0; s < order; s++) {
            segment(0, i)
            turtle.right(alpha)
        }
    
        turtle.penup()
        turtle.left(90+alpha/2)
        turtle.backward(radius)
        turtle.pendown()
    }

    return i < maxDepth
}