Skip to content

Instantly share code, notes, and snippets.

@kchia
Last active January 14, 2016 00:09
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 kchia/4a6375122bc548853b0d to your computer and use it in GitHub Desktop.
Save kchia/4a6375122bc548853b0d to your computer and use it in GitHub Desktop.
Creates a minesweeper board that has the ability to randomly plant mines on cells
// sets up Board class
var Board = function(dimension, mines) {
this.board = [];
for(var i = 0; i < dimension; i++) {
var row = [];
for(var j = 0; j < dimension; j++) {
row.push(new Cell(false));
}
this.board.push(row);
}
console.log('Generated a board of dimensions ' + dimension + ' by ' + dimension);
this.plantMines(dimension,mines);
};
// retrieves board 2D array
Board.prototype.getBoard = function() {
return this.board;
};
// plants mines randomly on board
Board.prototype.plantMines = function(dimension,mines) {
var maxMines = dimension * dimension;
if( mines < maxMines ) {
var minesPlanted = 0;
while(minesPlanted < mines) {
var x = generateRandNumber(dimension),
y = generateRandNumber(dimension);
if(!this.board[x][y].hasMine) {
this.board[x][y].setMine(true);
minesPlanted++;
}
}
console.log('There are ' + this.countMines() + ' mines on your board!');
} else {
throw new Error('You have too many mines! The number of mines must be fewer than ' + maxMines + '.');
}
};
// checks the number of mines on your board instance
Board.prototype.countMines = function() {
var count = 0,
i,
j,
row,
cell;
for(i = 0; i < this.board.length; i++) {
row = this.board[i];
for(j = 0; j < row.length; j++) {
cell = row[j];
if(cell.hasMine){
count++;
}
}
}
return count;
};
// sets up Cell class, with only hasMine property
var Cell = function(val) {
this.hasMine = val;
};
Cell.prototype.setMine = function(val) {
if(typeof val === 'boolean') {
this.hasMine = val;
} else {
throw new Error('Expected a boolean input but received a ' + typeof val + ' input instead.' )
}
};
// for checking whether the cell has a mine
Cell.prototype.getMineValue = function() {
return this.hasMine;
};
// generates random number up to max
var generateRandNumber = function(max) {
return Math.floor(Math.random() * max);
};
// sets the dimension and number of mines to be placed on the board
var dimension = 10;
var mines = 10;
// instantiates a board
var board = new Board(dimension,mines);
console.log(board.getBoard());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment