HomeJavascriptColor Guessing Game Javascript

Color Guessing Game Javascript

Hi everyone. Welcome to another new tutorial by Coding Artist. In this tutorial, we take a look at how to build a ‘Color Guessing Game’. To build this project we need HTML, CSS, and Javascript. Get ready to learn something fun and exciting today.

Video Tutorial:

Hi everyone. Welcome to another new tutorial by Coding Artist. In this tutorial, we take a look at how to build a ‘Color Guessing Game’. To build this project we need HTML, CSS, and Javascript. Get ready to learn something fun and exciting today.

Project Folder Structure:

Let’s build the project folder structure before we begin writing the code. We create a project folder called ‘Color Guessing Game’. Inside this folder, we have three files. These files are index.html, style.css, and script.js.

HTML:

We begin with the HTML Code. First, create a file called – ‘index.html’. Copy the code below and paste it into your HTML file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Color Guessing Game</title>
    <!-- Google Fonts -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div id="display-container">
      <div class="header flex-space">
        <div class="title">
          <p>Color Guessing Game</p>
        </div>
        <div class="timer"></div>
      </div>

      <div id="container">
        <!-- Questions and options are displayed here-->
      </div>

      <div class="flex-space">
        <div class="number-of-count">
          <span class="number-of-questions"></span>
        </div>
        <div id="next-button">Next</div>
      </div>
    </div>

    <div class="start-screen">
      <button id="start-button">Start</button>
    </div>

    <div class="score-container hide">
      <div id="user-score"></div>
      <button id="restart">Restart</button>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Next, we style our list using CSS. For this copy, the code provided to you below and paste it into your stylesheet.

* {
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
  color: #19084e;
}
body {
  margin: 0;
  background-color: #9873fe;
}
button {
  border: none;
  outline: none;
  cursor: pointer;
}
.start-screen,
.score-container {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #9873fe;
}
#start-button,
#restart {
  position: absolute;
  font-size: 1.2em;
  padding: 1em 3em;
  border-radius: 2em;
  box-shadow: 0 1em 3em rgba(37, 22, 80, 0.3);
}
.flex-space {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.flex {
  display: flex;
}
#display-container {
  background-color: #ffffff;
  position: absolute;
  width: 90%;
  max-width: 37em;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  padding: 3em 2em;
  border-radius: 0.8em;
  box-shadow: 0 1em 3em rgba(37, 22, 80, 0.3);
}
.header {
  padding: 0.5em;
  border-bottom: 1px solid #c8c5d1;
}
.header .title,
.timer span {
  font-weight: 600;
}
.question-color {
  font-size: 1.5em;
  text-align: center;
}
#container {
  margin-bottom: 1em;
}
.button-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1em;
  place-items: center;
}
.option-div {
  width: 100%;
  height: 10em;
  padding: 1em;
  margin: 0.3em 0;
  text-align: left;
  border-radius: 0.5em;
}
.option-div:disabled {
  cursor: not-allowed;
}
.correct {
  background: url("correct.svg");
}
.incorrect {
  background: url("incorrect.svg");
}
.correct,
.incorrect {
  background-repeat: no-repeat;
  background-size: 3em;
  background-position: center;
}
#next-button {
  font-size: 1.1em;
  background-color: #9873fe;
  color: #ffffff;
  padding: 0.4em 2em;
  border-radius: 0.3em;
}
.hide {
  display: none;
}
#restart {
  margin-top: 6em;
}

Javascript:

Finally, we add functionality using Javascript. Once again copy the code below and paste it into your script file. In this game, we provide the user with 5 questions. Each question would be a hex code and will have 4 color options. The user has to choose the correct option before the timer ends.

Now that we know what happens, Let’s make it happen.

  • Initially, we would display a start screen to the user from where the user can start the game. When the user clicks Start Button the start screen is hidden and the questions screen is displayed.
  • We first call the ‘populateQuiz’ function to fill 5 quizzes in our array.
  • Now that we have questions we create the cards for our questions in the ‘quizCreator’ function, each option in our quiz has a ‘data-option’ attached to it for storing the hex code.
  • Then we start the timer using the ‘timerDisplay’ function. The timer is simply the count variable decremented and displayed every second until it hits zero. Once it hits zero the next question is displayed.
  • Then we display the current question using the ‘quizDisplay’ function.
  • As soon as the user clicks on an option the ‘checker’ function is called which checks if the ‘data-option’ value of the current question has the same value as the correct option for the question. if yes, we increment the score else we display the correct option and move to the next question.
  • This continues until the last question and then we display the restart screen.
let timer = document.getElementsByClassName("timer")[0];
let quizContainer = document.getElementById("container");
let nextButton = document.getElementById("next-button");
let numOfQuestions = document.getElementsByClassName("number-of-questions")[0];
let displayContainer = document.getElementById("display-container");
let scoreContainer = document.querySelector(".score-container");
let restart = document.getElementById("restart");
let userScore = document.getElementById("user-score");
let startScreen = document.querySelector(".start-screen");
let startButton = document.getElementById("start-button");
let questionCount;
let scoreCount = 0;
let count = 10;
let countdown;
//For hex codes
let letters = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];

//Questions and Options Array
let quizArray = [];

