Native js implements a minesweeper game with custom difficulty

Native js implements a minesweeper game with custom difficulty

This article example shares the specific code of js to implement the minesweeper game for your reference. The specific content is as follows

Game features:

1. There are four levels of difficulty
2. You can set your own difficulty

1. HTML related code

<!DOCTYPE html>
<html lang="en">
 
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Minesweeper</title>
 <script src="js/mine.js"></script>
 <link rel="stylesheet" href="./css/mine.css" >
</head>
<!-- 
Demand Analysis:
 1. Game area:
  9*9 area 2. Squares can be opened and marked. Left click to open, numbers are displayed, which are the number of mines in the surrounding squares. Right click to mark 3. Mines are randomly distributed 4. When you step on a mine, the game ends and all mines are displayed 5. Chain to open large empty squares 6. The number of remaining mines and timer 7. Game victory conditions. All squares except mines are opened, then the game is won. Information contained in a square:
  Coordinate xy
  Is it a mine? Number of mines around it = 9
  The two-dimensional array stores the number of surrounding mines -->
 
<body>
 <div class="level">
 <button type="button" name="button" class="choice-level">Custom</button>
 <button type="button" name="button" class="choice-level">Elementary</button>
 <button type="button" name="button" class="choice-level">Intermediate</button>
 <button type="button" name="button" class="choice-level">Advanced</button>
 <button type="button" name="button" class="choice-level">Devil Level</button>
 <button type="button" name="button" class="restart">Restart</button>
 </div>
 <div class="gameBox"></div>
 <div class="info">
 <p>Number of mines remaining:
  <span class="residue"></span>
 </p>
 <p>
  TIME:
  <span class="tick"></span>S
 </p>
 
 </div>
</body>
 
 
</html>

2. CSS style

*{
 margin: 0;
 padding: 0;
}
.gameBox{
 margin-top: 30px;
}
body{
 font-size: 0;
}
ul{
 list-style: none;
 text-align: center;
 overflow: hidden;
}
.col{
 display: inline-block;
 width: 22px;
 height: 22px;
 line-height: 22px;
 background-color: rgba(32, 226, 255, 0.4);
 border: 1px solid rgb(129, 129, 129);
 font-size: 16px;
 margin: 1.5px;
 vertical-align: top;
 position: relative;
}
.col:hover{
 background-color: #0af;
}
.col span{
 cursor: default;
}
.hide{
 display: none;
}
.boom{
 background: url("../img/boom.svg") no-repeat 2.5px 2px;
 background-size: 18px 18px;
}
.num-1{
 color: rgb(8, 153, 235);
}
.num-2{
 color: rgb(255, 45, 178);
}
.num-3{
 color:#16a085;
}
.num-4{
 color: #8e44ad;
}
.num-5{
 color: rgb(255, 167, 45);
}
.num-6{
 color: rgb(8, 126, 176);
}
.num-7{
 color: #e67e22;
}
.num-8{
 color: #c0392b;
}
.img-flag{
 width: 18px;
 height: 18px;
 position: absolute;
 top: 3px;
 left: 3px;
}
.level{
 margin-top: 30px;
 font-size: 20px;
 text-align: center;
}
.level button{
 padding: 5px 8px;
 background-color: rgb(67, 183, 189);
 border: none;
 outline: none;
 border-radius: 3px;
 cursor: pointer;
 color: #fff;
}
.level button:hover{
 background-color: rgb(23, 132, 138);
}
.info{
 margin-top: 30px;
 font-size: 16px;
 text-align: center;
}
.info p{
 display: inline-block;
 width: 130px;
 margin: 0 auto;
}
.info p span{
 color: rgb(67, 183, 189);
}

3.js code

