Skip to content

Instantly share code, notes, and snippets.

@Double0negative
Last active September 1, 2020 02:50
Show Gist options
  • Save Double0negative/bec5ef949b301468d275522c54fd7bcd to your computer and use it in GitHub Desktop.
Save Double0negative/bec5ef949b301468d275522c54fd7bcd to your computer and use it in GitHub Desktop.
console.log(createBoard(10, 15).board);
function createBoard(size, mines) {
let container = {
status: undefined,
revealed: 0,
size,
mines,
board: new Array(size).fill({})
.map(i => new Array(size).fill({}).map(o => ({
cell: 0,
show: false
})))
}
while (mines > 0) {
let x = Math.floor(Math.random() * size)
let y = Math.floor(Math.random() * size)
if (container.board[x][y] == "-1")
continue
container.board[x][y].cell = "-1";
getNearby(container, x, y, (cell) => cell.cell != -1)
.forEach(pos => pos.cell.cell++)
mines--
}
return container;
}
function getNearby(container, x, y, filter) {
let nearBy = [];
for (let a = x - 1; a < x + 2; a++) {
for (let b = y - 1; b < y + 2; b++) {
if (container.board[a]) {
let cell = container.board[a][b]
if (cell && !(a == x && b == y) && filter(cell))
nearBy.push({ x: a, y: b, cell });
}
}
}
return nearBy;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment