Minsweeper API design (JavaScript)

by hekevintran

JavaScript

MINE = '*'


function range(n) {
	return Array.from(Array(n).keys());
}

function randomChoice(array) {
	return array[Math.floor(Math.random() * array.length)];
}

function generateBoard(width, height, numberOfMines) {
	let board = getBlankBoard(width, height);
	placeMines(width, height, board, numberOfMines);
	countMines(width, height, board);
	return board;
}

function getBlankBoard(width, height) {
	let ret = [];
	for (let i of range(height)) {
		let row = [];
		for (let j of range(width)) {
			row.push(0);
		}
		ret.push(row);
	}
	return ret;
}

// function placeMines(width, height, board, numberOfMines) {
// 	while (numberOfMines > 0) {
// 		let y = randomChoice(range(height));
// 		let x = randomChoice(range(width));
// 		if (board[y][x] != MINE) {
// 			board[y][x] = MINE;
// 			numberOfMines -= 1;
// 		}
// 	}
// }

function placeMines(width, height, board, numberOfMines) {
	while (numberOfMines > 0) {
		let y = randomChoice(range(height));
		let x = randomChoice(range(width));
		if (board[y][x] != MINE) {
			board[y][x] = MINE;
			numberOfMines -= 1;
		}
	}
}

function countMines(width, height, board) {
	let deltas = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [-1, 1], [1, -1], [1, 1]];
	for (let y of range(height)) {
		for (let x of range(width)) {
			if (board[y][x] != MINE) {
				let count = 0;
				for (let [dx, dy] of deltas) {
				    y2 = y + dy;
					x2 = x + dx;
					if ( (y2 < 0 || y2 > Math.max(...range(height))) || (x2 < 0 || x2 > Math.max(...range(width))) ) {
						continue;
					} else {
						if (board[y2][x2] === MINE) {
							count += 1;
						}
					}
				}
				board[y][x] = count;
			}
		}
	}
}

function printBoard(board) {
	for (let row of board) {
		console.log(row.join(''));
	}
}

printBoard(generateBoard(5, 5, 3))