window.onload = function() {
 var row = 4;
 var col = 4;
 var num = 1;
 // Determine that you cannot win after stepping on a landmine var gg = false;
 // Generate map function mineMap(r, c, num) {
 //Definition line var map = [];
 //Give the number of rows and generate a two-dimensional array for (var i = 0; i < r; i++) {
  map[i] = new Array()
 }
 // Assignment for (var i = 0; i < map.length; i++) {
  for (var j = 0; j < c; j++) {
  // //Number of mines around map[i][j] = 0;
  }
 }
 var plus = function(array, x, y) {
  if (x >= 0 && x < r && y >= 0 && y < c) {
  if (array[x][y] !== 9) {
   array[x][y]++
  }
  }
 }
 for (var i = 0; i < num; i++) {
  var x = Math.floor(Math.random() * r)
  var y = Math.floor(Math.random() * c)
  if (map[x][y] != 9) {
  map[x][y] = 9
   //6 up and down + 1
  for (var j = -1; j < 2; j++) {
   //Three plus(map, x - 1, y + j)
   //Next three plus(map, x + 1, y + j)
  }
  //2 on the left and right +1
  plus(map, x, y - 1)
  plus(map, x, y + 1)
  } else {
  //Re-randomize num++
  }
 }
 return map;
 }
 //First write the x-axis quantity into ul, then write the y-axis attributes into li
 function writeHtml(map) {
 // Get the box var gameBox = document.querySelector(".gameBox");
 //Declare an empty string to store the generated ul and li
 var gridHTML = "";
 for (var i = 0; i < map.length; i++) {
  gridHTML += '<ul class = "row" data-x="' + i + '">';
  //Generate li
  for (var j = 0; j < map[0].length; j++) {
  var m = map[i][j]
  if (m == 0) {
   m = "";
  }
  gridHTML += "<li class='col' data-y=" + j + ">" +
   "<span class='hide num-" + m + "'>" + m + "</span>" +
   "<img src='img/flag.svg' class='img-flag hide'>" +
   "</li>"
  }
  gridHTML += '</ul>'
  gameBox.innerHTML = gridHTML;
 }
 }
 
 //Bind events to the grid, right-click on the digital mine function show() {
 // Get the row ul
 var rows = document.querySelectorAll(".row");
 // Traverse all ul
 for (var i = 0; i < rows.length; i++) {
  var element = rows[i];
  // Add click event element.onclick = function(event) {
   //Currently clicked element var el = event.target;
   // Determine whether it is li
   if (el.nodeName != "LI") {
   return;
   }
   //todo determines whether it is opened and marked if (el.style.background == "white" || !el.children[1].classList.contains("hide")) {
   return;
   }
   // Get the span tag content var mineNum = el.children[0].innerHTML;
   if (mineNum !== "9" && el.style.background !== "white") {
   // Blank chain open if (mineNum == "") {
    var x = parseInt(el.parentNode.dataset.x);
    var y = parseInt(el.dataset.y);
    showNoMine(x, y);
   }
   // li background turns white; span displays el.style.background = "white";
   el.children[0].style.display = "inline";
   // Determine the number of open mines clearMineNum++;
   // Victory function judgeVictory()
 
   } else if (mineNum == "9") {
   // Clear the victory timer clearInterval(stopTime);
   // li adds class name el.classList.add("boom");
   alert("You are such a scumbag!")
   gg = true;
   // Display all mines, get all li
   var all = document.querySelectorAll(".col");
   // Place all mines var ff = [];
   var allnum = 0;
   // Traverse all li
   for (var i = 0; i < all.length; i++) {
    if (all[i].children[0].innerHTML == "9") {
    // Lei assigns values ​​to the array ff[allnum] = all[i];
    allnum++;
    }
   }
   // Set a timer to open mines one by one allnum = 0;
   var stop = setInterval(function() {
    ff[allnum].classList.add("boom")
    allnum++;
    // Determine the end condition if (allnum == ff.length) {
    // Clear the timer clearInterval(stop);
    }
   }, 30)
 
   }
  }
  // Right click to mark a mine element.oncontextmenu = function(event) {
  // Prevent the right-click menu event.preventDefault();
  // Get the current clicked node var el = event.target;
  // Determine if (el.parentNode.nodeName == "LI") {
   el = el.parentNode;
  }
  if (el.nodeName != "LI") {
   return;
  }
  // Get img
  var classList = el.children[1].classList;
  // Remaining mine number var residue = document.querySelector(".residue");
  var mineNum = parseInt(residue.innerHTML);
  // If there is no flag and it has not been clicked, you can insert a flag if (classList.contains("hide") && el.style.background != "white") {
   // Remove hidden classList.remove("hide");
   // Get the mine number mineNum--;
  } else if (el.style.background != "white") {
   classList.add("hide");
   // Determine the number of mines if (mineNum < num) {
   mineNum++;
   }
  }
  // Remaining mine number residue.innerHTML = mineNum;
  }
 }
 }
 
 function judgeVictory() {
 //Game victory if (clearMineNum === (row * col - num)) {
  //Make a small animationvar all = document.querySelectorAll(".col");
  var allNum = 0;
  var stop = setInterval(function() {
  var r = Math.floor(Math.random() * 256)
  var g = Math.floor(Math.random() * 256)
  var b = Math.floor(Math.random() * 256)
  all[allNum].style.background = "rgba(" + r + "," + g + "," + b + ",0.6)";
  //Hide both the flag and span all[allNum].children[0].style.display = "none"
  all[allNum].children[1].style.display = "none"
  allNum++
  if (allNum === all.length) {
   clearInterval(stop)
   if (!gg) {
   alert("Good luck, let's eat chicken tonight")
   init(row, col, num)
   }
  }
  }, 20)
 }
 }
 //Automatically open spaces function showNoMine(x, y) {
 for (var i = -1; i <= 1; i++) {
  if (x + i >= 0 && x + i < row) {
  // Get the current row var rowElement = document.querySelectorAll(".row")[x + i];
  for (var j = -1; j <= 1; j++) {
   if (y + j >= 0 && y + j < col) {
   //Get the current cell var el = rowElement.children[y + j]
    //Automatically open the grid must be unopened if (el.style.background != "white") {
    el.style.background = "white"
    el.children[0].style.display = "inline"
    //Open the number of squares + 1
    clearMineNum++
    //Judge whether the game is won judgeVictory(clearMineNum)
 
    if (el.children[0].innerText === "") {
    showNoMine(x + i, y + j)
    }
   }
   }
  }
  }
  // if (x + i >= 0 && x + i < row) {
  // // Get the current row // var rowElement = document.querySelectorAll(".row")[x + i];
  // for (var j = -1; j <= 1; j++ && y + j < col) {
  // // Get the current cell // var el = rowElement.children[y + j];
  // if (el.style.background !== "white") {
  // el.style.background = "white";
  // el.children[0].style.display = "inline";
  // // The number of opened grids increases by 1
  // clearMineNum++;
  // //Judge whether the game is won// judgeVictory(clearMineNum);
  // // Determine whether the surrounding grid is empty// if (el.children[0].innerHTML === "") {
  // showNoMine(x + i, y + j)
  // }
  // }
  // }
  // }
 }
 
 }
 //Initialization method var stopTime;
 
 function init(row, col, num) {
 //Data initialization clearMineNum = 0
 gg = false;
 // Clear the original map and generate a new map var box = document.querySelector(".gameBox")
 box.innerHTML = "";
 var map = mineMap(row, col, num);
 //Create a new map writeHtml(map);
 show()
  //Write the number of mines into HTML var residue = document.querySelector(".residue")
 residue.innerHTML = num
  // Get the timing var tick = document.querySelector(".tick");
 var i = 0;
 // Initialize tick.innerHTML = i;
 // Clear timing clearInterval(stopTime);
 // Timer stopTime = setInterval(function() {
  tick.innerHTML = ++i
 }, 1000)
 }
 // Reset var restart = document.querySelector(".restart");
 restart.onclick = function(event) {
  //Stop bubbling event.stopPropagation()
  init(row, col, num)
 }
 // Custom var level = document.querySelector(".level")
 level.onclick = function(event) {
 var el = event.target;
 switch (el.innerHTML) {
  case "Primary":
  row = 9;
  col = 9;
  num = 10;
  init(row, col, num)
  break;
  case "Intermediate":
  row = 16;
  col = 16;
  num = 40;
  init(row, col, num)
  break;
  case "Advanced":
  row = 16;
  col = 30;
  num = 479;
  init(row, col, num)
  break;
  case "Devil level":
  row = 40;
  col = 50;
  num = 300;
  init(row, col, num)
  break;
  case "custom":
  row = prompt("Please enter the number of columns!");
  col = prompt("Please enter the number of rows!");
  num = prompt("Please enter the number of mines you want, (please choose carefully)");
  init(row, col, num);
  break;
  default:
  row = 9;
  col = 9;
  num = 10;
  init(row, col, num)
  break;
 }
 }
 init(row, col, num)
}

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Implementing a simple minesweeper game based on JavaScript
  • js+canvas implements a simple minesweeper game
  • Implementing a minesweeper game code example using javascript
  • HTML+JavaScript to implement the minesweeper game
  • JavaScript version of the classic game Minesweeper game complete example [with demo source code download]
  • Share your own minesweeper game made with JS
  • Using pure javascript to implement the classic minesweeper game
  • JavaScript makes Windows classic minesweeper game
  • javascript minesweeper game
  • js implements the classic minesweeper game

