Created
August 20, 2019 17:16
-
-
Save qsona/70a0eb5bb26595a22baa0b2425f8f617 to your computer and use it in GitHub Desktop.
minesweeper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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