jeudi 29 août 2019

Variable in a function stored in global variable

This is a dice game where you get random number when 'rolling' the dice, the point are accumulated until you get 1, then you start again with 0 points (nextPlayer function is called). The challenge was to add if else statement when you roll 6 two times in a row - you start again.

this is the solution: dice is the random number(Internal variable), lastDice is the previous rolled number of points, so that it can be compared. So the previous roll has to be saved in a separate GLOBAL variable.

Why does the lastDice has to be global and why does it retain the previous roll if there's the statement lastDice = dice?

var lastDice

function() {
   if(gamePlaying) { 
     var dice = Math.floor(Math.random() * 6) + 1; 

   IF the rolled nr was NOT = 1, update score

   if (dice === 6 && lastDice === 6){
     scores = 0;
     nextPlayer(); 

   } else if (dice !== 1) {
     roundScore += dice;

   } else {
       nextPlayer();
   }

   lastDice = dice
}

});

Aucun commentaire:

Enregistrer un commentaire