Canvas (3) 圍棋落子

綁定一個 onclick 事件,並且取得棋子在棋盤的索引位置。因為所有的棋子都是落在交叉點,所以點擊事件裡面
的參數要傳入的變數要取得的是相對於左上角開始的 x 軸及 y 軸的座標 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
var canvas = document.getElementById("canvas");
canvas.width = 450;
canvas.height = 450;
var cxt = canvas.getContext("2d");

cxt.strokeStyle = "black";

for (var i = 0; i < 15; i++) {
cxt.moveTo(15 + i * 30, 15);
cxt.lineTo(15 + i * 30, 435);
cxt.stroke();
cxt.moveTo(15, 15 + i * 30);
cxt.lineTo(435, 15 + i * 30);
cxt.stroke();
}

oneStep = function(i, j, me) {
//i,j =棋盤上索引, me 黑棋或白棋
cxt.beginPath();
cxt.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * this.Math.PI);
cxt.closePath();
var gradient = cxt.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, "#636766");
} else {
gradient.addColorStop(0, "#D1D1D1");
gradient.addColorStop(1, "#F9F9F9");
}

cxt.fillStyle = gradient;
cxt.fill();
};

oneStep(0, 0, true);
oneStep(1, 1, false);

canvas.onclick = function(e) {
var x = e.offsetX;
var y = e.offsetY;
var i = Math.floor(x / 30);
var j = Math.floor(y / 30);
oneStep(i, j, true);
};

接下來開始落子,並可以切換黑白子。預設如果 me=true 則為黑子,下完黑子則輪白子。並且設定一個條件式,避免已經落子的位置被下一手更改。需要一個空陣列儲存所有棋盤上落子的狀況,並且遍歷這個棋盤,把 x、y 軸都設定成初始值沒有落子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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;
}
}

canvas.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, true);
if (me) {
chessBoard[i][j] = 1;
} else {
chessBoard[i][j] = 2;
}
}

me = !me;
};

Powered by Hexo and Hexo-theme-hiker

Copyright © 2013 - 2020 CYC'S BLOG All Rights Reserved.

UV : | PV :