JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
var grid = document.getElementById("grid");
var testMode = false; //Turn this variable to true to see where the mines are
var gameLevel = 1;
var colNumber = 10;
var rowNumber = 10;
generateGrid();
function generateGrid() {
//generate row*col grid
grid.innerHTML = "";
for (var i = 0; i < rowNumber; i++) {
row = grid.insertRow(i);
for (var j = 0; j < colNumber; j++) {
cell = row.insertCell(j);
cell.onclick = function() {
clickCell(this);
};
var mine = document.createAttribute("data-mine");
mine.value = "false";
cell.setAttributeNode(mine);
}
}
addMines();
}
function addMines() {
//Add mines randomly
for (var i = 0; i < gameLevel * 10; i++) {
var row = Math.floor(Math.random() * rowNumber);
var col = Math.floor(Math.random() * colNumber);
var cell = grid.rows[row].cells[col];
cell.setAttribute("data-mine", "true");
if (testMode) cell.innerHTML = "X";
}
}
function revealMines() {
//Highlight all mines in red
for (var i = 0; i < rowNumber; i++) {
for (var j = 0; j < colNumber; j++) {
var cell = grid.rows[i].cells[j];
if (cell.getAttribute("data-mine") == "true") cell.className = "mine";
}
}
}
function checkLevelCompletion() {
var levelComplete = true;
for (var i = 0; i < rowNumber; i++) {
for (var j = 0; j < colNumber; j++) {
if ((grid.rows[i].cells[j].getAttribute("data-mine") == "false") && (grid.rows[i].cells[j].innerHTML == "")) levelComplete = false;
}
}
if (levelComplete) {
alert("You Win!");
revealMines();
// you can add level up codes here after...
}
}
function clickCell(cell) {
//Check if the end-user clicked on a mine
if (cell.getAttribute("data-mine") == "true") {
revealMines();
alert("Game Over");
} else {
cell.className = "clicked";
//Count and display the number of adjacent mines
var mineCount = 0;
var cellRow = cell.parentNode.rowIndex;
var cellCol = cell.cellIndex;
//alert(cellRow + " " + cellCol);
for (var i = Math.max(cellRow - 1, 0); i <= Math.min(cellRow + 1, rowNumber - 1); i++) {
for (var j = Math.max(cellCol - 1, 0); j <= Math.min(cellCol + 1, colNumber - 1); j++) {
if (grid.rows[i].cells[j].getAttribute("data-mine") == "true") mineCount++;
}
}
cell.innerHTML = mineCount;
if (mineCount == 0) {
//Reveal all adjacent cells as they do not have a mine
for (var i = Math.max(cellRow - 1, 0); i <= Math.min(cellRow + 1, rowNumber - 1); i++) {
for (var j = Math.max(cellCol - 1, 0); j <= Math.min(cellCol + 1, colNumber - 1); j++) {
//Recursive Call
if (grid.rows[i].cells[j].innerHTML == "") clickCell(grid.rows[i].cells[j]);
}
}
}
checkLevelCompletion();
}
}