PDA

View Full Version : onclick turns for tic tac toe



xrhstos
04-27-2012, 04:16 PM
Hello all and thank you for reading this. I am trying to start tic tac toe but I dont know how to turn the onclick events displaying X and O. Please I would like some advice or help thank you very much all. this is my code.in the code below X is only displayed on my table and I dont know how to give turns :( plz help me.


function tableclick()
{
this.innerHTML = "X";

}

for (var i=1; i<10; i++)
{
document.getElementById("cell"+i).onclick = tableclick;
}

jscheuer1
04-27-2012, 09:40 PM
function tableclick(){
this.innerHTML = tableclick.token;
tableclick.token = tableclick.token === 'X'? 'O' : 'X';
}
tableclick.token = 'X';

for(var i = 1; i < 10; ++i){
document.getElementById('cell' + i).onclick = tableclick;
}

xrhstos
04-28-2012, 12:37 PM
I would like to thank you for your code it worked perfectly but what I did I added a global variable to my code giving the value of X and then I added an IF statement to give the turns ! I am a bit concerned of how to stop overwriting the boxes when they are marked so to only allow the move only if the box("-") has neither of X or O could you help me on that ?

Many thanks!

jscheuer1
04-28-2012, 07:25 PM
In general, due to possible conflicts with other scripts that might be added later, it's a good idea to limit the global exposure of variable and function names. With this code, no global exposure is required, but that would make it a little more complicated. To add the feature you requested, add the highlighted as shown:


function tableclick(){
this.innerHTML = tableclick.token;
tableclick.token = tableclick.token === 'X'? 'O' : 'X';
this.onclick = function(){return;};
}
tableclick.token = 'X';

for(var i = 1; i < 10; ++i){
document.getElementById('cell' + i).onclick = tableclick;
}

To remove all global exposure:


;(function(){
function tableclick(){
this.innerHTML = tableclick.token;
tableclick.token = tableclick.token === 'X'? 'O' : 'X';
this.onclick = function(){return;};
}
tableclick.token = 'X';

for(var i = 1; i < 10; ++i){
document.getElementById('cell' + i).onclick = tableclick;
}
})();