canvas画布,还是一个比较令人头疼的东西,由于自己用得少,所以觉得还很欠缺,偶然间看到人家写的五子棋,便也顺便学习一下,写个试试,全当练练手,顺便记录一下。
1、先创建canvas,画个棋盘
var context = chess.getContext('2d'); context.strokeStyle = "#dedede"; var drawLine=function(){ for(var i=0;i<15;i++){ context.moveTo(15+i*30,15); context.lineTo(15+i*30,435); context.stroke(); context.moveTo(15,15+i*30); context.lineTo(435,15+i*30); context.stroke(); } }; drawLine();
2、然后就是自己落子和电脑对应落子
var oneStep = function(i,j,me){ context.beginPath(); context.arc(15+i*30,15+j*30,13,0,2*Math.PI); var gradient = context.createRadialGradient(15+i*30+2,15+j*30-2,13,15+i*30+2,15+j*30-2,0) if(me){ gradient.addColorStop(0,"#0a0a0a"); gradient.addColorStop(1,"#636766"); }else{ gradient.addColorStop(0,"#d1d1d1"); gradient.addColorStop(1,"#f9f9f9"); } context.fillStyle = gradient; context.fill(); context.closePath(); }; chess.onclick=function(e){ if(over){ return; } if(!me){ return; } var x= e.offsetX; var y= e.offsetY; var i = Math.floor(x/30); var j = Math.floor(y/30); if(chessBoard[i][j] == 0){ oneStep(i, j,me); chessBoard[i][j] = 1; for(var k=0;k<count;k++){ if(wins[i][j][k]){ myWin[k]++; computerWin[k] = 6; if(myWin[k] == 5){ msgBox.style.display = "block"; msgTxt.innerHTML = "你赢了!"; over = true; } } } if(!over){ me = !me; computerAI(); } } }; var computerAI = function(){ var myScore = []; var computerScore = []; var max = 0; var u = 0, v = 0; for(var i = 0;i<15;i++){ myScore[i]=[]; computerScore[i]=[]; for(var j=0;j<15;j++){ myScore[i][j] = 0; computerScore[i][j] = 0; } } for(var i = 0;i<15;i++){ for(var j=0;j<15;j++){ if(chessBoard[i][j] == 0){ for(var k=0;k<count;k++){ if(wins[i][j][k]){ if(myWin[k]==1){ myScore[i][j]+=200; }else if(myWin[k]==2){ myScore[i][j]+=400; }else if(myWin[k]==3){ myScore[i][j]+=2000; }else if(myWin[k]==4){ myScore[i][j]+=10000; } if(computerWin[k]==1){ computerScore[i][j]+=300; }else if(computerWin[k]==2){ computerScore[i][j]+=500; }else if(computerWin[k]==3){ computerScore[i][j]+=3000; }else if(computerWin[k]==4){ computerScore[i][j]+=20000; } } } } if(myScore[i][j] > max){ max = myScore[i][j]; u=i; v=j; }else if(myScore[i][j] == max){ if(computerScore[i][j]>computerScore[u][v]){ u=i; v=j; } } if(computerScore[i][j]>max){ max = computerScore[i][j]; u=i; v=j; }else if(computerScore[i][j] == max){ if(myScore[i][j] > myScore[u][v]){ u=i; v=j; } } } } oneStep(u,v,false); chessBoard[u][v] = 2; for(var k=0;k<count;k++){ if(wins[u][v][k]){ computerWin[k]++; myWin[k] = 6; if(computerWin[k] == 5){ msgBox.style.display = "block"; msgTxt.innerHTML = "Computer赢了!"; over = true; } } } if(!over){ me = !me; } };
反正这玩意儿,掌握技巧后就能老赢,哈哈,可能是写得缺陷比较大吧
想获取完整代码的小伙伴,可以去微信小程序搜索 ‘工具百宝汇’,在“模版-其他”中可以获取网盘分享地址哦
标签:canvas,15,gradient,max,30,五子棋,对战,context,var From: https://www.cnblogs.com/Immortal-brother/p/17687811.html