我正在努力在画布上创建井字游戏。我目前被困在一个点,我检测到画布上的 x/y 坐标是否已经存在符号(X 或 O)。
我尝试使用 ImageData 检查元素是否存在,但如果不存在则返回错误。我还想也许我可以为正方形或符号分配一个 ID。但是,从我读过的内容来看,这似乎是不可能的。
任何帮助,将不胜感激。
你可以在这里看到运行的游戏http://jsfiddle.net/weeklygame/dvJ5X/30/
function TTT() {
this.canvas = document.getElementById('ttt');
this.context = this.canvas.getContext('2d');
this.width = this.width;
this.height = this.height;
this.square = 100;
this.boxes = [];
this.turn = Math.floor(Math.random() * 2) + 1;
this.message = $('.message');
};
var ttt = new TTT();
TTT.prototype.currentPlayer = function() {
var symbol = (this.turn === 1) ? 'X' : 'O';
ttt.message.html('It is ' + symbol + '\'s turn');
};
// Draw the board
TTT.prototype.draw = function(callback) {
// Draw Grid
for(var row = 0; row <= 200; row += 100) {
var group = [];
for(var column = 0; column <= 200; column += 100) {
group.push(column);
this.context.strokeStyle = 'white';
this.context.strokeRect(column,row,this.square,this.square);
};
this.boxes.push(group);
};
callback;
};
// Get center of the click area cordinates
TTT.prototype.cordinates = function(e) {
var row = Math.floor(e.clientX / 100) * 100,
column = Math.floor(e.clientY / 100) * 100;
return [row, column];
};
// Check if the clicked box has symbol
TTT.prototype.check = function(row, column) {
};
// Get cordinates and set image in container
TTT.prototype.click = function(e) {
var cordinates = ttt.cordinates(e),
x = cordinates[0] + 100 / 2,
y = cordinates[1] + 100 / 2,
image = new Image();
if (ttt.turn === 1) {
image.src = 'http://s8.postimg.org/tdp7xn6lt/naught.png';
ttt.turn = 2;
} else {
image.src = 'http://s8.postimg.org/9kd44xt81/cross.png';
ttt.turn = 1;
};
ttt.context.drawImage(image, x - (image.width / 2), y - (image.height / 2));
ttt.currentPlayer();
};
function render() {
ttt.draw($('#ttt').on("click", ttt.click));
ttt.currentPlayer();
};
(function init() {
render();
})();