运行效果:
代码:
<!DOCTYPE html>
<html>
<body>
<canvas id="chess" width="450px" height="450px"></canvas>
<script>
var role = "red"; //红方
var chressBord = []; //棋盘
var chess = document.getElementById("chess");
var context = chess.getContext('2d');
window.onload = function()
{
for (var i = 0; i < 15; i++) // 画棋盘
{
context.moveTo(15 + i * 30 , 15);
context.lineTo(15 + i * 30 , 435);
context.moveTo(15 , 15 + i * 30);
context.lineTo(435 , 15 + i * 30);
context.stroke();
}
for (var i = 0; i < 15; i++)
{
chressBord[i] = [];
for (var j = 0; j < 15; j++)
{
chressBord[i][j] = 0; //初始化不放棋子
}
}
}
chess.onclick = function(event)// 红绿双方下棋
{
role == "red" ? role = "green" : role = "red";
var i = Math.floor(event.offsetX / 30);
var j = Math.floor(event.offsetY / 30);
if(chressBord[i][j] == 0)
{
DrawChess(i, j, role);
chressBord[i][j] = role; //占位置
if (CheckWin(i, j, role) == true)
{
alert(role + " is win!");
}
}
}
var CheckOneDirection = function(p, xdiff, ydiff)
{
var tmp = {x: 0, y: 0};
var count = 0;
for (i = 1; i < 5; i++)
{
tmp.x = p.x - xdiff * i;
tmp.y = p.y - ydiff * i;
if (chressBord[tmp.x][tmp.y] != role)
break;
count++;
}
for (i = 1; i < 5; i++)
{
tmp.x = p.x + xdiff * i;
tmp.y = p.y + ydiff * i;
if (chressBord[tmp.x][tmp.y] != role)
break;
count++;
}
if (count >= 4)
return true;
}
var CheckWin = function(x0, y0)
{
var p = {x: x0, y: y0};
if (CheckOneDirection(p, 0, 1)
|| CheckOneDirection(p, 1, 0)
|| CheckOneDirection(p, -1, 1)
|| CheckOneDirection(p, 1, 1)) //直线判断
return true;
return false;
}
var DrawChess = function(i, j, role) //画棋子
{
context.beginPath();
context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);// 画圆
context.closePath();
context.fillStyle = role;
context.fill();
}
</script>
</body>
</html>