dimanche 23 octobre 2016

How to make an if/else statement loop?

I'm new to Javascript, so I'm not sure if I'm asking the right question here. But I have 6 elements - 6 trees, that a user can click on and then they disappear. After all of them have disappeared, I want something else to happen. But since I don't know what order the user will click them in (and I haven't really learned that much about JS yet) I thought that an if/else statement asking if there's only 0 trees left, then call a new function.

Unfortunately I cannot seem to get it to work, I don't know if I'm writing it the wrong way or placing it the wrong place or just doing it wrong, but it seems like it gives a false result already in the beginning, since the user hasn't clicked on anything yet. So how do I make it run in a loop and check how many trees are left several times?

Sorry the code is a bit long, but I'm not really sure how to optimise it and make it shorter just yet.

var TreesLeft = 6;
function TreeGoneOnClick(){
console.log("TreeGoneOnClick");
    BigTrees.classList.add("flash");
//click each tree
    tree1.addEventListener("click", tree1Clicked);
    tree2.addEventListener("click", tree2Clicked);
    tree3.addEventListener("click", tree3Clicked);
    tree4.addEventListener("click", tree4Clicked);
    tree5.addEventListener("click", tree5Clicked);
    tree6.addEventListener("click", tree6Clicked);

ifelse();
}

function tree1Clicked (){
    console.log("tree1 clicked");
    TreesLeft-=1;
    tree1.classList.remove("tree1S");
}

function tree2Clicked (){
    console.log("tree2 clicked");
    TreesLeft-=1;
    tree2.classList.remove("tree2S");
}

function tree3Clicked (){
    console.log("tree3 clicked");
    TreesLeft-=1;
    tree3.classList.remove("tree3S");
}

function tree4Clicked (){
    console.log("tree4 clicked");
    TreesLeft=TreesLeft-1;
    tree4.classList.remove("tree4S");
}

function tree5Clicked (){
    console.log("tree5 clicked");
    TreesLeft-=1;
    tree5.classList.remove("tree5S");
}

function tree6Clicked (){
    console.log("tree6 clicked");
    TreesLeft-=1;
    tree6.classList.remove("tree6S");
}



function ifelse(){
    if (TreesLeft ==0){
    console.log("it worked");
     allTreesGone();
     }
    else {
    console.log("did not work");
    }
  }


 function allTreesGone (){
   console.log("All trees are gone");
 }   

Aucun commentaire:

Enregistrer un commentaire