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

Installation and use tutorial of Elasticsearch tool cerebro

Cerebro is an evolution of the Elasticsearch Kopf...

MySQL sorting feature details

Table of contents 1. Problem scenario 2. Cause An...

Native js implements shopping cart logic and functions

This article example shares the specific code of ...

Use of js optional chaining operator

Preface The optional chaining operator (?.) allow...

Use of MySQL DATE_FORMAT function

Suppose Taobao encourages people to shop during D...

mysql: [ERROR] unknown option '--skip-grant-tables'

MySQL database reports ERROR 1045 (28000): Access...

js uses Canvas to merge multiple pictures into one implementation code

Solution function mergeImgs(list) { const imgDom ...

Common interview questions and answers for web designer positions

1. What are the templates for ASP.NET Web applicat...

Detailed explanation of bash command usage

On Linux, bash is adopted as the standard, which ...

A detailed discussion of evaluation strategies in JavaScript

Table of contents A chestnut to cover it Paramete...

The difference between div and table in speed, loading, web application, etc.

1: Differences in speed and loading methods The di...

js canvas implements verification code and obtains verification code function

This article example shares the specific code of ...

A few things about favicon.ico (it’s best to put it in the root directory)

Open any web page: for example, http://www.baidu....