Created
August 20, 2021 01:35
지뢰찾기
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 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