html5 canvas 五子棋游戏
<!doctype html> <html> <head> <meta charset="utf-8"> <title>五子棋</title> <style type="text/css"> *{ margin: 0px; padding: 0px; } canvas{ background: url(images/bg.jpg); } canvas:hover{ cursor: pointer; } </style> </head> <body> <canvas width="800" height="800" id="canvas"></canvas> <script type="text/javascript"> //初始化 var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var flag = 1; //定义二维数组 var data = new Array(); for(var i=1; i<16; i++){ data[i] = new Array(); for(var j=1; j<16; j++){ data[i][j] = 0; } } window.onload = function() { // 1.绘制网格 drawGrid(); // 2.绘制棋子 drawPiece(); } function drawGrid() { for(var i=1; i<16; i++){ context.beginPath(); context.moveTo(50, 50*i); context.lineTo(750, 50*i); context.closePath(); context.stroke(); } for(var i=1; i<16; i++){ context.beginPath(); context.moveTo(50*i, 50); context.lineTo(50*i, 750); context.closePath(); context.stroke(); } } function drawPiece() { canvas.onclick = function(){ var x = Math.round(event.clientX/50); var y = Math.round(event.clientY/50); if(data[x][y] !=0){ alert("棋子不能重复"); return false; } if(flag == 1){ data[x][y] = 1; context.fillStyle = "#000"; context.beginPath(); context.arc((x*50), (y*50), 20, 0*Math.PI, 2*Math.PI, false); context.closePath(); context.fill(); bunko(x, y, flag); flag = 2; }else{ data[x][y] = 2; context.fillStyle = "#fff"; context.beginPath(); context.arc((x*50), (y*50), 20, 0*Math.PI, 2*Math.PI, false); context.closePath(); context.fill(); bunko(x, y, flag); flag = 1; } } function bunko(x, y, flag) { var count1 = 0; var count2 = 0; var count3 = 0; var count4 = 0; /* 1.水平方向判断 */ //向左判断 for(var n=x; n>0; n--){ if(data[n][y] != flag){ break; } count1 = count1+1; } //向右判断 x+1 表示在水平方向上判断时不包含当前棋子本身 for(var n=x+1; n<16; n++){ if(data[n][y] != flag){ break; } count1 = count1+1; } /* 2.垂直方向判断 */ //向上判断 for(var n=y; n>0; n--){ if(data[x][n] != flag){ break; } count2 = count2+1; } //向下判断 y+1 表示在垂直方向上判断时不包含当前棋子本身 for(var n=y+1; n<16; n++){ if(data[x][n] != flag){ break; } count2 = count2+1; } /* 3.斜对角(右下左上方向)*/ //右下左上 for(var n=x, m=y; n>1 && m>1; n--, m--){ if(data[n][m] != flag){ break; } count3 = count3+1; } for(var n=x+1, m=y+1; n<16 && m<16; n++, m++){ if(data[n][m] != flag){ break; } count3 = count3+1; } for(var n=x, m=y; n<16 && m>1; n++, m--){ if(data[n][m] != flag){ break; } count4 = count4+1; } for(var n=x-1, m=y+1; n>0 && m<16; n--, m++){ if(data[n][m] != flag){ break; } count4 = count4+1; } if(count1>=5 || count2>=5 || count3>=5 || count4>=5){ if(flag == 1){ alert("黑棋赢了!"); return false; }else{ alert("白起赢了!"); } } } } </script> </body> </html>