October 4, 2022
How-to-Create-a-Simple-JavaScript-Game
Spread the love

JavaScript is generally referred to as scripting or the programming language that usually helps to implement complex features on web pages. Every time a web page displays a piece of static information for you to look at — displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, etc then it is clear that JavaScript is probably involved in all these aspects.

It is also known as the third layer of the layer cake in terms of the standard web technologies that are usually known as HTML (Hyper Text Markup Language) and CSS (Cascading Style Sheets). Nowadays games are the new trend and these are to be created and implemented in terms of trending technologies like JavaScript. Games like Quizzes are made with the help of JavaScript to have better user experiences. There are many companies like web development company in Sydney that can provide the best services in this area.

Make a simple JavaScript quiz includes simple steps like:

  • Setting up the structure of the game
  • Showing the questions
  • On submitting, it should show the results
  • Putting it all together

This can help in getting the simple JavaScript quiz without any external code requirement. Therefore avoiding animations, excessive styles, and various other things will distract from the JavaScript quiz.

Step:1 Set up the Structure

Create divs to hold your quiz and the results.

HTML

Get Results

Add some of the required inputs:

  • The quiz questions
  • A place to put the quiz
  • A place for the results
  • A submit button

The JavaScript Structure

function generateQuiz(questions, quizContainer, resultsContainer, submitButton){

function showQuestions(questions, quizContainer){
    // code will go here
}

function showResults(questions, quizContainer, resultsContainer){
    // code will go here
}

// show the questions
showQuestions(questions, quizContainer);

// when the user clicks submit, show results
submitButton.onclick = function(){
    showResults(questions, quizContainer, resultsContainer);
}

}

Step 2: Showing the Questions

var myQuestions = [
{
question: “What is 10/2?”,
answers: {
a: ‘3’,
b: ‘5’,
c: ‘115’
},
correctAnswer: ‘b’
},
{
question: “What is 30/3?”,
answers: {
a: ‘3’,
b: ‘5’,
c: ’10’
},
correctAnswer: ‘c’
}
];

Next, you need a proper way to show the questions. For this, you need to fill out showQuestions function. For each question, all you need to do is show the question along with all of the answer choices.

function showQuestions(questions, quizContainer){
// we’ll need a place to store the output and the answer choices
var output = [];
var answers;

// for each question...
for(var i=0; i<questions.length; i++){

    // first reset the list of answers
    answers = [];

    // for each available answer to this question...
    for(letter in questions[i].answers){

        // ...add an html radio button
        answers.push(
            '<label>'
                + '<input type="radio" name="question'+i+'" value="'+letter+'">'
                + letter + ': '
                + questions[i].answers[letter]
            + '</label>'
        );
    }

    // add this question and its answers to the output
    output.push(
        '<div class="question">' + questions[i].question + '</div>'
        + '<div class="answers">' + answers.join('') + '</div>'
    );
}

// finally combine our output list into one string of HTML and put it on the page
quizContainer.innerHTML = output.join('');

}

Once all of the things are done, you can therefore run the function.

Step 3: Showing the results On Submission

Fill out the show results function and then you can show the results of the quiz.

The Javascript Logic:
For every question, you need to find the selected answer.
If the answer is correct you then need to respond as per the requirement.
If the answer is wrong then you need to respond accordingly.
Then showing the number of correct answers out of the total.

The JavaScript Code to show the results of the quiz:
function showResults(questions, quizContainer, resultsContainer){

// gather answer containers from our quiz
var answerContainers = quizContainer.querySelectorAll('.answers');

// keep track of user's answers
var userAnswer = '';
var numCorrect = 0;

// for each question...
for(var i=0; i<questions.length; i++){

    // find the selected answer
    userAnswer = (answerContainers[i].querySelector('input[name=question'+i+']:checked')||{}).value;

    // if answer is correct
    if(userAnswer===questions[i].correctAnswer){
        // add to the number of correct answers
        numCorrect++;

        //colour the answers green
        answerContainers[i].style.color = 'lightgreen';
    }
    // if the answer is wrong or blank
    else{
        //colour the answers red
        answerContainers[i].style.color = 'red';
    }
}

// show the number of correct answers out of total
resultsContainer.innerHTML = numCorrect + ' out of ' + questions.length;

}

The next step usually involves showing the quiz results when someone just clicks on the submit button.

// on submit, show results
submitButton.onclick = function(){
showResults(questions, quizContainer, resultsContainer);
}

Step 4: Putting it all together

Now all you need to do is let your JavaScript know what are the HTML elements that are to be used for the quiz, the results, and the submit button.

var quizContainer = document.getElementById(‘quiz’);
var resultsContainer = document.getElementById(‘results’);
var submitButton = document.getElementById(‘submit’);
Now that everything’s in place, you can generate your JavaScript quiz!
generateQuiz(myQuestions, quizContainer, resultsContainer, submitButton);

Also Read: Fundamental Concepts of Content Marketing & Strategy

Leave a Reply

Your email address will not be published.