<<:  The shell script regularly counts the PV of access.log under Nginx and sends it to the API and saves it in the database

>>:  64-bit CentOs7 source code installation mysql-5.6.35 process sharing

Recommend

Implementation of Docker private warehouse registry deployment

As more and more Docker images are used, there ne...

HTML unordered list bullet points using images CSS writing

Create an HTML page with an unordered list of at l...

Mybatis statistics of the execution time of each SQL statement

background I am often asked about database transa...

Linux kernel device driver advanced character device driver notes

/****************** * Advanced character device d...

Example of how to configure multiple virtual hosts in nginx

It is very convenient to configure virtual host v...

Disabled values ​​that cannot be entered cannot be passed to the action layer

If I want to make the form non-input-capable, I se...

How to use port 80 in Tomcat under Linux system

Application Scenario In many cases, we install so...

Control the vertical center of the text in the HTML text box through CSS

When the height attribute of Text is defined, the ...

Complete steps for Docker to pull images

1. Docker pull pulls the image When using $ docke...

Detailed explanation of docker version es, milvus, minio startup commands

1. es startup command: docker run -itd -e TAKE_FI...

37 Tips for a Good User Interface Design (with Pictures)

1. Try to use single column instead of multi-colum...

Some suggestions for ensuring MySQL data security

Data is the core asset of an enterprise and one o...