android数字扫雷小游戏,100行代码实现的JS扫雷小游戏

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值