dimanche 25 juillet 2021

'Bounce' in if else statement causing alert box to pop up more than once

I am designing a quiz that generates the question & answers dynamically each time, I have written an if else statement to check if the answer is right but something isn't quite right. The increment score function doesn't work properly as random numbers are added and the alert box pops up more than once. It seems there is a bounce within the function but I can't figure out what it is.

// Game controls

const startButton = document.getElementById('start-button');
const quitButton = document.getElementById('quit-button');
const mainHeading = document.getElementById('main-heading');
const gameContainer = document.getElementById('game-container');
const scoreOutput = document.getElementById('score-total');
var questionCountOutput = document.getElementById('question-count');
const randomQuestion = document.getElementById('random-question');


let currentScore = 0;
let questionCount = 0;

startButton.addEventListener('click', startGame);
quitButton.addEventListener('click', quitGame);
randomQuestion.addEventListener('click', getRandomQuestion);

const maxQuestions = 10;
const scoreValue = 20;

// Start game
function startGame(event) {
  startButton.classList.add('hidden')
  mainHeading.classList.add('hidden')
  gameContainer.classList.remove('hidden')
  questionCount = 0;
  currentScore = 0;
  generateQuestion()
};

// Quit Game
function quitGame(event) {
  if (window.confirm('Are you sure you want to quit?')) {
    gameContainer.classList.add('hidden')
    startButton.classList.remove('hidden')
  }
};
// Generates the questions    
function generateQuestion() {

  // Increment question count by 1 each time
  questionCount++;
  questionCountOutput.innerText = `${questionCount}`;
  // variables to help generate question
  let countriesCount = countriesList.length;
  let randomNumber = getRandomInt(0, countriesCount);
  let chosenCountry = (countriesList[randomNumber].country); // Generate random country from array 
  let correctAnswer = (countriesList[randomNumber].capital); // Generate the correct capital city from array 

  // Define correct answer
  let isCorrectQuestionAnswer = {
    question: chosenCountry,
    option: correctAnswer
  };


  // Generate 3 random cities from capitalListOptions to act as other answer options
  let answerOption1 = (countriesList[getRandomInt(0, countriesList.length)].capital);
  let answerOption2 = (countriesList[getRandomInt(0, countriesList.length)].capital);
  let answerOption3 = (countriesList[getRandomInt(0, countriesList.length)].capital);
  // define option outputs to loop through
  let optionOutputs = [{
      'question': chosenCountry,
      'option': correctAnswer
    },
    {
      'question': chosenCountry,
      'option': answerOption1
    },
    {
      'question': chosenCountry,
      'option': answerOption2
    },
    {
      'question': chosenCountry,
      'option': answerOption3
    }
  ];

  // Randomise the outputs so the correct answer isn't in the same place all the time 
  randomOptionOutputs = optionOutputs.sort(() => Math.random() - 0.5);
  let buttonOutputs = '';
  let i = 0;

  // Loop through the options and retrieve their key values
  //add key values to as button attributes
  Object.keys(randomOptionOutputs).forEach(function(key) {
    // Code to define the html for the buttons 
    buttonOutputs += '<button id="answer-' + i + '" data-answer="' + randomOptionOutputs[key]['option'] + '" data-country="' + randomOptionOutputs[key]['question'] + '" class="answer-btn" >' + randomOptionOutputs[key]['option'] + '</button>';
    i++;
  });

  // Create the answer buttons and the questionText
  document.getElementById('country-name').innerHTML = chosenCountry;
  document.getElementById('answers-container').innerHTML = buttonOutputs;

  // Loop through the buttons that have been created and add event listeners to them
  for (let i = 0; i < 4; i++) {
    document.getElementById("answer-" + i).addEventListener("click", function() {
      checkAnswer(isCorrectQuestionAnswer)
    });

  };
};

// Generate random number to use as array index to generate questions and answers 
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
};

// Checks if the answer selected is right, increments the score if it is, then moves on the to the next question
function checkAnswer(isCorrectQuestionAnswer) {
  //  Using a jquery method, retrieve the data-answer for the button clicked and compare this with the isCorrectQuestionAnswer object 'option'
  $(document).on('click', '.answer-btn', function() {
    var clickedButtonAnswer = $(this).data('answer');
    // var clickedButtonQuestion = $(this).data('country');
    if ((clickedButtonAnswer === isCorrectQuestionAnswer["option"])) {
      $(this).addClass("correct");
      incrementScore(scoreValue);
      alert('Well done!!! You got that right');
      generateQuestion();
      return
    } else {
      $(this).addClass("incorrect");
      alert("Ahhh that wasn't quite right - no worries, you'll get it next time!");
      generateQuestion();
      return
    };
  });

};


// function to increment the score with each new question 
function incrementScore(num) {
  currentScore += num;
  scoreOutput.innerText = `${currentScore}`;
};

Aucun commentaire:

Enregistrer un commentaire