NotSoSure
NotSoSure

Reputation: 117

How can I toggle same Event listener to Two different function?

I am making one game which can be played by two players so if one player finish with his turn same event listener should attach to the player tow but it's not toggling between two players.

In my code I made one variable 'changeTurn' which stores the boolean value of the player turns if true then player one turn and if false player two turn. but in if condition changeTurn value is false still it executes the 'If(changeTurn === true)' which should not execute. can someone help me with that please why it do like that?

GAME RULES:

- The game has 2 players, playing in rounds
- In each turn, a player rolls a dice as many times as he whishes. Each 
  result get added to his ROUND score
- BUT, if the player rolls a 1, all his ROUND score gets lost. After that, 
  it's the next player's turn
- The player can choose to 'Hold', which means that his ROUND score gets 
  added to his GLBAL score. After that, it's the next player's turn
- The first player to reach 100 points on GLOBAL score wins the game.

*/

const rollDice = document.querySelector('.btn-roll');
const diceImage = document.querySelector('.dice');
const hold = document.querySelector('.btn-hold');
const newGame = document.querySelector('.btn-new');

let changeTurn = true;
let randomNumber = 0;
let loop = true;

let totalScore = 0;
document.querySelector('#score-0').textContent = totalScore;
document.querySelector('#score-1').textContent = totalScore;


let currentScore = 0;
document.querySelector('#current-0').textContent = currentScore;
document.querySelector('#current-1').textContent = currentScore;

//while(loop){

  //newGame.addEventListener('click',function(){
 //   loop = false;
  //})

  if(changeTurn){
    rollDice.addEventListener('click',function(){
      randomNumber = Math.floor((Math.random()*6)+1);

      for(i = 1; i <=6 ; i++){            // selecting image by changing src name
        console.log(randomNumber);
        if(randomNumber === i ){
          diceImage.setAttribute('src',`dice-${i}.png`);
          break;
        }
      }
      currentScore += randomNumber;
      document.querySelector('#current-0').textContent = currentScore; // adding current score to player-1
    
      if(randomNumber === 1){
        document.querySelector('#current-0').textContent = 0;  //reseting player-1 current score cotent to 0
        currentScore = 0;                                      //reseting current score variable to 0
        changeTurn = false;
      }
      
    })

    hold.addEventListener('click',function(){
      totalScore += currentScore;                                  // adding total score to toatal variable
      document.querySelector('#score-0').textContent = totalScore; // adding total to score content
      document.querySelector('#current-0').textContent = 0;        // reseting current score content to 0
      currentScore = 0;      // resetting current score variable
      changeTurn = false;   //changning turn
    })
  }
//============================================================================
  if(!changeTurn){
    rollDice.addEventListener('click',function(){
      randomNumber = Math.floor((Math.random()*6)+1);

      for(i = 1; i <=6 ; i++){            // selecting image by changing src name
        console.log(randomNumber);
        if(randomNumber === i ){
          diceImage.setAttribute('src',`dice-${i}.png`);
          break;
        }
      }
      currentScore += randomNumber;
      document.querySelector('#current-1').textContent = currentScore;
    
      if(randomNumber === 1){
        document.querySelector('#current-1').textContent = 0;
        currentScore = 0;
        changeTurn = true;
      }
      
    })

    hold.addEventListener('click',function(){
      console.log('hi')
      totalScore += currentScore;
      document.querySelector('#score-1').textContent = totalScore;
      document.querySelector('#current-1').textContent = 0;
      currentScore = 0;
      changeTurn = true;
    })
  }

Upvotes: 1

Views: 173

Answers (1)

varun agarwal
varun agarwal

Reputation: 1509

The problem is that you have a check during setting the event listener, but the callback of the event listener is not making any checks, hence both the events are triggered. You could change it to:

rollDice.addEventListener('click',function(){
  randomNumber = Math.floor((Math.random()*6)+1);

  for(i = 1; i <=6 ; i++){            // selecting image by changing src name
    console.log(randomNumber);
    if(randomNumber === i ){
      diceImage.setAttribute('src',`dice-${i}.png`);
      break;
    }
  }
  var id = changeTurn? 0: 1;
  currentScore += randomNumber;
  document.querySelector(`#current-${id}`).textContent = currentScore; // adding current score to player-1

  if(randomNumber === 1){
    document.querySelector(`#current-${id}`).textContent = 0;  //reseting player-1 current score content to 0
    currentScore = 0;                                      //reseting current score variable to 0
    changeTurn = !changeTurn;
  }

})

hold.addEventListener('click',function(){
  var id = changeTurn? 0: 1;
  totalScore += currentScore;                                  // adding total score to total variable
  document.querySelector(`#score-${id}`).textContent = totalScore; // adding total to score content
  document.querySelector(`#current-${id}`).textContent = 0;        // reseting current score content to 0
  currentScore = 0;      // resetting current score variable
  changeTurn = !changeTurn;   //changing turn
})

Upvotes: 1

Related Questions