本文实例为大家分享了canvas实现五子棋游戏的具体代码,供大家参考,具体内容如下

html部分

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body style="margin: 0;">
  <canvas style="margin-left: 20px;" id="five"></canvas>
  <h1 style="font-size: 40px;font-weight: bolder;margin-left: 200px;margin-top: 0;margin-bottom: 0;">五子棋</h1>
  <h2 style="font-size: 40px;font-weight: bolder;margin-left: 200px;margin-top: 0;" id="currole">轮到:黑</h2>
  <div id="res" style="font-size: 40px;font-weight: bolder;margin-left: 200px;">胜者:</div>
</body>
<script>
  let cav = document.getElementById('five')
  let ctx = cav.getContext('2d')
  let k = 50 //倍数
  let r = k/4
  cav.width = cav.height = 16*k
  ctx.strokeStyle="#000000";
  for(let i = 0;i<15;i++){
    ctx.beginPath();
    ctx.moveTo((i+1)*k,k);
    ctx.lineTo((i+1)*k,15*k);
    ctx.stroke();
  }
  for(let i = 0;i<15;i++){
    ctx.beginPath();
    ctx.moveTo(k,(i+1)*k);
    ctx.lineTo(15*k,(i+1)*k);
    ctx.stroke();
  }
  function initer(event){
    let x = event.offsetX - k
    let y = event.offsetY - k
    let xclose = close(x,0,14)
    let yclose = close(y,0,14)
    let nodearr = []
    let minxd = Math.abs(x-xclose[0]*k)<Math.abs(x-xclose[1]*k)"click",initer)
  function close(coo,lort,rorb){
    coo<0"black"
      ctx.beginPath();
      ctx.arc(arr[0]+k,arr[1]+k,r,0,2*Math.PI);
      ctx.stroke();
      ctx.fill();
      checkFinish([arr[0]/k,arr[1]/k])
      gomoku[arr[0]/k][arr[1]/k] = colorflag
      colorflag = 1
      document.getElementById('currole').innerHTML="轮到:白"
    }else{
      ctx.fillStyle="white"
      ctx.beginPath();
      ctx.arc(arr[0]+k,arr[1]+k,r,0,2*Math.PI);
      ctx.stroke();
      ctx.fill();
      checkFinish([arr[0]/k,arr[1]/k])
      gomoku[arr[0]/k][arr[1]/k] = colorflag
      colorflag = 0
      document.getElementById('currole').innerHTML="轮到:黑"
    }
  }

</script>
<script src="/UploadFiles/2021-04-02/five.js">

外部js文件部分

let gomoku = new Array(15)
for(let i = 0;i<gomoku.length;i++){
  gomoku[i]=new Array(15)
}
//black 0 white 1

function checkFinish(curnode){
  for(let i =0;i<4;i++){
    let totalLength = 1
    let aflag = true
    let bflag = true
    for(let j=0;j<4;j++){
      let dictNum = j+1
      switch(i){
        case 0:
          if(aflag){
            (gomoku[curnode[0]+dictNum][curnode[1]]===colorflag)
            &&((curnode[0]+dictNum)<=14)"click",initer)
        }else{
          document.getElementById('res').innerHTML='胜者:白方'
          cav.removeEventListener("click",initer)
        }
        break;
      }
      if((aflag===false)&&(bflag===false)){
        break;
      }
    }
    if(totalLength>=5){
      break;
    }
  }
}
//all work and no play makes jack a dull boy

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!