Circle packing

A probably pretty naive way of circle packing. Circles with a radius > hide_radius are not drawn.

#packing

Created by reinder on 2018/11/16
407
0

Log in to post a comment.

// Circle packing. Created by Reinder Nijhoff 2018
// @reindernijhoff
//
// https://turtletoy.net/turtle/f9915c1d89
//

Canvas.setpenopacity(1);

const pack_in_circle = Math.random() >= .5;
const canvas_size = 95;
const hide_radius = 5;
const max_radius = 10;
const min_radius = .3;
const radius_decr = .99;
const max_tries = 5000;

let radius = max_radius;

const circles = [];

const turtle = new Turtle();

function add_circle(t, r) {
    let coord_found = false;
    let tries = 0;
    
    while (!coord_found && tries < max_tries) {
        tries ++;
        const x = Math.random() * (canvas_size-r)*2 -canvas_size + r;
        const y = Math.random() * (canvas_size-r)*2 -canvas_size + r;
        let possible = true;
        for (let i=0; i<circles.length; i++) {
            const dx = circles[i][0] - x;
            const dy = circles[i][1] - y;
            const dr = circles[i][2] + r;
            
            if ( dx*dx + dy*dy < dr * dr || 
                 (pack_in_circle && 
                  x*x+y*y > (canvas_size-r)*(canvas_size-r))) {
                possible = false;
                break;
            }
        }
        if (possible) {
            coord_found = true;
            if (r < hide_radius) {
                draw_circle(x,y,t, r);
            }
            circles.push([x,y,r]);
            return true;
        }
    }
    return false;
}

function draw_circle(x,y,t, r) {
    turtle.penup();
    turtle.goto(x,y-r);
    turtle.pendown();
    turtle.circle(r);
}

function walk(i) {
    if (!add_circle(turtle, radius)) {
        radius *= radius_decr;
    }
    return radius >= min_radius;
}