当前位置:首页 >> 网络编程

利用js canvas实现五子棋游戏

本文实例为大家分享了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

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