// 全局属性
var c = null,
ctx = null,
// 地图
map = null,
// 黑棋、白棋,黑棋预落子,白棋预落子
blackPiece = null,
whitePiece = null,
blackPieceA = null,
whitePieceA = null,
// 格子,棋子的大小
size = null,
// size的一半
halfSize = null,
// 画线的数量
number = null,
// 鼠标所在的X,Y坐标
// mapX = null,
// mapY = null,
// 频繁读取的坐标变量
x = null,
y = null,
// 游戏帧率
fps = null;
window.onload = function () {
c = document.getElementById("myCanvas");
ctx = c.getContext("2d");
ctx.strokeStyle = "#444041";
fps = 1000 / 10;
size = 50;
halfSize = size / 2;
number = 16;
// mapX = halfSize;
// mapY = halfSize;
blackPiece = document.createElement('img');
blackPiece.src = "./imgs/black.png";
whitePiece = document.createElement('img');
whitePiece.src = "./imgs/white.png";
blackPieceA = document.createElement('img');
blackPieceA.src = "./imgs/_black.png";
whitePieceA = document.createElement('img');
whitePieceA.src = "./imgs/_white.png";
// 地图的初始化, 1-黑棋, 2-白棋, 0-无子
initMap();
console.log(map);
// 游戏开始
begin();
};
function initMap() {
map = [];
for (let x = 0; x < number; x++) {
map[x] = [];
for (let y = 0; y < number; y++) {
map[x][y] = 0;
}
}
}
function drawCheckerboard() {
// 准备重绘棋盘
ctx.clearRect(0, 0, c.width, c.height);
// 画棋盘线条
for(let x = 0; x < number; x++) {
ctx.moveTo((x + 1) * size, size);
ctx.lineTo((x + 1) * size, number * size);
}
for(let y = 0; y < number; y++) {
ctx.moveTo(size, (y + 1) * size);
ctx.lineTo(number * size, (y + 1) * size);
}
ctx.stroke();
// 绘制棋盘上的棋子
for (let x = 0; x < number; x++) {
for (let y = 0; y < number; y++) {
if(1 == map[x][y]) {
ctx.drawImage(blackPiece, (x + 0.5) * size, (y + 0.5) * size, size, size);
}
else if(2 == map[x][y]) {
ctx.drawImage(whitePiece, (x + 0.5) * size, (y + 0.5) * size, size, size);
}
}
}
}
function drawPos() {
// 判断鼠标是否在棋盘
if(x < halfSize || y < halfSize ||
x > c.width - halfSize || y > c.height - halfSize) {
return;
}
console.log("mapX: ", mapX, " mapY:", mapY)
console.log(" x: ", x, " y: ", y);
ctx.drawImage(whitePieceA, x, y, size, size);
}
function begin() {
window.setInterval(
// 获取当前坐标
function () {
c.onmousemove = function (e) {
// 如果此时落子,则落在(x,y)处, 圆心为(x+halfSize, y+halfSize)
x = Math.floor((e.layerX + halfSize) / size) * size - halfSize;
y = Math.floor((e.layerY + halfSize) / size) * size - halfSize;
return;
}
drawCheckerboard();
drawPos();
},
fps
);
}