Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const cols = 10;
- const rows = 10;
- const mines = 25;
- const mineChar = ".";
- let board = new Array(rows).fill(0).map(() => new Array(cols).fill(0));
- function printBoard() {
- for (let i = 0; i < rows; i++) {
- for (let j = 0; j < cols; j++) {
- process.stdout.write(board[i][j].toString().padEnd(4, ' '));
- }
- process.stdout.write('\n');
- }
- }
- require('assert')(mines <= cols * rows, 'too many mines');
- let mineCount = 0;
- while (mineCount < mines) {
- let y = Math.floor(Math.random() * rows);
- let x = Math.floor(Math.random() * cols);
- if (board[y][x] == mineChar) continue;
- board[y][x] = mineChar;
- mineCount++;
- }
- const steps = [
- [-1, -1], [-1, 0], [-1, 1],
- [0, -1], [0, 1],
- [1, -1], [1, 0], [1, 1]
- ];
- // printBoard();
- for (let i = 0; i < rows; i++) {
- for (let j = 0; j < cols; j++) {
- if (board[i][j] == mineChar) continue;
- let cnt = 0;
- for (let k = 0; k < steps.length; k++) {
- let y = i + steps[k][0];
- let x = j + steps[k][1];
- if (x < 0 || x >= cols || y < 0 || y >= rows) continue;
- if (board[y][x] == mineChar) cnt++;
- }
- board[i][j] = cnt;
- // console.log("i = " + i + "; j = " + j);
- // printBoard();
- }
- }
- printBoard();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement