Last active
January 9, 2020 19:59
-
-
Save friendlyanon/ff2264534747370f0de7acf482b469dd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const map = { | |
"-1": "💥", | |
"0": "🟦", | |
}; | |
const inRange = (number, max) => 0 <= number && number < max; | |
const neighbors = [ | |
[-1, -1], [-1, 0], [-1, 1], | |
[0, -1], [ 0, 1], | |
[1, -1], [ 1, 0], [ 1, 1], | |
]; | |
function incrementNeighbors(field, y, x) { | |
const { length: height, 0: { length: width } } = field; | |
for (let [j, i] of neighbors) { | |
j += y; | |
i += x; | |
if (inRange(j, height) && inRange(i, width)) { | |
const row = field[j]; | |
if (row[i] >= 0) { | |
++row[i]; | |
} | |
} | |
} | |
} | |
function stringify(row) { | |
let lastSeen = -1; | |
let result = ""; | |
for (const number of row) { | |
const cell = number > 0 ? | |
`${String.fromCharCode(48 + number)}\ufe0f\u20e3` : | |
map[number]; | |
switch ((lastSeen === 0) << 1 | (number === 0)) { | |
case 0b00: | |
result += `||${cell}||`; | |
break; | |
case 0b01: | |
result += `||${cell}`; | |
break; | |
case 0b10: | |
result += `||||${cell}||`; | |
break; | |
case 0b11: | |
result += cell; | |
break; | |
} | |
lastSeen = number; | |
} | |
return lastSeen === 0 ? `${result}||` : result; | |
} | |
function generate(width = 10, height = 10, difficulty = 0.5) { | |
const field = Array.from( | |
{ length: height }, | |
() => Array(width).fill(0), | |
); | |
const cutoff = difficulty ** 2.5; | |
for (let y = 0; y < height; ++y) { | |
for (let x = 0; x < width; ++x) { | |
if (Math.random() < cutoff) { | |
field[y][x] = -1; | |
incrementNeighbors(field, y, x); | |
} | |
} | |
} | |
return field.map(stringify).join("\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment