An Introduction To HTML Games: The Best Guide

HTML stands for HyperText Markup Language. It is the most widely used and popular language for web application development. Created by Berners-Lee in 1991, but first published in 1995. HTML has gone through multiple versions over the years. HTML 4 was a popular breakthrough version that was published in the year 1999. HTML 4 garnered a lot of attention and saw quick and widespread adoption all over the globe for web application development. HTML 5 is the current version of the programming language and was published in the year 2012.

In this HTML Games article, we focus on the practical aspect of HTML, along with CSS and JavaScript in real-world applications. Since we also work with CSS and JavaScript to develop the game, you can consider them a prerequisite for this article.

In this article, you will code along with us an HTML Game - QUIZ using the three main languages in web development, namely, HTML, CSS, and JavaScript. So without further ado, let’s get started!

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Project Directory

The Project Directory should look like the image attached below, in the end.

html-quiz

Fig: Project Directory

index.html

This file contains all the HTML codes that we need for this game. Later on, we add CSS and JavaScript to be able to interact with the game and also to make it look good.

<!DOCTYPE html>

<html lang="en">

  <head>

    <meta charset="UTF-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <meta http-equiv="X-UA-Compatible" content="ie=edge" />

    <link href="styles.css" rel="stylesheet" />

    <title>HTML Game - Quiz</title>

  </head>

  <body>

    <div class="container">

      <div id="question-container" class="hide">

        <div id="question">Question</div>

        <div id="answer-buttons" class="btn-grid">

          <button class="btn">Answer 1</button>

          <button class="btn">Answer 2</button>

          <button class="btn">Answer 3</button>

          <button class="btn">Answer 4</button>

        </div>

      </div>

      <div class="controls">

        <button id="start-btn" class="start-btn btn">Start</button>

        <button id="next-btn" class="next-btn btn hide">Next</button>

      </div>

    </div>

    <script src="script.js"></script>

  </body>

</html>

  • This file contains the basic HTML boilerplate code.
  • Import CSS stylesheet inside the head tag.
  • The title of the game, as usual, is defined within the head tag.
  • The layout of the web page is within the body tag.
  • We are using div tags to be able to add styles and layouts to HTML elements.
  • Note that most elements have a class or an id to identify those elements when working with JavaScript and CSS.
  • Import the javascript file in the end, within the body tag.
Get skilled in HTML5 and CSS3 with the Full Stack Java Developer Master's Program. Click to check out the program details! 

script.js

This file includes the code that makes the game work. Let’s go through the code and understand what each snippet of the code is for.

const startButton = document.getElementById("start-btn");

const nextButton = document.getElementById("next-btn");

const questionContainerElement = document.getElementById("question-container");

const questionElement = document.getElementById("question");

const answerButtonsElement = document.getElementById("answer-buttons");

let shuffledQuestions, currentQuestionIndex;

startButton.addEventListener("click", startGame);

nextButton.addEventListener("click", () => {

  currentQuestionIndex++;

  setNextQuestion();

});

function startGame() {

  startButton.classList.add("hide");

  shuffledQuestions = questions.sort(() => Math.random() - 0.5);

  currentQuestionIndex = 0;

  questionContainerElement.classList.remove("hide");

  setNextQuestion();

}

function setNextQuestion() {

  resetState();

  showQuestion(shuffledQuestions[currentQuestionIndex]);

}

function showQuestion(question) {

  questionElement.innerText = question.question;

  question.answers.forEach((answer) => {

    const button = document.createElement("button");

    button.innerText = answer.text;

    button.classList.add("btn");

    if (answer.correct) {

      button.dataset.correct = answer.correct;

    }

    button.addEventListener("click", selectAnswer);

    answerButtonsElement.appendChild(button);

  });

}

function resetState() {

  clearStatusClass(document.body);

  nextButton.classList.add("hide");

  while (answerButtonsElement.firstChild) {

    answerButtonsElement.removeChild(answerButtonsElement.firstChild);

  }

}

function selectAnswer(e) {

  const selectedButton = e.target;

  const correct = selectedButton.dataset.correct;

  setStatusClass(document.body, correct);

  Array.from(answerButtonsElement.children).forEach((button) => {

    setStatusClass(button, button.dataset.correct);

  });

  if (shuffledQuestions.length > currentQuestionIndex + 1) {

    nextButton.classList.remove("hide");

  } else {

    startButton.innerText = "Restart";

    startButton.classList.remove("hide");

  }

}

function setStatusClass(element, correct) {

  clearStatusClass(element);

  if (correct) {

    element.classList.add("correct");

  } else {

    element.classList.add("wrong");

  }

}

function clearStatusClass(element) {

  element.classList.remove("correct");

  element.classList.remove("wrong");

}

const questions = [

  {

    question: "Which one of these is a JavaScript framework?",

    answers: [

      { text: "Python", correct: false },

      { text: "Django", correct: false },

      { text: "React", correct: true },

      { text: "Eclipse", correct: false },

    ],

  },

  {

    question: "Who is the prime minister of India?",

    answers: [

      { text: "Narendra Modi", correct: true },

      { text: "Rahul Gandhi", correct: false },

    ],

  },

  {

    question: "Which one of these is used for mobile app development?",

    answers: [

      { text: "Flask", correct: false },

      { text: "Flutter", correct: true }

    ],

  },

 

  {

    question: "What is 4 * 3?",

    answers: [

      { text: "6", correct: false },

      { text: "12", correct: true },

    ],

  },

];

  • We declare all the variables that we will be needing in the game and set a default value.
  • We then add event listeners to the buttons to make them functional.
  • We define a function ‚ÄėstartGame()‚Äô that is attached to the Start button in the game:
    • On pressing the button, questions appear on the screen with answer choices.
    • Every time the game is restarted, questions get shuffled.
  • We define a function ‚ÄėsetNextQuestion()‚Äô that performs the following operations:
    • Calls the ‚ÄėresetState()‚Äô function.
    • Calls the ‚ÄėshowQuestion()‚Äô function with the shuffled question as to the parameter.
  • We define a function ‚ÄėshowQuestion()‚Äô that takes in a question as a parameter and displays it on-screen.
    • Creates the answer buttons depending on the number of choices for each question.
  • We define a function ‚ÄėresetState()‚Äô that performs the following operations:
    • Calls ‚ÄėclearStatusClass()‚Äô function.¬†
    • Hides the ‚ÄėNext‚Äô button until the answer is selected for a particular question.¬†
  • We define a function ‚ÄėselectAnswer()‚Äô‚Äô that takes in the click event as the parameter:
    • Sets the selected button that was clicked by the user.
    • If the user has reached the end of all the questions, the restart button is displayed.
    • Displays the relevant output according to the user‚Äôs choice.
  • We define a function ‚ÄėsetStatusClass()‚Äô that sets the status of the question, whether the answer is true or not according to the user‚Äôs choice.
  • We then define a function ‚ÄėclearStatusClass()‚Äô that, as the name suggests, clears the status of the question.
    • We define the color of the shape.
    • Then, we define the cell dimensions.
    • Lastly, we define a list of questions and answers that we want to keep in this Quiz.

    styles.css

    This file contains the code that we use to stylize the elements of the HTML Quiz game. Let’s go through the stylesheet and understand all the styles applied to this project.

    *,

    *::before,

    *::after {

      box-sizing: border-box;

      font-family: Gotham Black;

    }

    :root {

      --hue-neutral: 200;

      --hue-wrong: 0;

      --hue-correct: 145;

    }

    body {

      --hue: var(--hue-neutral);

      padding: 0;

      margin: 0;

      display: flex;

      width: 100vw;

      height: 100vh;

      justify-content: center;

      align-items: center;

      background-color: hsl(var(--hue), 100%, 20%);

    }

    body.correct {

      --hue: var(--hue-correct);

    }

    body.wrong {

      --hue: var(--hue-wrong);

    }

    .container {

      width: 800px;

      max-width: 80%;

      background-color: white;

      border-radius: 5px;

      padding: 10px;

      box-shadow: 0 0 10px 2px;

    }

    .btn-grid {

      display: grid;

      grid-template-columns: repeat(2, auto);

      gap: 10px;

      margin: 20px 0;

    }

    .btn {

      --hue: var(--hue-neutral);

      border: 1px solid hsl(var(--hue), 100%, 30%);

      background-color: hsl(var(--hue), 100%, 50%);

      border-radius: 5px;

      padding: 5px 10px;

      color: white;

      outline: none;

      cursor: pointer;

    }

    .btn:hover {

      border-color: black;

    }

    .btn.correct {

      --hue: var(--hue-correct);

      color: black;

    }

    .btn.wrong {

      --hue: var(--hue-wrong);

    }

    .start-btn,

    .next-btn {

      font-size: 1.5rem;

      font-weight: bold;

      padding: 10px 20px;

      cursor: pointer;

    }

    .controls {

      display: flex;

      justify-content: center;

      align-items: center;

    }

    .hide {

      display: none;

    }

    • Define CSS styles for the body, which includes background, font styles, and a basic layout.
    • Define the style for the container and buttons.
    • Set hue colors that change according to the answer - right, wrong, or neutral.

    End Result

    The screenshot below is how the end result is expected to look.

    end-result

    We hope you had fun and learned the basics of HTML games and enjoyed going through this ‚ÄėIntroduction to HTML Games‚Äô article.

    Get Ahead of the Curve and Master HTML Today

    HTML is a programming language every programmer - aspiring or established needs to have in their arsenal. Having understood the fundamentals of the language, and gotten a practical walkthrough of how to develop an HTML game, your next step should be to enroll in a comprehensive program like our Full Stack Java Developer Masters’ Program. The program covers all the skills and practical training that you will need to become career-ready. To know more about the language, you can also check out our YouTube channel for video that provides a quick 101 or introduction to HTML and helps you learn how to develop a simple HTML game. 

    If you’re an aspiring mobile or web developer, HTML training is vital to broaden your skills and expand your career horizons. In case you have any questions for us regarding this article, do mention them in the comments section. We'll have our top experts address them for you at the earliest.

    About the Author

    Aryan GuptaAryan Gupta

    Aryan is a tech enthusiast who likes to stay updated about trending technologies of today. He is passionate about all things technology, a keen researcher, and writes to inspire. Aside from technology, he is an active football player and a keen enthusiast of the game.

    View More
    • Disclaimer
    • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.