1

我正在努力在画布上创建井字游戏。我目前被困在一个点,我检测到画布上的 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();
})();
4

2 回答 2

3

使用数组跟踪网格位置对您来说不是更容易吗?当您在网格上放置某些东西时,请在数组中分配该位置。这样,您不必想办法从 Canvas 中读取它,您只需在数组中查看即可。这也允许您在需要时从数组中快速重绘画布,例如当屏幕调整大小时......

于 2013-10-07T05:13:51.030 回答
2

要检测单击了哪个字段,请遍历您的 9 个字段并检查单击的位置是否在绘制该字段的区域中。

为了能够做到这一点,请存储字段的状态(位置以及它是否有 X、O 或什么都没有)。您还应该将 9 个字段存储在一个数组中,以便您可以轻松地迭代它们。我会将它存储在一个二维数组(3x3)中。

function Field(x, y) {
    this.x = x;
    this.y = y;
    this.value = null; // Can be null, 'X' or 'O'
}

tic tac toe 字段的初始化:

var fields = [
    [new Field(0,0), new Field(1,0), new Field(2,0)],
    [new Field(0,1), new Field(1,1), new Field(2,1)],
    [new Field(0,2), new Field(1,2), new Field(2,2)]
];

迭代:

for (var y = 0; y <= 2; y++) {
    for (var x = 0; x <= 2; x++) {
        var field = fields[y][x];
        // Do something with the field.
    }
}

我会用模型坐标存储字段的位置。因此,您将坐标乘以一个值以获得在画布上绘图的坐标。

于 2013-10-07T06:39:13.853 回答