Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const mineCell = () => ({ isMine: true });
- const numberCell = numAdjacentMines => ({ isMine: false, numAdjacentMines });
- const genMtx = (w, h) => {
- return Array(h)
- .fill(null)
- .map(() => Array(w).fill(null));
- };
- function getRandomInt(min, max) {
- return Math.floor(Math.random() * (max - min + 1)) + min;
- }
- const serializeBoard = mtx =>
- mtx
- .map(row =>
- row
- .map(cell => {
- if (cell.isMine) {
- return '*';
- } else {
- return cell.numAdjacentMines;
- }
- })
- .join(''),
- )
- .join('\n');
- const genBoard = (w, h, numMines) => {
- const board = genMtx(w, h);
- // 1. populate mines
- for (let index = 0; index < numMines; index++) {
- do {
- const x = getRandomInt(0, w - 1);
- const y = getRandomInt(0, h - 1);
- if (!board[y][x]) {
- board[y][x] = mineCell();
- break;
- }
- } while (true);
- }
- // 2. calculate num adj
- for (let rowIdx = 0; rowIdx < board.length; rowIdx++) {
- const row = board[rowIdx];
- for (let colIdx = 0; colIdx < row.length; colIdx++) {
- let numAdjacentMines = 0;
- const cell = board[rowIdx][colIdx];
- if (cell && cell.isMine) continue;
- // check adj cells
- for (let y = rowIdx - 1; y <= rowIdx + 1; y++) {
- for (let x = colIdx - 1; x <= colIdx + 1; x++) {
- if (board[y]) {
- const row = board[y];
- if (row[x]) {
- if (row[x].isMine) numAdjacentMines++;
- }
- }
- }
- }
- board[rowIdx][colIdx] = numberCell(numAdjacentMines);
- }
- }
- return serializeBoard(board);
- };
- const b = genBoard(4, 4, 5);
- console.log(b);
Add Comment
Please, Sign In to add comment