<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
canvas {
display: block;
margin: 50px auto;
box-shadow: -2px -2px 2px #efefef, 5px 5px 5px #999;
}
</style>
</head>
<body>
<canvas id="canvas" width="450" height="450"></canvas>
<script>
var mc = document.getElementById('canvas');
var ctx = mc.getContext('2d');
var me = true;
var chessArr = [];
var over = false;
//赢法数组
var wins = [];
//赢法的统计数组
var myWin = [];//人
var computerWin = [];//计算机
for (var i = 0; i < 15; i++) {
chessArr[i] = [];
for (var j = 0; j < 15; j++) {
chessArr[i][j] = 0;
}
}
//初始化
//初始化赢法数组
for (var i = 0; i < 15; i++) {
wins[i] = [];
for (var j = 0; j < 15; j++) {
wins[i][j] = [];
}
}
var count = 0;//赢法种类索引
//横线
for (var i = 0; i < 15; i++) {
for (var j = 0; j < 11; j++) {
for (var k = 0; k < 5; k++) {
wins[i][j + k][count] = true;
}
count++;
}
}
//竖线
for (var i = 0; i < 15; i++) {
for (var j = 0; j < 11; j++) {
for (var k = 0; k < 5; k++) {
wins[j + k][i][count] = true;
}
count++;
}
}
//斜线
for (var i = 0; i < 11; i++) {
for (var j = 0; j < 11; j++) {
for (var k = 0; k < 5; k++) {
wins[i + k][j + k][count] = true;
}
count++;
}
}
//反斜线
for (var i = 0; i < 11; i++) {
for (var j = 14; j > 3; j--) {
for (var k = 0; k < 5; k++) {
wins[i + k][j - k][count] = true;
}
count++;
}
}
console.log(wins, count);
for (var i = 0; i < count; i++) {
myWin[i] = 0;
computerWin[i] = 0;
}
var logo = new Image();
logo.src = "img/book.jpg";
logo.onload = function () {
ctx.drawImage(logo, 0, 0, 450, 450);
drawBoard();
}
//绘制棋盘
function drawBoard() {
ctx.strokeStyle = '#bfbfbf';
for (var i = 0; i < 15; i++) {
ctx.moveTo(15 + i * 30, 15);
ctx.lineTo(15 + i * 30, 435);
ctx.moveTo(15, i * 30 + 15);
ctx.lineTo(435, i * 30 + 15);
ctx.stroke();
}
}
//绘制棋子
function drawChess(i, j, me) {
ctx.beginPath();
ctx.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
ctx.closePath();
var gradient = ctx.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, "#636367");
} else {
gradient.addColorStop(0, "#D1D1D1");
gradient.addColorStop(1, "#f9f9f9");
}
ctx.fillStyle = gradient;
ctx.fill();
}
mc.onclick = function (e) {
if (over) {
return;
}
var x = e.offsetX;
var y = e.offsetY;
var i = Math.floor(x / 30);
var j = Math.floor(y / 30);
if (chessArr[i][j] == 0) {
drawChess(i, j, me);
if (me) {
chessArr[i][j] = 1;
} else {
chessArr[i][j] = 2;
}
me = !me;
for (var k = 0; k < count; k++) {
if (wins[i][j][k]) {
myWin[k]++;
computerWin[k] = 6;
if (myWin[k] == 5) {
window.alert("you win !!!");
over = true;
}
}
}
}
}
</script>
</body>
</html>