Skip to content

Instantly share code, notes, and snippets.

@typable
Last active Apr 28, 2021
Embed
What would you like to do?
Terminal 2D Noise
function base(n) {
return Math.pow(2, n) + 1;
}
function find(x, n) {
let b = 2;
let i = 0;
while(x > b) {
b = base(i + 1);
i++;
}
return base(i - n);
}
function make(x, n) {
for(let i = 0; i < n; i++) {
x += x - 1;
}
return x;
}
function noise(length, depth) {
const array = Array.from({ length }).map(() => Math.random());
for(let i = 0; i < depth; i++) {
expand(array);
}
return array;
}
function noise2D(length, depth) {
let array = Array.from({ length }).map(() => Array.from({ length }).map(() => Math.random()));
for(let i = 0; i < depth; i++) {
for(let i = 0; i < array.length; i++) {
expand(array[i]);
}
expand2D(array);
}
return array;
}
function expand(array) {
for(let i = 1; i < array.length; i += 2) {
const min = Math.min(array[i], array[i - 1]);
const max = Math.max(array[i], array[i - 1]);
array.splice(i, 0, Math.random() * (max - min) + min);
}
}
function expand2D(array) {
for(let i = 1; i < array.length; i += 2) {
const row = [];
for(let j = 0; j < array[i].length; j++) {
const min = Math.min(array[i][j], array[i - 1][j]);
const max = Math.max(array[i][j], array[i - 1][j]);
row.push(Math.random() * (max - min) + min);
}
array.splice(i, 0, row);
}
}
const [x = 16, n = 2] = Deno.args;
const k = find(x, n);
console.log(`${x}x${x} : ${n}`);
const a = noise2D(k, n).slice(0, x).map(n => n.slice(0, x));
let s = '';
for(let i = 0; i < a.length; i++) {
for(let j = 0; j < a[i].length; j++) {
s += `\u001b[48;5;${240 + Math.floor(15 * a[i][j])}m `;
}
s += '\u001b[0m\n';
}
s += '\u001b[0m';
console.log(s);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment