Skip to content

Instantly share code, notes, and snippets.

@qsona
Created August 20, 2019 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qsona/70a0eb5bb26595a22baa0b2425f8f617 to your computer and use it in GitHub Desktop.
Save qsona/70a0eb5bb26595a22baa0b2425f8f617 to your computer and use it in GitHub Desktop.
minesweeper
const assert = require('assert');
const _ = require('lodash');
class Masu {
constructor(isMine, isOpened) {
this.isMine = isMine;
this.isOpened = isOpened;
}
}
const Board = _.chunk(_.shuffle(_.times(10, () => new Masu(true, false)).concat(_.times(71, () => new Masu(false, false)))), 9)
console.log(Board)
function display(board) {
console.log(board.map(b => b.map(t => t.isMine ? '*' : '-').join('')).join("\n"))
}
function countAdjacentMine(x, y, board) {
let count = 0;
for (let a = x-1; a <= x+1; a++)
for (let b = y-1; b <= y+1; b++)
if (board[a] && board[a][b] && board[a][b].isMine) count++;
return count;
}
function display2(board) {
console.log(
board.map((b, x) => (
b.map((t, y) => (
!t.isOpened ? '-' :
t.isMine ? '*' :
(countAdjacentMine(x, y, board) || 'o')
)).join('')
)).join("\n")
);
}
display(Board)
console.log('==============')
function open(x, y, board) {
const masu = board[x][y];
assert(!masu.isOpened)
masu.isOpened = true;
if (masu.isMine) {
console.log('MINE')
return false;
}
const count = countAdjacentMine(x, y, board);
if (count > 0) {
return true;
}
for (let a = x-1; a <= x+1; a++)
for (let b = y-1; b <= y+1; b++)
if (board[a] && board[a][b] && !board[a][b].isOpened) {
open(a, b, board);
}
return true;
}
open(0, 0, Board)
display2(Board)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment