Circle packing #1

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

#packing

Log in to post a comment.

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

Canvas.setpenopacity(1);

const canvas_size = 95;
const hide_radius = 5; // min=0, max=20, step=1
const max_radius = 10; // min=0.01, max=20, step=0.01
const min_radius = .3; // min=0.01, max=2, step=0.01
const shape = 1; // min=0, max=1, step=1 (Box, Circle)
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;
        const possible = circles.every(c => {
            const dx = c[0] - x;
            const dy = c[1] - y;
            const dr = c[2] + r;
            
            return dx**2 + dy**2 > dr**2 && (!shape || x**2 + y**2 < (canvas_size-r)**2);
        });
        if (possible && (!shape || x*x+y*y < (canvas_size-r)*(canvas_size-r))) {
            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.jump(x,y-r);
    turtle.circle(r);
}

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