dimanche 18 juin 2017

Refactoring code to evaluate multiple button clicks for a quiz in JQuery without evaluating each separate button in the function

I'm working on a trivia game in jQuery where I produce a question and then 4 buttons with options for the user to click as their guess, then it'll tell you whether or not the answer is correct. I'm trying to refactor the code, I have a working version of it already, but to check the answers in that working version I have a function with an if statement evaluating each separate button click that'll log a correct answer if the answer is equal to the index of the choice associated with that particular button, so basically it's the same function with the same exact text, the only thing different is the button we're evaluating each time.

I figure I can cut about 70 lines of code out of the file by changing this but I can't wrap my head around how to do this, wondering if anyone can help explain to me how?

Here's what I have so far in the new version, there's a comment above the line I'm having trouble with which is the last function, right now i have it reading as if the first choice in the questions object is the zero index, then it'll be true, i basically had this same thing in my original version 3 different times for indexes 1, 2 and 3 also, which made it a lot of redundant code. I'm thinking maybe I need to do something with assigning a data attribute to each button in the html and maybe something with $(this).attr() in the JQuery but I dont know, I'm struggling and this is still really new to me!

Here's the HTML:

<html>

<head>
    <!-- jQuery CDN-->
    <script src="http://ift.tt/2nYZfvi"></script>
    <!-- Bootstrap CDN -->
    <link href="http://ift.tt/2apRjw3" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!-- Google Fonts Stylesheets -->
    <link href="http://ift.tt/2ibTSC4" rel="stylesheet">
    <link href="http://ift.tt/1RAwgm4" rel="stylesheet">
    <link href="http://ift.tt/2sGZFsU" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="assets/css/trivia-game.css">
    <title>Trivia Game</title>
</head>

<body>
    <div class="jumbotron">
        <div class="text-center">
            <!-- Correct answer section -->
            <div class="col-lg-4 text-center" id="correct-answers">
                <ul>
                    <li class="block-font">CORRECT ANSWERS:</li>
                    <h1><li class="block-font" id="correct"></li></h1>
                </ul>
            </div>
            <!-- Start game section -->
            <div class="col-lg-4">
                <img src="assets/images/nfl.png" height="75px">
                <h1 class="line-height block-font" style="margin-bottom: .25em">Trivia Game</h1>
                <button id="reset-game" class="btn btn-danger text-center">
                    <span class="glyphicon glyphicon-flash"></span> Reset Game!</button>
            </div>
            <!-- Incorrect answer section -->
            <div class="col-lg-4 text-center" id="incorrect-answers">
                <ul>
                    <li class="block-font">INCORRECT ANSWERS:</li>
                    <h1><li class="block-font" id="incorrect"></li></h1>
                </ul>
            </div>
        </div>
    </div>
    <nav class="text-center">TIME LEFT:
        <br>
        <span id="timer"></span></nav>
    <div class="container-fluid">
        <div class="row">

            <!-- Main Section holding the games content -->
            <div class="col-lg-6 col-lg-offset-3 text-center" id="main-section">
                <h1 style="font-family: 'Rajdhani', sans-serif;
">Question</h1>
                <hr>
                <h2 id="question"></h2>
                <button id="btn-one" class="btn btn-success text-center choice"><span id="answer-one"></span></button>
                <br>
                <button id="btn-two" class="btn btn-success text-center choice"><span id="answer-two"></span></button>
                <br>
                <button id="btn-three" class="btn btn-success text-center choice"><span id="answer-three"></span></button>
                <br>
                <button id="btn-four" class="btn btn-success text-center choice"><span id="answer-four"></span></button>
                <h2><span id="message"></span></h2>
            </div>
        </div>
    </div>
    <script type="text/javascript" src="assets/javascript/original1.js">
    </script>
</body>

</html>

Here's the JS I'm working on:

var timerId = setInterval(timer, 1000);

var incorrectAnswers = 0;

var correctAnswers = 0;

var objectIndex = 0;

var questions = [{
    question: "What player has the record for most receiving yards in a season?",
    choices: ["Jerry Rice", "Randy Moss", "Calvin Johnson", "Tim Brown"],
    answer: "Calvin Johnson"
}, 
{
    question: "Which quarterback played in two Superbowls on two different teams within the same division?",
    choices: ["Peyton Manning", "Kurt Warner", "Tom Brady", "Eli Manning"],
    answer: "Kurt Warner"
}, 
{
    question: "Which team won the 1995 Super Bowl?",
    choices: ["Dallas Cowboys", "San Francisco 49ers", "New York Giants", "Pittsburgh Steelers"],
    answer: "San Francisco 49ers"
}, 
{
    question: "Who is the all-time leader in rushing yards in the NFL?",
    choices: ["Barry Sanders", "Walter Payton", "Curtis Martin", "Emmitt Smith"],
    answer: "Emmitt Smith"
}, 
{
    question: "What is the rookie record for receving touchdowns?",
    choices: ["10", "17", "12", "8"],
    answer: "17"
}, 
{
    question: "Who intercepted Russell Wilson to defeat the Seahawks in Super Bowl?",
    choices: ["Darrelle Revis", "Ty Law", "Malcolm Butler", "Richard Sherman"],
    answer: "Malcolm Butler"
}, 
{
    question: "Which of these teams cameback from the largest playoff deficit in NFL history to win the game?",
    choices: ["New England Patriots", "Buffalo Bills", "Indianapolis Colts", "San Francisco 49ers"],
    answer: "Buffalo Bills"
}, {
    question: "Which of these teams has never reached the Super Bowl?",
    choices: ["Carolina Panthers", "Jacksonville Jaguars", "Cincinnati Bengals", "Arizona Cardinals"],
    answer: "Jacksonville Jaguars"
}, 
{
    question: "Who has the most wins as a head coach in the NFL?",
    choices: ["Don Shula", "Tom Landry", "Vince Lombardi", "Bill Belichick"],
    answer: "Don Shula"
}, 
{
    question: "Which player kicked the longest field goal in NFL history?",
    choices: ["David Akers", "Sebastian Janikowski", "Jason Elam", "Matt Prater"],
    answer: "Matt Prater"
}];


writeInitialScore();

writeQuestionAndChoices();

resetGame();

checkAnswer();


function writeInitialScore() {
    $("#correct").html(correctAnswers);
    $("#incorrect").html(incorrectAnswers);
};


function resetGame() {
    $('#reset-game').click(function() {
        window.location.reload();
    })
}


function timer() {
    if (timeLeft === 0) {
        clearInterval(timerId)
        incorrectAnswers++
        $('#incorrect').html(incorrectAnswers)
        $('#message').html('<h2><font color="red"><font color="red">Times up! The answer was ' + questions[objectIndex].answer + '!')
        objectIndex++
        setTimeout(writeQuestionAndChoices, 1500)
        displayFinalScore();
    } else {
        $('#timer').html(timeLeft + ' seconds');
        timeLeft--;
    }
}


function writeQuestionAndChoices() {
    timeLeft = 20;
    $('#message').empty();
    $('#question').html(questions[objectIndex].question);
    $('#answer-one').html(questions[objectIndex].choices[0]);
    $('#answer-two').html(questions[objectIndex].choices[1]);
    $('#answer-three').html(questions[objectIndex].choices[2]);
    $('#answer-four').html(questions[objectIndex].choices[3]);

    clearInterval(timerId)
    timerId = setInterval(timer, 1000);

    if (objectIndex >= questions.length) {
        displayFinalScore();
    }

    if (timeLeft === 0) {
        objectIndex++
    }
}

 var choiceIndex = 0


function displayFinalScore() {
    if (correctAnswers + incorrectAnswers === questions.length) {
        $("#main-section").html('<h2 style="margin-top: 9em; color: black;">You answered ' + correctAnswers + ' out of ' + questions.length + ' correctly for a final score of ' + ((correctAnswers / questions.length) * 100) + '%! Press the reset button to play again!')
    }
}

//This is where we'll check the answers, having trouble here with the condition in the if statement
function checkAnswer() {
    $('#main-section').on('click', 'button', function() {
        if (questions[objectIndex].answer === questions[objectIndex].choices[0]) {
            clearInterval(timerId);
            correctAnswers++
            $('#correct').html(correctAnswers)
            $('#message').html('<h2 style="color: green;">That\'s correct, the answer was ' + questions[objectIndex].answer + ', good job!');

        } else {
            clearInterval(timerId);
            incorrectAnswers++
            $('#incorrect').html(incorrectAnswers)
            $('#message').html('<h2 style="color: red;"><font color="red">Incorrect! The answer was ' + questions[objectIndex].answer + '!');
        }

        objectIndex++
        setTimeout(writeQuestionAndChoices, 2000);
        setTimeout(displayFinalScore, 5000);
        timer();

    })
}

Here's the JS for the function to check the answer that works but its done by selecting the id of each button and evaluating each button with a ton of code:

function checkAnswer() {
$('#btn-one').on('click', function() {
    if (questions[objectIndex].answer === questions[objectIndex].choices[0]) {
        clearInterval(timerId);
        correctAnswers++
        $('#correct').html(correctAnswers)
        $('#message').html('<h2><font color="green">That\'s correct, the answer was ' + questions[objectIndex].answer + ', good job!');

    } else {
        clearInterval(timerId);
        incorrectAnswers++
        $('#incorrect').html(incorrectAnswers)
        $('#message').html('<h2><font color="red"><font color="red">Incorrect! The answer was ' + questions[objectIndex].answer + '!');
    }

    objectIndex++
    setTimeout(writeQuestionAndChoices, 2000);
    setTimeout(displayFinalScore, 5000);
    timer();

})


$('#btn-two').on('click', function() {
    if (questions[objectIndex].answer === questions[objectIndex].choices[1]) {
        clearInterval(timerId);
        correctAnswers++
        $('#correct').html(correctAnswers)
        $('#message').html('<h2><font color="green">That\'s correct, the answer was ' + questions[objectIndex].answer + ', good job!');

    } else {
        clearInterval(timerId);
        incorrectAnswers++
        $('#incorrect').html(incorrectAnswers)
        $('#message').html('<h2><font color="red">Incorrect! The answer was ' + questions[objectIndex].answer + '!');
    }

    objectIndex++
    setTimeout(writeQuestionAndChoices, 2000);
    setTimeout(displayFinalScore, 5000);
    timer();

})


$('#btn-three').on('click', function() {
    if (questions[objectIndex].answer === questions[objectIndex].choices[2]) {
        clearInterval(timerId);
        correctAnswers++
        $('#correct').html(correctAnswers)
        $('#message').html('<h2><font color="green">That\'s correct, the answer was ' + questions[objectIndex].answer + ', good job!');

    } else {
        clearInterval(timerId);
        incorrectAnswers++
        $('#incorrect').html(incorrectAnswers)
        $('#message').html('<h2><font color="red">Incorrect! The answer was ' + questions[objectIndex].answer + '!');
    }

    objectIndex++
    setTimeout(writeQuestionAndChoices, 2000);
    setTimeout(displayFinalScore, 5000);
    timer();

})


$('#btn-four').on('click', function() {
    if (questions[objectIndex].answer === questions[objectIndex].choices[3]) {
        clearInterval(timerId);
        correctAnswers++
        $('#correct').html(correctAnswers)
        $('#message').html('<h2><font color="green">That\'s correct, the answer was ' + questions[objectIndex].answer + ', good job!');

    } else {
        clearInterval(timerId);
        incorrectAnswers++
        $('#incorrect').html(incorrectAnswers)
        $('#message').html('<h2><font color="red">Incorrect! The answer was ' + questions[objectIndex].answer + '!');
    }

    objectIndex++
    setTimeout(writeQuestionAndChoices, 2000);
    setTimeout(displayFinalScore, 5000);
    timer();

})

}

Aucun commentaire:

Enregistrer un commentaire