定义canvas及黑白棋变量
<font color="#2f4f4f" face="微软雅黑" size="3">var canvas
var context
var isWhite = true//设置是否该轮到白棋
var isWell = false//设置该局棋盘是否赢了,如果赢了就不能再走了
var img_b = new Image()
img_b.src = "images/b.png"//白棋图片
var img_w = new Image()
img_w.src = "images/c.png"//黑棋图片</font>
为棋盘的二维数组用来保存棋盘信息
<font color="#2f4f4f" face="微软雅黑" size="3">var chessData = new Array(15)//初始化0为没有走过的,1为白棋走的,2为黑棋走的
for (var x = 0x <15x++) {
chessData[x] = new Array(15)
for (var y = 0y <15y++) {
chessData[x][y] = 0
}
}</font>
绘制棋盘的线
<font color="#2f4f4f" face="微软雅黑" size="3"> for (var i = 0i <= 640i += 40) {
context.beginPath()
context.moveTo(0, i)
context.lineTo(640, i)
context.closePath()
context.stroke()
context.beginPath()
context.moveTo(i, 0)
context.lineTo(i, 640)
context.closePath()
context.stroke()
}
}</font>
判断该棋局的输赢
<font color="#2f4f4f" face="微软雅黑" size="3">if (count1 >= 5 || count2 >= 5 || count3 >= 5 || count4 >= 5) {
if (chess == 1) {
alert("白棋赢了")
}
else {
alert("黑棋赢了")
}
isWell = true//设置该局棋盘已经赢了,不可以再走了
}</font>
html代码:
<font color="#2f4f4f" face="微软雅黑" size="3"><body onload="drawRect()">
<div>
<canvas width="640" id="canvas" onmousedown="play(event)" height="640">你的浏览器不支持HTML5 canvas ,请使用 google chrome 浏览器 打开.
</canvas>
</div>
</body></font>