Advertisement
kraxor

minesweeper

Nov 17th, 2019
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const cols = 10;
  2. const rows = 10;
  3. const mines = 25;
  4. const mineChar = ".";
  5.  
  6. let board = new Array(rows).fill(0).map(() => new Array(cols).fill(0));
  7.  
  8. function printBoard() {
  9.     for (let i = 0; i < rows; i++) {
  10.         for (let j = 0; j < cols; j++) {
  11.             process.stdout.write(board[i][j].toString().padEnd(4, ' '));
  12.         }
  13.         process.stdout.write('\n');
  14.     }
  15. }
  16.  
  17. require('assert')(mines <= cols * rows, 'too many mines');
  18. let mineCount = 0;
  19. while (mineCount < mines) {
  20.     let y = Math.floor(Math.random() * rows);
  21.     let x = Math.floor(Math.random() * cols);
  22.     if (board[y][x] == mineChar) continue;
  23.     board[y][x] = mineChar;
  24.     mineCount++;
  25. }
  26.  
  27. const steps = [
  28.     [-1, -1], [-1, 0], [-1, 1],
  29.     [0, -1], [0, 1],
  30.     [1, -1], [1, 0], [1, 1]
  31. ];
  32.  
  33. // printBoard();
  34. for (let i = 0; i < rows; i++) {
  35.     for (let j = 0; j < cols; j++) {
  36.         if (board[i][j] == mineChar) continue;
  37.         let cnt = 0;
  38.         for (let k = 0; k < steps.length; k++) {
  39.             let y = i + steps[k][0];
  40.             let x = j + steps[k][1];
  41.             if (x < 0 || x >= cols || y < 0 || y >= rows) continue;
  42.             if (board[y][x] == mineChar) cnt++;
  43.         }
  44.         board[i][j] = cnt;
  45.         // console.log("i = " + i + "; j = " + j);
  46.         // printBoard();
  47.     }
  48. }
  49.  
  50. printBoard();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement