lundi 29 mai 2023

Why do the buttons on this JavaScript trivia game keep displaying an incorrect answer when the correct answer button was clicked?

I am building a trivia game using vanilla JavaScript and Bootstrap, the app gets questions from the https://opentdb.com API, displays the question and then four multiple choice answers on a separate button using Bootstrap. A simple random loop to generate numbers between 1 and 4 (without repeating) to an array is created to ensure the buttons are shuffled for the next question.

Ever since introducing the nextQuestion function to go to the next question, if I click on the correct answer, that button will not change to "Correct!" and a random "Incorrect" button will show. Before I was just refreshing the page every time to generate another question.

I have tried declaring the rand array globally and under the nextQuestion function to reset it and outputting these numbers to the console to check that are changing. I've noticed that more than often the last correct answer position for the previous question is where the "Incorrect" button is shown.

Please let me know if you need anymore information.

Here is the code:

Main.js

const api_url = 'https://opentdb.com/api.php?amount=1&category=9&type=multiple&encode=url3986';
let score = 0;
let buttonClicked = false; // Variable to track button click state
const delay = 2000; // Delay in milliseconds

// Get questions and answers from API
async function getQuestion() {
    try {
        // Fetch questions from the API
        const response = await fetch(api_url);
        const data = await response.json();
        const { results } = data;

        displayQuestion(results);

    } catch (error) {
        console.log(error);
    }
}

function displayQuestion(results) {
    const question = decodeURIComponent(results[0].question);
    const answer = decodeURIComponent(results[0].correct_answer);
    const incorrect1 = decodeURIComponent(results[0].incorrect_answers[0]);
    const incorrect2 = decodeURIComponent(results[0].incorrect_answers[1]);
    const incorrect3 = decodeURIComponent(results[0].incorrect_answers[2]);

    // Generate random number without duplicates to shuffle position of answer buttons
    randomArray = [];
    let n = [1, 2, 3, 4];
    i = n.length;
    j = 0;

    while (i--) {
        j = Math.floor(Math.random() * (i + 1));
        randomArray.push(n[j]);
        n.splice(j, 1);
    }

    // Display question and answers on separate buttons for user input
    document.getElementById('question').textContent = question;
    document.getElementById(`answer${randomArray[0]}`).textContent = answer;
    document.getElementById(`answer${randomArray[1]}`).textContent = incorrect1;
    document.getElementById(`answer${randomArray[2]}`).textContent = incorrect2;
    document.getElementById(`answer${randomArray[3]}`).textContent = incorrect3;

    // User input for button click
    document.getElementById(`answer${randomArray[0]}`).addEventListener("click", correctAnswer);
    document.getElementById(`answer${randomArray[1]}`).addEventListener("click", incorrectAnswer1);
    document.getElementById(`answer${randomArray[2]}`).addEventListener("click", incorrectAnswer2);
    document.getElementById(`answer${randomArray[3]}`).addEventListener("click", incorrectAnswer3);
}

function correctAnswer() {
    if (buttonClicked) return; // Prevent multiple clicks within the delay period
    buttonClicked = true; // Set button click state to true
    document.getElementById(`answer${randomArray[0]}`).innerHTML = "Correct!";
    document.getElementById(`answer${randomArray[0]}`).className = 'btn btn-success btn-sm';
    // Increment the score
    score++;
    // Update the score display
    updateScore();
    setTimeout(() => {
        nextQuestion();
        buttonClicked = false; // Reset button click state after the delay
      }, delay);
}

function incorrectAnswer1() {
    if (buttonClicked) return; // Prevent multiple clicks within the delay period
    buttonClicked = true; // Set button click state to true
    document.getElementById(`answer${randomArray[1]}`).innerHTML = "Incorrect!";
    document.getElementById(`answer${randomArray[1]}`).className = 'btn btn-danger btn-sm';
    setTimeout(() => {
        nextQuestion();
        buttonClicked = false; // Reset button click state after the delay
      }, delay);
}

function incorrectAnswer2() {
    if (buttonClicked) return; // Prevent multiple clicks within the delay period
    buttonClicked = true; // Set button click state to true
    document.getElementById(`answer${randomArray[2]}`).innerHTML = "Incorrect!";
    document.getElementById(`answer${randomArray[2]}`).className = 'btn btn-danger btn-sm';
    setTimeout(() => {
        nextQuestion();
        buttonClicked = false; // Reset button click state after the delay
      }, delay);
}

function incorrectAnswer3() {
    if (buttonClicked) return; // Prevent multiple clicks within the delay period
    buttonClicked = true; // Set button click state to true
    document.getElementById(`answer${randomArray[3]}`).innerHTML = "Incorrect!";
    document.getElementById(`answer${randomArray[3]}`).className = 'btn btn-danger btn-sm';
    setTimeout(() => {
        nextQuestion();
        buttonClicked = false; // Reset button click state after the delay
      }, delay);
}

// Function to update the score
function updateScore() {
    const scoreElement = document.getElementById('score');
    scoreElement.textContent = `Score: ${score}`;
}

function nextQuestion() {
    // Clear the previous question and answer buttons
    document.getElementById('question').textContent = '';

    // Clear answer buttons' styles and text content
    for (let i = 0; i < randomArray.length; i++) {
      const answerButton = document.getElementById(`answer${randomArray[i]}`);
      answerButton.classList.remove('btn-success', 'btn-danger');
      answerButton.classList.add('btn-primary');
      answerButton.textContent = '';
    }
    getQuestion();
  }

getQuestion();

game.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Trivia Game</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
    <link href="/css/style.css" rel="stylesheet">
</head>
<body>
    <div id="container">
    <div class="text-center font-weight-bold col-8 mx-auto">
        <span id="question"></span>
    </div>
    <div class="d-grid gap-2 col-4 mx-auto">
        <button type="button" class="btn btn-primary btn-sm p-1" id="answer1"></button>
        <button type="button" class="btn btn-primary btn-sm" id="answer2"></button>
        <button type="button" class="btn btn-primary btn-sm" id="answer3"></button>
        <button type="button" class="btn btn-primary btn-sm" id="answer4"></button>
        <div class="text-center" id="score">Score: 0</div>
    </div>
    </div>
    <script src="main.js"></script>
</body>
</html>



Aucun commentaire:

Enregistrer un commentaire