Implementing a simple Gobang game with native JavaScript

Implementing a simple Gobang game with native JavaScript

This article shares the specific code for implementing a simple Gobang game in JavaScript for your reference. The specific content is as follows

HTML Page

The annotations are very clear, please study them carefully.

<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=no">
  <title>Gobang</title>
  <style>
    * {
      margin: 0px;
      padding: 0px;
    }
 
    .box {
      border-spacing: 0px;
      border: 1px solid #3c3c3c;
      background-color: #e1e1e2;
      margin: auto;
    }
    
    .piece {
      border-spacing: 0px;
      border: 1px solid;    
    }
  </style>
 
</head>
 
<body>
  <script type="text/javascript" src="./Gobang.js"></script>
</body>
 
</html>

Javascript

var ScreenWidth = {
  documentWidth: 500,
  containerWidth: 400, // container default width cellWidth: 20 // cell width}
if (document.documentElement.clientWidth < 500) {
  ScreenWidth.documentWidth = document.documentElement.clientWidth;
  ScreenWidth.containerWidth = ScreenWidth.documentWidth * 0.8;
  ScreenWidth.cellWidth = ScreenWidth.containerWidth * 0.05;
}
//Constant var reg = /\d{1,2}/g;
var white = []; // Place white piecesvar black = []; // Place black piecesvar tempKey = false; // Determine whether to move black or white piecesvar notOver = true; // Determine if the game is overvar tips = "White moves"; // Tips on moving piecesvar count = 0;//Number of connected piecesvar bv = false; // Black winsvar wv = false; // White winsvar yCanWin = [];// Arrays with the same vertical elementvar xCanWin = [];// Arrays with the same horizontal elementvar xyCanWin = [];// Arrays with the same positive and negative diagonalsvar yxCanWin = [];// Arrays with the same negative and positive diagonals// Use a timer to monitor victoryvar time = setInterval(function () {
  if (bv) {
    tips = "Black wins";
    document.getElementsByTagName("span")[0].innerText = tips;
    for (var i = 0; i < document.getElementsByClassName("pieceBox").length; i++) {
      document.getElementsByClassName("pieceBox")[i].onclick = null;
    }
    clearInterval(time);
  }
  if (wv) {
    tips = "White wins";
    document.getElementsByTagName("span")[0].innerText = tips;
    for (var i = 0; i < document.getElementsByClassName("pieceBox").length; i++) {
      document.getElementsByClassName("pieceBox")[i].onclick = null;
    }
    clearInterval(time);
  }
}, 100);
newGame(); // Start the game function newGame() {
  if (document.getElementsByTagName("table").length) {
    for (var i = 0; i < document.getElementsByTagName("table").length; i++) {
      document.getElementsByTagName("table")[i].remove();
    }
  }
  // Initialize the following content bgInit();
  pieceInit();
  spanFn();
  white = [];
  black = [];
  tempKey = false;
  notOver = true;
  tips = "White moves";
  count = 0;
  bv = false;
  xCanWin = [];
  yCanWin = [];
  xyCanWin = [];
  yxCanWin = [];
}
 
function spanFn() {
  var span = document.createElement("span");
  document.body.insertBefore(span, document.getElementsByTagName("script")[0]);
  span.innerText = tips;
}
// Board initialization function bgInit() {
  var table = document.createElement("table");
  table.className = "box"
  for (var y = 0; y < 20; y++) {
    var tr = document.createElement("tr");
    for (var x = 0; x < 20; x++) {
      var td = "<td class='box-" + y + "-" + x + "' style='width: " + ScreenWidth.cellWidth + "px; height: " + ScreenWidth.cellWidth + "px;border:1px solid #9c9c9c'></td>";
      tr.innerHTML += td;
    }
    table.appendChild(tr);
  }
  document.body.insertBefore(table, document.getElementsByTagName("script")[0]);
}
 
// Chess piece initialization function pieceInit() {
  var table = document.createElement("table");
  table.className = "piece"
  table.style = "position: absolute; top: 0; left:50%; margin-left:-" + (ScreenWidth.containerWidth + 42) / 2 + "px";
  for (var y = 0; y < 20; y++) {
    var tr = document.createElement("tr");
    for (var x = 0; x < 20; x++) {
      var td = "<td class='piece-" + y + "-" + x + " pieceBox' style='width: " + ScreenWidth.cellWidth + "px; height: " + ScreenWidth.cellWidth + "px;border:1px solid transparent;border-radius: 50%;'></td>";
      tr.innerHTML += td;
    }
    table.appendChild(tr);
  }
  document.body.insertBefore(table, document.getElementsByTagName("script")[0]);
}
 
// Move the chess piece for (var i = 0; i < document.getElementsByClassName("pieceBox").length; i++) {
  document.getElementsByClassName("pieceBox")[i].onclick = function () {
    if (tempKey) {
      this.style.backgroundColor = "#000"; // Black spot tempKey = false;
      black.push(this.className.match(reg));
      victory(black, 0); //Judge whether black wins or not if (notOver) {
        tips = tipsGo(tempKey);
        document.getElementsByTagName("span")[0].innerText = tips;
      }
    } else {
      this.style.backgroundColor = "#fff"; // Baizi tempKey = true;
      white.push(this.className.match(reg));
      victory(white, 1); //Judge whether white wins or not if (notOver) {
        tips = tipsGo(tempKey);
        document.getElementsByTagName("span")[0].innerText = tips;
      }
    }
    this.onclick = null; // cancel the click event after clicking}
}
 
// Tips on whether to go black or white function tipsGo(tempKey) {
  if (tempKey) {
    return "Black moves";
  } else {
    return "White moves";
  }
}
 
