javascript - How to detect if an object is at cordinates on canvas element? -
i'm working on creating tic-tac-toe game in canvas. i'm stuck @ point detect if there symbol(x or o) @ x/y cordinates on canvas.
i tried using imagedata check if element present returns error if nothing there. thought perhaps assign id square or symbol. doesn't seem possible i've read.
any appreciated.
you can see game running here 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 ' + symbol + '\'s turn'); }; // draw 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; }; // center of 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 clicked box has symbol ttt.prototype.check = function(row, column) { }; // cordinates , 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(); })();
to detect field clicked, iterate through 9 fields , check if clicked position in area field drawn.
to able this, store state of fields (position , if has x, o or nothing in it). should store 9 fields in array, can iterate on them. store in 2 dimensional array (3x3).
function field(x, y) { this.x = x; this.y = y; this.value = null; // can null, 'x' or 'o' }
initialisation of tic tac toe field:
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)] ];
iteration:
for (var y = 0; y <= 2; y++) { (var x = 0; x <= 2; x++) { var field = fields[y][x]; // field. } }
i store position of fields model coordinates. multiply coordinates value coordinates drawing on canvas.
Comments
Post a Comment