JSFiddle - React, Tailwind, and code Playground

by mjheick

JavaScript

function makeMinesweeperBoard(rows = 5, cols = 5, mines = 5) {
	var board = [];
  /* Make a blank board with 0s */
  for (let r = 0; r < rows; r++) {
  	let l = new Array();
  	for (let c= 0 ; c < cols; c++) {
    	l.push('0');
    }
    board.push(l);
  }
  /* Fill board with mines, aka Xs */
  while (mines > 0) {
  	let x = Math.floor(Math.random() * cols);
    let y = Math.floor(Math.random() * rows);
    if (board[x][y] == 'X') { continue; }
    board[x][y] = 'X';
    mines--;
  }
  /* Put the numbers where they need to be */
  for (let r = 0; r < rows; r++) {
  	for (let c = 0; c < cols; c++) {
    	if (board[r][c] == 'X') { continue; }
    	let totalMines = 0;
      for (let y = -1; y <= 1; y++) {
      	for (let x = -1; x <= 1; x++) {
        	if ((r + x) < 0) { console.log('1'); continue; }
          if ((c + y) < 0) { console.log('2'); continue; }
          if ((r + x) >= rows) { console.log('3'); continue; }
          if ((c + y) >= cols) { console.log('4'); continue; }
        	if (board[r + x][c + y] == "X") {
          	totalMines++;
          }
        }
      }
      board[r][c] = totalMines.toString();
    }
  }
  return board;
}

console.log(makeMinesweeperBoard());