Who’s That Pokémon? | JavaScript Project
Tags: javascript, webdev, programming, productivity
Published: 2023-12-21 14:58:02

Hey everyone. Welcome to today's tutorial. In today's tutorial, we will learn how to create a Pokémon quiz game called "Who's the Pokémon?". To build this project we would need HTML, CSS, and JavaScript. Let's discover how to build this project in a few simple and easy-to-follow steps.

> If you want to support my channel and see more great content, hit that subscribe button.😍
{% embed https://www.youtube.com/@learnwithdanial417 %}

## Video Tutorial:
For a better understanding of how we built the functionality of this project, I would advise you to watch the video below. If you find the video helpful give it a like and subscribe to [my YouTube channel](https://www.youtube.com/@learnwithdanial417) where I post new tips, tricks, and tutorials related to HTML, CSS, and JavaScript.

{% embed https://www.youtube.com/embed/0ps6W8ro8q8?si=mdvdIRq2D4KXQ37v %}

## Project Folder Structure:
Let's build the project folder structure before we begin writing the code. We create a project folder called 'Who's the Pokemon?'. Inside this folder, we have three files. These files are index.html, style.css, script.js, and the images of various Pokémon.

## 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>Who's that Pokemon</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 class="game-container hide">
      <div class="header">
        <div class="timer"></div>
      </div>
      <div class="container"></div>
    </div>
    <div class="score-container">
      <div id="user-score"></div>
      <button id="start">Start</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.

```
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  height: 100vh;
  background: linear-gradient(
    #da2e2c 49%,
    #090029 49%,
    #090029 51%,
    #ffffff 51%
  );
}
.score-container {
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
}
#start {
  background-color: #ffffff;
  height: 6em;
  width: 6em;
  font-size: 1.8em;
  border: 0.4em solid #090029;
  border-radius: 50%;
  cursor: pointer;
}
.game-container {
  background-color: #ffffff;
  width: 100%;
  max-width: 31em;
  padding: 3em 1.5em;
  border: 0.6em solid #090029;
  border-radius: 0.5em;
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
}
.timer span {
  font-weight: 600;
}
.header,
.num {
  text-align: right;
}
.pokemon-image {
  display: block;
  margin: 3em auto 0 auto;
}
.options {
  display: flex;
  justify-content: center;
  gap: 0.5em;
  flex-wrap: wrap;
}
.options button {
  background-color: #ffffff;
  padding: 0.8em;
  border: 0.3em solid #090029;
  border-radius: 0.5em;
  box-shadow: 0 0.5em 0 0 #090029;
  cursor: pointer;
}
.options button:hover {
  box-shadow: none;
  transform: translateY(0.6em);
}
.nxt-btn-div {
  margin-top: 3em;
  display: flex;
  justify-content: flex-end;
}
.next-btn {
  cursor: pointer;
  background-color: #090029;
  color: #ffffff;
  border-radius: 0.5em;
  font-size: 1.2em;
  padding: 0.8em 3em;
}
.hide {
  display: none;
}
.options:disabled {
  border-color: #a0a0a0;
  color: #a0a0a0;
  box-shadow: 0 0.5em 0 0 #a0a0a0;
  cursor: not-allowed;
}
.options button.correct {
  background: #58cc5d;
}
.options button.incorrect {
  background: #eb5650;
}
.options button.correct,
.options button.incorrect {
  color: #ffffff;
  border-color: #090029;
  box-shadow: 0 0.5em 0 0 #090029;
}
.score-container {
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
}
#user-score {
  margin-bottom: 1em;
  color: #ffffff;
}
```

## JavaScript:
Finally, we add functionality using JavaScript. Once again copy the code below and paste it into your script file.

The game consists of a series of questions with images of Pokémon, and the user has to choose the correct option from a list of options.

The steps included in creating this are:

- First, initialize all the images and their corresponding correct options in an array of objects and create an array of different options for the questions. Apart from this, declare variables and create references
- When the user clicks the start button the “startGame” function is called. It calls the “populateQuestions” function to populate 5 random. questions in an array and then calls the “cardGenerator” function to generate the UI for the game.
- “cardGenerator” further calls “populateOptions” to get all 4 options for our question and to shuffle options randomly it makes a call to the “randomShuffle” function, then it calls the “timerDisplay” function to start the countdown.
- When the user clicks an option the “checker” function is called which checks if the selected option is correct or not, updates the score, and calls the “nextQuestion” function which displays the next question. The “nextQuestion” function would also be called if the countdown ends or if the user clicks the next button.

```
//Initial References

//Questions Or Images
const questions = [
  {
    image: "Alakazam.jpg",
    correct_option: "Alakazam",
  },
  {
    image: "Arcanine.jpg",
    correct_option: "Arcanine",
  },
  {
    image: "Bulbasaur.jpg",
    correct_option: "Bulbasaur",
  },
  {
    image: "Cubone.jpg",
    correct_option: "Cubone",
  },
  {
    image: "Ditto.jpg",
    correct_option: "Ditto",
  },
  {
    image: "Gloom.jpg",
    correct_option: "Gloom",
  },
  {
    image: "Gyarados.jpg",
    correct_option: "Gyarados",
  },
  {
    image: "Hitmonlee.jpg",
    correct_option: "Hitmonlee",
  },
  {
    image: "Horsea.jpg",
    correct_option: "Horsea",
  },
  {
    image: "Koffing.jpg",
    correct_option: "Koffing",
  },
  {
    image: "Mewtwo.jpg",
    correct_option: "Mewtwo",
  },
  {
    image: "Seaking.jpg",
    correct_option: "Seaking",
  },
  {
    image: "Tauros.jpg",
    correct_option: "Tauros",
  },
  {
    image: "Venonat.jpg",
    correct_option: "Venonat",
  },
  {
    image: "Victreebe.jpg",
    correct_option: "Victreebe",
  },
  {
    image: "eevee.jpg",
    correct_option: "Eevee",
  },
];

//All options
const optionsArray = [
  "Alakazam",
  "Arcanine",
  "Bulbasaur",
  "Cubone",
  "Ditto",
  "Gloom",
  "Gyarados",
  "Hitmonlee",
  "Horsea",
  "Koffing",
  "Mewtwo",
  "Pikachu",
  "Seaking",
  "Tauros",
  "Venonat",
  "Victreebe",
  "eevee",
  "Ivysaur",
  "Venusaur",
  "Charmander",
  "Charmeleon",
  "Charizard",
  "Squirtle",
  "Wartortle",
  "Blastoise",
  "Caterpie",
  "Metapod",
  "Butterfree",
  "Weedle",
  "Kakuna",
  "Beedrill",
  "Pidgey",
  "Pidgeotto",
  "Pidgeot",
  "Rattata",
  "Raticate",
  "Spearow",
  "Fearow",
  "Ekans",
  "Arbok",
];
const container = document.querySelector(".container");
const gameContainer = document.querySelector(".game-container");
const startButton = document.getElementById("start");
const scoreContainer = document.querySelector(".score-container");
const userScore = document.getElementById("user-score");
let timer = document.getElementsByClassName("timer")[0];
let nextBtn;
let score, currentQuestion, finalQuestions;
let countdown,
  count = 11;

//Random value from array
const randomValueGenerator = (array) =>
  array[Math.floor(Math.random() * array.length)];

//Random shuffle array
const randomShuffle = (array) => array.sort(() => 0.5 - Math.random());

//Start game
const startGame = () => {
  //Select random 5 questions
  scoreContainer.classList.add("hide");
  gameContainer.classList.remove("hide");
  finalQuestions = populateQuestions();
  score = 0;
  currentQuestion = 0;
  //Generate card for first question
  cardGenerator(finalQuestions[currentQuestion]);
};

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

//Create options
const populateOptions = (correct_option) => {
  let arr = [];
  arr.push(correct_option);
  let optionsCount = 1;
  while (optionsCount < 4) {
    let randomvalue = randomValueGenerator(optionsArray);
    if (!arr.includes(randomvalue)) {
      arr.push(randomvalue);
      optionsCount += 1;
    }
  }
  return arr;
};

//Choose random questions
const populateQuestions = () => {
  let questionsCount = 0;
  let chosenObjects = [];
  let questionsBatch = [];
  //5 Questions
  while (questionsCount < 5) {
    let randomvalue = randomValueGenerator(questions);
    let index = questions.indexOf(randomvalue);
    if (!chosenObjects.includes(index)) {
      questionsBatch.push(randomvalue);
      chosenObjects.push(index);
      questionsCount += 1;
    }
  }
  return questionsBatch;
};

//check selected answer
const checker = (e) => {
  let userSolution = e.target.innerText;
  let options = document.querySelectorAll(".option");
  if (userSolution === finalQuestions[currentQuestion].correct_option) {
    e.target.classList.add("correct");
    score++;
  } else {
    e.target.classList.add("incorrect");
    options.forEach((element) => {
      if (element.innerText == finalQuestions[currentQuestion].correct_option) {
        element.classList.add("correct");
      }
    });
  }

  clearInterval(countdown);
  //disable all options
  options.forEach((element) => {
    element.disabled = true;
  });
};

//Next question
const nextQuestion = (e) => {
  //increment currentQuestion
  currentQuestion += 1;
  if (currentQuestion == finalQuestions.length) {
    gameContainer.classList.add("hide");
    scoreContainer.classList.remove("hide");
    startButton.innerText = `Restart`;
    userScore.innerHTML =
      "Your score is " + score + " out of " + currentQuestion;
    clearInterval(countdown);
  } else {
    cardGenerator(finalQuestions[currentQuestion]);
  }
};

//Card UI
const cardGenerator = (cardObject) => {
  const { image, correct_option } = cardObject;
  let options = randomShuffle(populateOptions(correct_option));
  container.innerHTML = `<div class="quiz">
  <p class="num">
  ${currentQuestion + 1}/5
  </p>
  <div class="questions">
    <img class="pokemon-image" src="${image}"/>
  </div>
    <div class="options">
    <button class="option" onclick="checker(event)">${options[0]}
    </button>
    <button class="option" onclick="checker(event)">${options[1]}
    </button>
    <button class="option" onclick="checker(event)">${options[2]}
    </button>
    <button class="option" onclick="checker(event)">${options[3]}
    </button>
    </div>

    <div class="nxt-btn-div">
        <button class="next-btn" onclick="nextQuestion(event)">Next</button>
    </div>

  </div>`;
  //For timer
  count = 11;
  clearInterval(countdown);
  //Display timer
  timerDisplay();
};

startButton.addEventListener("click", startGame);
```
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 on the ‘Download Code’ button below.

---

[Download Code](https://github.com/codingcss/Who-s-That-Pok-mon-JavaScript-Project)

---


{% embed https://github.com/codingcss/Who-s-That-Pok-mon-JavaScript-Project %}