/**
 * Ways to judge various wins * x represents the vertical coordinate, y represents the vertical coordinate * 1. Vertical win, that is, the x values ​​are the same, take the y values ​​and sort them and compare * 2. Horizontal win, that is, the y values ​​are the same, take the x values ​​and sort them and compare * 3. Forward diagonal win, x+y are the same values, take x or y and sort them and compare * 4. Reverse diagonal win, xy are the same values, take x or y and sort them and compare */
function victory(target, c) {
  if (target.length >= 5) {
    // 1. Vertical win yCanWin
    for (var i = 0; i < target.length; i++) {
      for (var j = 0; j < target.length; j++) {
        if (target[j][1] == target[i][1]) {
          yCanWin.push(target[j]); //Put the same value of x into the array yCanWin
        }
      }
      yWin(yCanWin, c);
      yCanWin = [];
    }
    // 2. Win xCanWin
    for (var m = 0; m < target.length; m++) {
      for (var n = 0; n < target.length; n++) {
        if (target[n][0] == target[m][0]) {
          xCanWin.push(target[n]); //Put the same value of y into the array xCanWin
        }
      }
      xWin(xCanWin, c);
      xCanWin = [];
    }
    // 3. Positive and oblique win xyCanWin (lower left to upper right)
    for (var a = 0; a < target.length; a++) {
      for (var b = 0; b < target.length; b++) {
        if (parseInt(target[b][0]) + parseInt(target[b][1]) == parseInt(target[a][0]) + parseInt(target[a][1])) {
          xyCanWin.push(target[b])
        }
      }
      yWin(xyCanWin, c);
      xyCanWin = [];
    }
    // 4. Backslash win yxCanWin (upper left to lower right)
    for (var v = 0; v < target.length; v++) {
      for (var w = 0; w < target.length; w++) {
        if (parseInt(target[w][0]) - parseInt(target[w][1]) == parseInt(target[v][0]) - parseInt(target[v][1])) {
          yxCanWin.push(target[w])
        }
      }
      xWin(yxCanWin, c);
      yxCanWin = [];
    }
  }
}
// Vertical win condition of chess (vertical win condition of chess)
function yWin(yCanWin, c) { // c = 0 represents black pieces c = 1 represents white pieces var sortArray = []; // sort array for (var i = 0; i < yCanWin.length; i++) {
    sortArray.push(yCanWin[i][0]);
  }
  sortArray.sort(function (x, y) {
    return x - y;
  });
  // After the array is sorted, compare the first number with the last number plus one (note the conversion of the numerical type)
  for (var j = 0; j < sortArray.length; j++) {
    if (sortArray[j + 1]) {
      if (parseInt(sortArray[j]) + 1 == parseInt(sortArray[j + 1])) {
        count++; // Add one for each consecutive number and clear it if there is a discontinuity if (count == 4 && c == 0) {
          bv = true;
          notOver = false; // Game over return;
        } else if (count == 4 && c == 1) {
          wv = true;
          notOver = false;
          return;
        }
      } else {
        count = 0;
      }
    }
  }
  count = 0;
}
// The horizontal winning condition of chess (the reverse diagonal winning condition of chess)
function xWin(xCanWin, c) {
  var sortArray = [];
  for (var i = 0; i < xCanWin.length; i++) {
    sortArray.push(xCanWin[i][1]);
  }
  sortArray.sort(function (x, y) {
    return x - y;
  });
  for (var j = 0; j < sortArray.length; j++) {
    if (sortArray[j + 1]) {
      if (parseInt(sortArray[j]) + 1 == parseInt(sortArray[j + 1])) {
        count++;
        if (count == 4 && c == 0) {
          bv = true;
          notOver = false;
          return;
        } else if (count == 4 && c == 1) {
          wv = true;
          notOver = false;
          return;
        }
      } else {
        count = 0;
      }
    }
  }
  count = 0;
}

For all articles on classic JavaScript games, please refer to the special topic for study.

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:
  • Pure JS implementation of Gobang game compatible with all browsers (with source code)
  • Implementing Gobang game based on JavaScript
  • Javascript and HTML5 use canvas to build a Web Gobang game to implement the algorithm
  • JS canvas draws the Gobang chessboard
  • H5+C3+JS to implement Gobang game (AI version)
  • Native JS+Canvas to implement Gobang game example
  • H5+C3+JS realizes two-player Gobang game (UI chapter)
  • js to realize a simple Gobang game
  • JavaScript beginner tutorial and simple implementation of Gobang applet
  • Native JS+Canvas to implement Gobang game

<<:  Summary of frequently used commands for Linux file operations

>>:  How to implement MySQL bidirectional backup

Recommend

Detailed explanation of the role and principle of key in Vue

Table of contents 1. Let’s start with the conclus...

Reasons why MySQL kill cannot kill threads

Table of contents background Problem Description ...

5 tips for writing CSS to make your style more standardized

1. Arrange CSS in alphabetical order Not in alphab...

Html page supports dark mode implementation

Since 2019, both Android and IOS platforms have s...

Summary of MySql import and export methods using mysqldump

Export database data: First open cmd and enter th...

Interviewers often ask questions about React's life cycle

React Lifecycle Two pictures to help you understa...

Implementation of Mysql User Rights Management

1. Introduction to MySQL permissions There are 4 ...

Hide HTML elements through display or visibility

Sometimes we need to control whether HTML elements...

Summary of knowledge points about events module in Node.js

Through the study and application of Node, we kno...

React event binding details

Table of contents Class component event binding F...

What to do if you forget the initial password when installing MySQL on Mac

Forgetting the password is a headache. What shoul...

How to view files in Docker image

How to view files in a docker image 1. If it is a...

Detailed summary of MySQL and connection-related timeouts

MySQL and connection related timeouts Preface: To...

Vue implements carousel animation

This article example shares the specific code of ...