Color Guessing Game using Javascript

In this article you will know how to create Color Guessing Game using HTML, CSS and JavaScript. If you are a beginner and want to improve your JavaScript knowledge then you can make this kind of JavaScript Color Prediction Game.

This project is not only a great way to enhance your JavaScript skills but also provides an entertaining and interactive experience for users.

This is a step by step tutorial that will help you learn how to create and work with a JavaScript Color Guessing Game.

Color Guessing Game Javascript

A Color Guessing Game using JavaScript is an interactive web application where users are presented with a randomly generated color, and they have to guess the correct color based on some criteria (e.g., RGB values, color names, etc.). 

The game typically involves providing users with visual clues, such as displaying the color in a designated area, and prompting them to input their guesses through a form or input field.

See the Pen Untitled by Growthpanda (@Growthpanda) on CodePen.

As you can see in the demo above, this is a simple Guess The Color Game design. First you will see a button, click on that button and the game will start. Then you will see a color code and 4 color options, you have to tell which color the color code is.

Build A Color Guessing Game With HTML,CSS,JS

Are you interested in making this Color Guessing Game? So let’s know how to make this color prediction game javascript. If you are just looking for the source code then use the download button below the article.

Step 1: Color Guessing Game HTML Code

To get started to create color guessing game, create a new HTML file and include the necessary boilerplate code. Link your JavaScript file and add a simple layout with a heading, a color display area, and a form for user input.

<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>

Step 2: Design the Color Guessing Game

Enhance the visual appeal of the game by adding some CSS. Create a new file (styles.css) and add styles to make the game more user-friendly.

I am designing the basic of this Color Guessing Game game by following codes. Here below code is used to design background color and DOM.

* {
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
  color: #19084e;
}
body {
  margin: 0;
  background-color: #9873fe;
}
.flex-space {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.flex {
  display: flex;
}

The following CSS has been used to design the buttons used for this Color Guessing Game.

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);
}

Now it’s time to design the remaining elements of this Javascript Color Guessing Game.

#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;
}

Step 3: Color Prediction Game Javascript code

Now, let’s create the JavaScript file (script.js) and implement the logic for the Color Guessing Game.

1. Importing and Initializing Variables:
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;
let letters = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
let quizArray = [];

Here, various HTML elements are selected using document.getElementById and document.getElementsByClassName. Additionally, several variables are declared to keep track of the Color Guessing Game game state, such as questionCount, scoreCount, count (for the timer), and countdown (to store the interval ID for the timer).

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

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

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

These functions are utility functions used to generate random values and create random hex color codes. generateRandomValue returns a random element from an array, colorGenerator generates a random hex color code, and populateOptions ensures an array of options has a specified length by generating additional options if needed.

3. Initializing the Quiz:
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,
    });
  }
};

The populateQuiz function creates a quiz with 5 questions. For each question, it generates a correct color (currentColor), populates an array of options (allColors), and adds a quiz object to the quizArray array.

4. Handling Next Button Click:
nextButton.addEventListener(
  "click",
  (displayNext = () => {
    questionCount += 1;
    if (questionCount == quizArray.length) {
      displayContainer.classList.add("hide");
      scoreContainer.classList.remove("hide");
      userScore.innerHTML =
        "Your score is " + scoreCount + " out of " + questionCount;
    } else {
      numOfQuestions.innerHTML =
        questionCount + 1 + " of " + quizArray.length + " Question";
      quizDisplay(questionCount);
      count = 10;
      clearInterval(countdown);
      timerDisplay();
    }
    nextButton.classList.add("hide");
  })
);

This code adds an event listener to the nextButton. When the button is clicked, the displayNext function is executed. It increments the questionCount, checks if it’s the last question, hides the question container and displays the score if so. Otherwise, it updates the question count display, shows the next question, resets the countdown timer, and hides the next button.

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

The timerDisplay function sets up the countdown timer using setInterval. It updates the timer display every second (1000 milliseconds), decrements the count variable, and clears the interval when the countdown reaches zero, triggering the displayNext function.

6. Displaying Quiz Questions:
const quizDisplay = (questionCount) => {
  let quizCards = document.querySelectorAll(".container-mid");
  quizCards.forEach((card) => {
    card.classList.add("hide");
  });
  quizCards[questionCount].classList.remove("hide");
};

The quizDisplay function hides all quiz cards and displays the current question card.

7. Quiz Creation Function:
function quizCreator() {
  quizArray.sort(() => Math.random() - 0.5);

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

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

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

    let questionDiv = document.createElement("p");
    questionDiv.classList.add("question");
    questionDiv.innerHTML = `<div class="question-color">${i.correct}</div>`;
    div.appendChild(questionDiv);

    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);
  }
}

The quizCreator function sorts the quiz array randomly, creates HTML elements for each question and its options, and appends them to the quizContainer.

8. Checker Function:
function checker(userOption) {
  let userSolution = userOption.getAttribute("data-option");
  let question = document.getElementsByClassName("container-mid")[questionCount];
  let options = question.querySelectorAll(".option-div");

  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");
      }
    });
  }

  clearInterval(countdown);
  options.forEach((element) => {
    element.disabled = true;
  });
  nextButton.classList.remove("hide");
}

The checker function handles user input. It checks if the selected option is correct, updates the score, and provides visual feedback. It also disables all options and reveals the correct answer.

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

The initial function initializes the Color Guessing Game game by resetting variables, clearing intervals, setting up the timer, creating the quiz, and displaying the first question.

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

This event listener resets the Color Guessing Game game when the restart button is clicked. It clears the quiz array, repopulates it, initializes the game, and shows the display container while hiding the score container.

11. Start Button Event Listener:
startButton.addEventListener("click", () => {
  startScreen.classList.add("hide");
  displayContainer.classList.remove("hide");
  quizArray = [];
  populateQuiz();
  initial();
});

This event listener starts the game when the start button is clicked. It hides the start screen, displays the quiz container, repopulates the quiz, and initializes the game.

Congratulations! You’ve successfully built a Color Guessing Game using JavaScript. Hopefully from this article you have learned how to create Color Guessing Game using html css and javascript.

This project not only provides a hands-on experience in JavaScript programming but also showcases the combination of HTML, CSS, and JavaScript to create a fun and interactive web application.

Leave a Comment