Skip to content

Instantly share code, notes, and snippets.

@PartyLich
Created January 27, 2020 17:44
Show Gist options
  • Save PartyLich/22a8ad989f5422de364bfd3306c55cc5 to your computer and use it in GitHub Desktop.
Save PartyLich/22a8ad989f5422de364bfd3306c55cc5 to your computer and use it in GitHub Desktop.
// Adapted from andai.tv/bonsai/
const pipe = (...fns) => (x) => fns.reduce((x, fn) => fn(x), x);
// const output = document.getElementById("output");
const ROWS = 30;
const COLS = 40;
const LIFE = 28;
const MAX_BRANCHES = 1024;
let branches = 0;
const rand = (min, max) => int(min + Math.random() * (Math.abs(min)+max));
const int = (float) => Math.round(float);
const makeCol = (len) => new Array(len).fill(' ');
function createGrid(rows = ROWS, cols = COLS) {
return new Array(rows)
.fill(cols)
.map(makeCol);
}
function grow(life = LIFE) {
return (grid) => {
const rows = grid.length;
if (!rows) throw new Error('Invalid grid dimensions');
const cols = grid[0].length;
const x = int(cols / 2); //+ rand(-1*cols/3, 2*cols / 3)
const y = rows - 3;
return branch(grid, x, y, life);
};
}
function getChar(dx, dy, life) {
switch (true) {
case (life === 0): return '&';
case (dy === 0): return '~';
case (dx === 0): return '|';
case (dx > 0): return '/';
case (dx < 0): return '\\';
default: return ' ';
}
}
function branch(grid, x, y, life, maxBranches = MAX_BRANCHES) {
branches++;
while (life > 0) {
const dy = (rand(0, 10) > 3)
? -1
: 0;
const dx = rand(-2, 2);
life--;
// recurse
if (branches < maxBranches) {
if (life % 13 == 0 || rand(0, 40) < 2 || life < 5) {
grid = branch(grid, x, y, life);
}
}
x += dx;
y += dy;
// console.log(x,y);
grid[y][x] = getChar(dx, dy, life);
}
return grid;
}
function print(grid) {
let str = grid.map((row) => row.join(''))
.join('\n');
// output.value = str
console.log(
str
);
}
const bonsai = pipe(
createGrid,
grow(),
print,
);
bonsai();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment