[vb]代码库
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=3, minimum-scale=1.0, maximum-scale=3.0">
<title>在线五子棋</title>
</head>
<body>
<canvas id="myCanvas" width="351" height="351" onclick="downChessman(event)"></canvas>
<script type="text/javascript">
var w=25;//方格宽度
var cxt=null,myCanvas=null;//
var arrays=new Array();
window.onload=function(){
myCanvas=document.getElementById("myCanvas");
cxt=myCanvas.getContext("2d");
cxt.translate(0.5,0.5);
init();
};
function init(){
cxt.strokeStyle="#666";
for(var i = 0;i<16;i++){
cxt.moveTo(w*i,0);
cxt.lineTo(w*i,14*w);
cxt.stroke();
cxt.restore();
}
for(var i = 0;i<16;i++){
cxt.moveTo(0,w*i);
cxt.lineTo(14*w,w*i);
cxt.stroke();
cxt.restore();
}
initDrawPoint();
initArray();
}
function initDrawPoint(){
cxt.fillStyle="#000";
for(var i=3;i<15;){
for(var j=3;j<15;){
cxt.beginPath();
cxt.arc(w*i,w*j,2,0,Math.PI*2,true);
cxt.fill();
j=j+8;
}
i=i+8;
}
cxt.beginPath();
cxt.arc(w*7,w*7,3,0,Math.PI*2,true);
cxt.fill();
}
function initArray(){
for(var i=0;i<16;i++){
arrays[i]=new Array();
for(var j=0;j<16;j++){
arrays[i][j]=0;
}
}
}
function drawChessman(i,j,type){
var img = new Image();
img.onload = function(){
cxt.drawImage(img, w*i-10,w*j-10);
//检查是否已经赢了
checkWin();
};
if(type){//是黑子
img.src="b.png";
}else{
img.src="w.png";
}
}
var type=false;
function downChessman(e){
type = !type;
var ox = myCanvas.offsetLeft,oy=myCanvas.offsetTop;
var x = Math.round((e.clientX-ox) / w);
var y = Math.round((e.clientY-oy) / w);
//console.log("cx="+(e.clientX-ox)+",cy="+(e.clientY-oy));
//console.log("x="+x+",y="+y);
var val = arrays[x][y];
if(val==0){//没有棋子
if(type){//黑子
arrays[x][y]=1;
}else{
arrays[x][y]=2;//白子
}
drawChessman(x,y,type);
}
}
function checkWin(){
var b0=b1=w0=w1=0;
for(var x=0;x<16;x++){
for(var y=0;y<16;y++){
var val = arrays[x][y];
if(val>0){//有棋子
if(y<16-5&&val==arrays[x][y+1]&&val==arrays[x][y+2]&&val==arrays[x][y+3]&&val==arrays[x][y+4]){//y轴连续5颗相同棋子
alert(val==1?"黑子获胜":"白子获胜");
return;
}
if(x<16-5&&y<16-5&&val==arrays[x+1][y+1]&&val==arrays[x+2][y+2]&&val==arrays[x+3][y+3]&&val==arrays[x+4][y+4]){//西北->东南方向连续5颗相同棋子
alert(val==1?"黑子获胜":"白子获胜");
return;
}
if(x<16-5&&val==arrays[x+1][y]&&val==arrays[x+2][y]&&val==arrays[x+3][y]&&val==arrays[x+4][y]){//x轴连续5颗相同棋子
alert(val==1?"黑子获胜":"白子获胜");
return;
}
if(x-4>=0&&val==arrays[x-1][y+1]&&val==arrays[x-2][y+2]&&val==arrays[x-3][y+3]&&val==arrays[x-4][y+4]){
alert(val==1?"黑子获胜":"白子获胜");
return;
}
}
}
}
}
</script>
</body>
</html>
by: 发表于:2017-12-01 14:55:34 顶(1) | 踩(1) 回复
??
回复评论