交叉落子问题
//设置一个数组来限制
var chessBoard = [];
var me = true;
for(var i=0;i<15;i++){
chessBoard[i]= [] ;
for(var j = 0;j<15;j++){
//初始化
chessBoard[i][j] = 0;
}
}
var chess = document.getElementById("chess");
var context = chess.getContext('2d');
context.strokeStyle="#BFBFBF";
//设置水印图片
var logo = new Image();
logo.src="image/logo.png";
//设置onload函数为了不让水印图片覆盖掉棋盘的格子
logo.onload = function() {
context.drawImage(logo,0,0,450,450);
drawChessBoard();
}
//画棋盘
var drawChessBoard = function() {
for (var i = 0; i < 15; i++) {
context.moveTo(15+i*30,15);
context.lineTo(15+i*30,433);
context.stroke();
context.moveTo(15,15+i*30);
context.lineTo(433,15+i*30);
context.stroke();
}
}
//画棋子
var onestep = function(i,j,me){
context.beginPath();
context.arc(15+i*30,15+i*30,13,0,360);
context.closePath();
gradient=context.createRadialGradient(15+i*30+2,15+i*30-2,13,15+i*30-2,15+i*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();
}
//实现落子
//首先注册一个onclick事件
chess.onclick = function(e){
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);
if(me){
//黑棋
chessBoard[i][j] = 1;
}else{
//白棋
chessBoard[i][j] = 2;
}
//轮流下棋
me = !me;
}
}