本地五子棋
棋盘部分
用HTML5中的canvas画棋盘,画一个15*15的正方形棋盘。
- 给一个画布背景。
- 用for循环画所有横线,即横坐标不变,纵坐标递增。
- 用for循环画所有竖线,即纵坐标不变,横坐标递增。
for(var i = 1; i < 16;i++){
ctx.beginPath(); //提笔
ctx.moveTo(20, i * 20);
ctx.lineTo(300, i * 20);
ctx.stroke();
}
for(var i = 1; i < 16; i++){
ctx.beginPath();
ctx.moveTo(20 * i, 20);
ctx.lineTo(20 * i,300);
ctx.stroke();
}
点击生成棋子
- 给canvas添加onmousedown鼠标点击事件。或者给canvas添加click监听事件。
canvas.addEventListener('click',function(e){})
- 调用棋子生成器。
- 获取点击位置,并对该坐标先除以20,四舍五入再乘以20,保证棋子在棋盘交叉线上。
- 调用canvas中的arc画圆。
设置黑白规则
- 当黑棋下完后必须是白棋下。
- 为了记录上一次下的棋子的颜色,所以将画过的棋子的坐标放入一个数组中。
- 如果数组长度是偶数则为黑子,奇数为白子。
悔棋处理
- 将该子元素从数组pop出去并将canvas清除(ctx.clearRect(x,y,w,h))。
- 重绘棋盘。
全部代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
canvas {
background-color: burlywood;
}
</style>
</head>
<body>
<canvas width="320px" height="320px" onmousedown="produceChess()"></canvas>
<button onclick="regretChess()">悔棋</button>
</body>
</html>
<script>
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var aChess = [];
drawLine(16);
// 棋盘格线
function drawLine(num) {
for (var i = 1; i < num; i++) {
ctx.beginPath();
ctx.moveTo(20, i * 20);
ctx.lineTo(300, i * 20);
ctx.stroke();
}
for (var i = 1; i < num; i++) {
ctx.beginPath();
ctx.moveTo(20 * i, 20);
ctx.lineTo(20 * i, 300);
ctx.stroke();
}
}
// 棋子生成器
function produceChess() {
var x, y;
// 棋子放在交叉格上
x = Math.round(event.clientX / 20) * 20;
y = Math.round(event.clientY / 20) * 20;
aChess.push({
x: x,
y: y,
color: aChess.length % 2 ? 'white' : 'black'
});
// 黑白规则
ctx.fillStyle = aChess.length % 2 ? 'black' : 'white';
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI * 2);
ctx.fill();
}
// 悔棋,将该子元素从数组pop出去并将canvas清除,并重绘棋盘。
function regretChess() {
aChess.pop();
ctx.clearRect(20,20,300,300);
drawLine(16);
aChess.forEach(function(item){
ctx.beginPath();
ctx.fillStyle = item.color
ctx.arc(item.x, item.y, 10, 0, Math.PI*2);
console.log(item.x, item.y);
ctx.fill();
})
}
</script>
联网五子棋
-
使用websocket建立连接。
-
利用广播使所有客户端都可以看到别人别人下的棋。