const generateRandomValue = (array) =>
  array[Math.floor(Math.random() * array.length)];

//Generate Hex Codes
const colorGenerator = () => {
  newColor = "#";
  for (let i = 0; i < 6; i++) {
    newColor += generateRandomValue(letters);
  }
  return newColor;
};

//Create Options
const populateOptions = (optionsArray) => {
  let expectedLength = 4;
  while (optionsArray.length < expectedLength) {
    let color = colorGenerator();
    if (!optionsArray.includes(color)) {
      optionsArray.push(color);
    }
  }
  return optionsArray;
};

//Create quiz Objecy
const populateQuiz = () => {
  for (let i = 0; i < 5; i++) {
    let currentColor = colorGenerator();
    let allColors = [];
    allColors.push(currentColor);
    allColors = populateOptions(allColors);
    quizArray.push({
      id: i,
      correct: currentColor,
      options: allColors,
    });
  }
};

//Next button
nextButton.addEventListener(
  "click",
  (displayNext = () => {
    //increment questionCOunt
    questionCount += 1;
    //If last question
    if (questionCount == quizArray.length) {
      //hide question container and display score
      displayContainer.classList.add("hide");
      scoreContainer.classList.remove("hide");

      //User score
      userScore.innerHTML =
        "Your score is " + scoreCount + " out of " + questionCount;
    } else {
      //displau questionCount
      numOfQuestions.innerHTML =
        questionCount + 1 + " of " + quizArray.length + " Question";

      //display quiz
      quizDisplay(questionCount);
      //count=11(so it start with 10)
      count = 10;
      //clearInterval for next question
      clearInterval(countdown);
      //display timer
      timerDisplay();
    }
    nextButton.classList.add("hide");
  })
);

//Timer
const timerDisplay = () => {
  countdown = setInterval(() => {
    timer.innerHTML = `<span>Time Left: </span> ${count}s`;
    count--;
    if (count == 0) {
      clearInterval(countdown);
      displayNext();
    }
  }, 1000);
};

//Display Quiz
const quizDisplay = (questionCount) => {
  let quizCards = document.querySelectorAll(".container-mid");
  //hide other cards
  quizCards.forEach((card) => {
    card.classList.add("hide");
  });

  //display current question card
  quizCards[questionCount].classList.remove("hide");
};

//Quiz Creation
function quizCreator() {
  //randomly sort questions
  quizArray.sort(() => Math.random() - 0.5);

  //Generate quiz
  for (let i of quizArray) {
    //Randomly sort options
    i.options.sort(() => Math.random() - 0.5);

    //Quiz card creation
    let div = document.createElement("div");
    div.classList.add("container-mid", "hide");

    //Question number
    numOfQuestions.innerHTML = 1 + " of " + quizArray.length + " Question";

    //question
    let questionDiv = document.createElement("p");
    questionDiv.classList.add("question");
    questionDiv.innerHTML = `<div class="question-color">${i.correct}</div>`;
    div.appendChild(questionDiv);
    //Options
    div.innerHTML += `
    <div class="button-container">
    <button class="option-div" onclick="checker(this)" style="background-color: ${i.options[0]}" data-option="${i.options[0]}"></button>
    <button class="option-div" onclick="checker(this)" style="background-color: ${i.options[1]}" data-option="${i.options[1]}"></button>
    <button class="option-div" onclick="checker(this)" style="background-color: ${i.options[2]}" data-option="${i.options[2]}"></button>
    <button class="option-div" onclick="checker(this)" style="background-color: ${i.options[3]}" data-option="${i.options[3]}"></button>
    </div>
    `;
    quizContainer.appendChild(div);
  }
}

function checker(userOption) {
  let userSolution = userOption.getAttribute("data-option");
  let question =
    document.getElementsByClassName("container-mid")[questionCount];
  let options = question.querySelectorAll(".option-div");
  //If users clicked answer === correct
  if (userSolution === quizArray[questionCount].correct) {
    userOption.classList.add("correct");
    scoreCount++;
  } else {
    userOption.classList.add("incorrect");
    options.forEach((element) => {
      if (
        element.getAttribute("data-option") == quizArray[questionCount].correct
      ) {
        element.classList.add("correct");
      }
    });
  }
  //clear interval
  clearInterval(countdown);
  //disable all options
  options.forEach((element) => {
    element.disabled = true;
  });
  nextButton.classList.remove("hide");
}

function initial() {
  nextButton.classList.add("hide");
  quizContainer.innerHTML = "";
  questionCount = 0;
  scoreCount = 0;
  clearInterval(countdown);
  count = 10;
  timerDisplay();
  quizCreator();
  quizDisplay(questionCount);
}

//Restart game
restart.addEventListener("click", () => {
  quizArray = [];
  populateQuiz();
  initial();
  displayContainer.classList.remove("hide");
  scoreContainer.classList.add("hide");
});

//When user clicks on start button
startButton.addEventListener("click", () => {
  startScreen.classList.add("hide");
  displayContainer.classList.remove("hide");
  quizArray = [];
  populateQuiz();
  initial();
});

Go ahead and customize the project the way you like. If you have any queries, suggestions, or feedback comment below. Download the source code by clicking the ‘Download Code’ button below.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

nineteen − nine =

Most Popular