Skip to content

Instantly share code, notes, and snippets.

@jeongsd
Created August 20, 2021 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeongsd/e2bf9d1871135601d2674c438e23fedb to your computer and use it in GitHub Desktop.
Save jeongsd/e2bf9d1871135601d2674c438e23fedb to your computer and use it in GitHub Desktop.
지뢰찾기
const UNREVEALED_MINE = "M";
const UNREVEALED_EMPTY = "E";
const REVEALED_BLANK = "B";
const REVEALED_MINE = "X";
const adjacentIndexes = [
[-1, -1],
[-1, 0],
[-1, 1],
[1, 1],
[1, 0],
[1, -1],
[0, -1],
[0, 1],
];
const getAdjacentMineCount = (board, [row, column]) => {
let count = 0;
for (const [plusRow, plusColumn] of adjacentIndexes) {
const adjacentRow = row + plusRow
const adjacentColumn = column + plusColumn
if (
board?.[adjacentRow]?.[adjacentColumn] === UNREVEALED_MINE
) {
count++;
}
}
return count;
};
const resolveEmpty = (board, [row, column]) => {
const adjacentMineCount = getAdjacentMineCount(board, [row, column])
if (adjacentMineCount === 0) {
board[row][column] = REVEALED_BLANK
for (const [plusRow, plusColumn] of adjacentIndexes) {
const adjacentRow = row + plusRow
const adjacentColumn = column + plusColumn
if (
board?.[adjacentRow]?.[adjacentColumn] === UNREVEALED_EMPTY
) {
resolveEmpty(board, [adjacentRow, adjacentColumn])
}
}
} else {
board[row][column] = String(adjacentMineCount)
}
return board
};
const updateBoard = function (board, click) {
const newBoard = [...board.map(row => [...row])];
const [row, column] = click;
const cellType = newBoard[row][column];
if (cellType === REVEALED_BLANK) {
return newBoard;
} else if (cellType === REVEALED_MINE) {
return newBoard;
} else if (Number.isInteger(Number(cellType))) {
return newBoard;
} else if (cellType === UNREVEALED_MINE) {
newBoard[row][column] = REVEALED_MINE;
} else if (cellType === UNREVEALED_EMPTY) {
resolveEmpty(newBoard, [row, column])
}
return newBoard;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment