Guest User

Untitled

a guest
Jan 20th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. const mineCell = () => ({ isMine: true });
  2. const numberCell = numAdjacentMines => ({ isMine: false, numAdjacentMines });
  3.  
  4. const genMtx = (w, h) => {
  5. return Array(h)
  6. .fill(null)
  7. .map(() => Array(w).fill(null));
  8. };
  9.  
  10. function getRandomInt(min, max) {
  11. return Math.floor(Math.random() * (max - min + 1)) + min;
  12. }
  13.  
  14. const serializeBoard = mtx =>
  15. mtx
  16. .map(row =>
  17. row
  18. .map(cell => {
  19. if (cell.isMine) {
  20. return '*';
  21. } else {
  22. return cell.numAdjacentMines;
  23. }
  24. })
  25. .join(''),
  26. )
  27. .join('\n');
  28.  
  29. const genBoard = (w, h, numMines) => {
  30. const board = genMtx(w, h);
  31.  
  32. // 1. populate mines
  33. for (let index = 0; index < numMines; index++) {
  34. do {
  35. const x = getRandomInt(0, w - 1);
  36. const y = getRandomInt(0, h - 1);
  37. if (!board[y][x]) {
  38. board[y][x] = mineCell();
  39. break;
  40. }
  41. } while (true);
  42. }
  43.  
  44. // 2. calculate num adj
  45. for (let rowIdx = 0; rowIdx < board.length; rowIdx++) {
  46. const row = board[rowIdx];
  47.  
  48. for (let colIdx = 0; colIdx < row.length; colIdx++) {
  49. let numAdjacentMines = 0;
  50. const cell = board[rowIdx][colIdx];
  51. if (cell && cell.isMine) continue;
  52.  
  53. // check adj cells
  54. for (let y = rowIdx - 1; y <= rowIdx + 1; y++) {
  55. for (let x = colIdx - 1; x <= colIdx + 1; x++) {
  56. if (board[y]) {
  57. const row = board[y];
  58. if (row[x]) {
  59. if (row[x].isMine) numAdjacentMines++;
  60. }
  61. }
  62. }
  63. }
  64.  
  65. board[rowIdx][colIdx] = numberCell(numAdjacentMines);
  66. }
  67. }
  68.  
  69. return serializeBoard(board);
  70. };
  71.  
  72. const b = genBoard(4, 4, 5);
  73. console.log(b);
Add Comment
Please, Sign In to add comment