Prime Directive

Chooses 3-5 prime factors, then at each iteration, turns right if `i` is not divisible by any of the factors, left otherwise. A completely symmetric draw of a pattern takes `4 × (the product of the chosen primes)` iterations.

Log in to post a comment.

Canvas.setpenopacity(-0.5);
const size = 0.75;
const steps = 4;
const extent = 100;
const start = [0, 0];
const primes = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61];

Turtle.prototype.checkBounds = function() {
    this.penup();
    const x = this.x();
    const y = this.y();
    if      (x > extent)  this.setx(-extent+(x-extent));
    else if (x < -extent) this.setx(extent-(-1*(x+extent)));
    if      (y > extent)  this.sety(-extent+(y-extent));
    else if (y < -extent) this.sety(extent-(-1*(y+extent)));
    this.pendown();
}

Turtle.prototype.decideDirection = function(i) {
    return this.factors.reduce((a, f) => a && i%f, true);
}

Turtle.prototype.chooseFactors = function(factors) {
    const n = 3+Math.floor(2*Math.random());
    this.factors = [];
    for (let i = 0; i < n; i++) {
        this.factors.push(factors.splice(Math.floor(Math.random()*factors.length), 1));
    }
}

const turtle = new Turtle();
turtle.penup();
turtle.goto(start[0], start[1]);
turtle.chooseFactors(primes);
turtle.end = turtle.factors.reduce((a, f) => a*f, 4);
turtle.pendown();

function walk(i) {
    turtle.circle(turtle.decideDirection(i) ? size : -size, 90, steps);
    turtle.checkBounds();
    return i < turtle.end;
}