Skip to content Skip to sidebar Skip to footer

How Do I Create Turns In A Tic Tac Toe Game?

Sorry if this is really obvious. I am pretty new to JavaScript. I have had to create a basic X game . Here is the HTML code.

Solution 1:

you need a variable for it

var nextTurn = 'X'

at the top

then something like:

if (this.id == "cell1")
 {
      if(document.getElementById("cell1").innerHTML == ""){ 
           document.getElementById("cell1").innerHTML = nextTurn;
           changeTurn();
      }
 }  

etc

function changeTurn(){
      if(nextTurn == 'X'){
           nextTurn = 'O';
      } else {
           nextTurn = 'X';
      }
 }

Solution 2:

I have cleaned up your code a bit:

<!DOCTYPE html><html><head><metacontent="text/html; charset=UTF-8"http-equiv="content-type"><title>Example</title><styletype="text/css">td{width:20px;height:20px;text-align: center;vertical-align: middle;}
</style></head><body><tableborder="1"cellpadding="5"><tbody><tr><td ></td><td ></td><td ></td></tr><tr><td ></td><td ></td><td ></td></tr><tr><td ></td><td ></td><td ></td></tr></tbody></table><scripttype="text/javascript">//IE 8 and below doesn't have String.trim() so have to add itif(!String.prototype.trim){
    String.prototype.trim=function(){
        returnthis.replace(/^[\s]*[\s]*$/igm,"");
    }
}
var game={
    currentPlayer:"X",
     move:function(e){
        e=window.event||e;//IE uses window.eventvar src=e.target||e.srcElement;
        if(src.tagName==="TD"&&src.innerHTML.trim()===""){
            src.innerHTML=game.currentPlayer;
            game.currentPlayer=(game.currentPlayer==="X")?"O":"X";
        }
    }
}

var table=document.body.getElementsByTagName("table")[0];
if(typeof table.addEventListener==="function"){
    table.addEventListener("click",game.move);
}elseif(typeof table.attachEvent){
    //for IE
    table.attachEvent("onclick", game.move);
}
</script></body></html>

Post a Comment for "How Do I Create Turns In A Tic Tac Toe Game?"