Subdivision of space 1

Random binary subdivision of space

Log in to post a comment.

// You can find the Turtle API reference here: https://turtletoy.net/syntax
Canvas.setpenopacity(1);

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

class Branch {
    constructor(x0,y0,x1,y1) {
        this.x0 = x0;
        this.y0 = y0;
        this.x1 = x1;
        this.y1 = y1;
    }
}

const root = new Branch(-100,-100,100,100);

const tree = [];

tree.push(root);

function biasedSplit() {
    return 0.5+(Math.random()-Math.random())/2;
}

// split one branch and choose the split direction at random.
function splitBranchEitherWay(parent) {
    if( Math.random() > 0.5 ) {
        // split vertically
        split = (parent.y1-parent.y0) * biasedSplit() + parent.y0;
        c0 = new Branch(parent.x0,parent.y0,parent.x1,split);
        c1 = new Branch(parent.x0,split,parent.x1,parent.y1);
    } else {
        // split horizontally
        split = (parent.x1-parent.x0) * biasedSplit() + parent.x0;
        c0 = new Branch(parent.x0,parent.y0,split,parent.y1);
        c1 = new Branch(split,parent.y0,parent.x1,parent.y1);
    }
    parent.c0=c0;
    parent.c1=c1;
    tree.push(c0,c1);
}

// split the tree one time at a random branch that does not already have children.
function splitTreeRandomly() {
    index = 0;
    do {
        index = Math.floor(Math.random() * tree.length);
        // check for children
    } while(tree[index].c0!=null);
    
    splitBranchEitherWay(tree[index]);
}

splitTreeRandomly();
splitTreeRandomly();
splitTreeRandomly();
splitTreeRandomly();
splitTreeRandomly();


// The walk function will be called until it returns false.
function walk(i) {
    for(var i=0;i<tree.length;++i) {
        var b = tree[i];
        turtle.penup();
        turtle.goto(b.x0,b.y0);
        turtle.pendown();
        turtle.goto(b.x1,b.y0);
        turtle.goto(b.x1,b.y1);
        turtle.goto(b.x0,b.y1);
        turtle.goto(b.x0,b.y0);
        turtle.penup();
    }
    return false;
}