js canvas to realize the Gobang game

js canvas to realize the Gobang game

This article shares the specific code of the canvas to implement the Gobang game for your reference. The specific content is as follows

Effect

Ideas

  • canvans draws a chessboard, leaving space for chess pieces on the edge when drawing
  • Listen for click events, draw the moves and record them in the dictionary
  • Winning judgment: Check whether there are enough consecutive pieces in four directions

Code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>ym</title>
  <style>
    canvas {
      display: block;
      margin: 0 auto;
      border: 0
    }

    .result {
      text-align: center;
    }
    button{
      display: block;
      margin: 0 auto;
      padding: 4px 20px;
      border:0;
      color: #fff;
      outline: none;
      border-radius: 3px;
      background: #43a6ff
    }
    button:hover{
      font-weight: bold;
      cursor: pointer;
    }
  </style>
</head>
<body>
<canvas id="cv" width="200px" height="200px"></canvas>
<p class="result"></p>
<button onclick="loadPanel(400, 400,30,13)">Refresh</button>
<script>

  loadPanel(400, 400,30,13);

  /**
   * 1) Click to place the piece and switch the player* 2) Based on the current position of the piece, use the "米" shape to determine whether it can form five or more consecutive pieces* @param w chessboard width* @param h chessboard height* @param cs grid size* @param ps chess piece radius*/
  function loadPanel(w, h, cs, ps) {
    let i, j, k;
    let chks = [[1, 0], [0, 1], [1, 1], [1, -1]]; // horizontal, vertical, diagonal downward, diagonal upward let successNum = 5; // winning standard let resultEl = document.querySelector('.result');

    //1) Draw the chessboard, the edge should be separated by the chess piece radius cs = cs || 16; //Default grid width and height ps = ps || 4; //Chess piece radius h = h || w; //Height is equal to width by default let el = document.getElementById('cv');
    el.setAttribute('width', w + 'px');
    el.setAttribute('height', h + 'px');
    let context = el.getContext("2d");
    // Calculate the chessboard split and round down let splitX = ~~((w - 2 * ps) / cs), splitY = ~~((h - 2 * ps) / cs);

    // Initialize the position of the pieces using dictionary storage, which is simpler than arrays and reduces memory usage let pieces = {};
    //Loop line drawing context.translate(ps, ps);
    context.beginPath();
    context.strokeStyle = '#000';
    //vertical line for (i = 0; i < splitX + 1; i++) {
      context.moveTo(cs * i, 0);
      context.lineTo(cs * i, splitY * cs);
      context.stroke();
    }
    //Horizontal line for (j = 0; j < splitY + 1; j++) {
      context.moveTo(0, cs * j);
      context.lineTo(splitX * cs, cs * j);
      context.stroke();
    }
    context.closePath();

    let user = 0, colors = ['#000', '#fefefe'];
    el.addEventListener('click', function (e) {
      let x = e.offsetX,
        y = e.offsetY,
        //Calculate the range of moves rx = ~~((x - ps) / cs) + (((x - ps) % cs <= cs / 2) ? 0 : 1),
        ry = ~~((y - ps) / cs) + (((y - ps) % cs <= cs / 2) ? 0 : 1);
      //Draw the chess piececontext.beginPath();
      context.arc(cs * rx, cs * ry, ps, 2 * Math.PI, false);
      context.fillStyle = colors[user];
      context.strokeStyle = '#000';
      user ? user = 0 : user = 1; //Switch the player context.fill();
      context.stroke();
      context.closePath();

      //Record chess piece position let piece = pieces[rx + '-' + ry] = user;

      //M-shaped calculation results, using the current chess position to calculate whether there are five consecutive identical chess pieces in a certain direction for (j = 0; j < chks.length; j++) {
        let num = 1, chk = chks[j];
        for (i = 1; i <= 4; i++) {
          if (pieces[(rx + chk[0] * i) + '-' + (ry + chk[1] * i)] == piece) {
            num++
          } else {
            for (i = -1; i >= -4; i--) {
              if (pieces[(rx + chk[0] * i) + '-' + (ry + chk[1] * i)] == piece) {
                num++
              }
            }
            break
          }
        }
        if (num == successNum) {
          resultEl.innerHTML = ['white', 'black'][user] + 'Fang wins';
          break;
        }
      }
    })
  }
</script>
</body>
</html>

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:
  • Javascript and HTML5 use canvas to build a Web Gobang game to implement the algorithm
  • JS canvas draws the Gobang chessboard
  • Native JS+Canvas to implement Gobang game example
  • Gobang game implemented by JS+canvas [Man vs. Machine Version]
  • Native JS+Canvas to implement Gobang game
  • js+canvas to realize Gobang game
  • Detailed explanation of the steps to implement JS+canvas Gobang human-computer battle
  • JS+Canvas to realize Gobang game
  • Using js canvas to realize Gobang game
  • JavaScript+canvas to implement Gobang game

<<:  How to configure Basic Auth login authentication in Nginx

>>:  Detailed tutorial for installing MySQL on Linux

Recommend

Example of how to build a Harbor public repository with Docker

The previous blog post talked about the Registry ...

Nginx Linux installation and deployment detailed tutorial

1. Introduction to Nginx Nginx is a web server th...

Example code for implementing dynamic skinning with vue+element

Sometimes the theme of a project cannot satisfy e...

Details on using bimface in vue

Table of contents 1. Install Vue scaffolding 2. C...

How many times will multiple setStates in React be called?

Table of contents 1. Two setState, how many times...

Differences and comparisons of storage engines in MySQL

MyISAM storage engine MyISAM is based on the ISAM...

Summary of common commands in Dockerfile

Syntax composition: 1 Annotation information 2 Co...

Best Practices for Developing Amap Applications with Vue

Table of contents Preface Asynchronous loading Pa...

Sample code for changing the color of a png image through a CSS3 filter

This method uses the drop-shadow filter in CSS3 t...

MySQL log trigger implementation code

SQL statement DROP TRIGGER IF EXISTS sys_menu_edi...

Vue+swiper realizes timeline effect

This article shares the specific code of vue+swip...