Open In App

JavaScript Pair Game

Last Updated : 22 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will create a Card Pair game using JavaScript. The Concentration or Memory Matching Game is mainly utilized for memory tests & concentration levels of the player. Here, the player needs to find out all the matching pairs of identical cards placed that are face-down on the board & the player can only turn 2 cards at a time. Accordingly, try to remember their position for the respective card match. The player needs to complete the game with the fewest number of moves to find all the pairs of cards. After completing the project, the below images will appear:

Screenshot-from-2023-07-28-15-51-22

Prerequisites:

  • HTML
  • CSS
  • JavaScript

Project Structure:

The following project structure will appear:

Screenshot-from-2023-07-28-09-46-13

Approach:

  • Create the game card layout in HTML using HTML tags like divs, headings, span, p, etc. in the body tags along with relevant class names and ids.
  • Use tags, ids, and class names to style the page with CSS properties like margin, padding, background color, font properties, height, width, box, etc.
  • In JavaScript first create a list of items to be used in the game and rearrange them with the shuffle function using swapping and math.random() method.
  • Define a function createCard() to render the items on the web page using HTML DOM methods like createElement, classList.add, getElementById, etc., and render all items using the array.map() method.
  • Use addEventListener to handle click to update moves and trigger the toggle function to update the cards accordingly with the setTimeout function to apply some delay.
  • Use the check function to check the finish condition and display the result using the window.alert

Example: This example illustrates the Pair Game using Javascript.

HTML




<!-- index.html -->
<!DOCTYPE html>
<html>
  
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" 
          content="IE=edge" />
    <title>Pair game</title>
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1" />
    <link rel="stylesheet" 
          href="style.css" />
</head>
  
<body>
    <h1>Find All Pair Cards</h1>
    <div class="root">
        <br />
        <h3 id="count">Total Moves : 0</h3>
        <div class="card" id="card"></div>
    </div>
    <script src="script.js"></script>
</body>
  
</html>


CSS




/* style.css */
  
@import url(
  
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
  
body {
    min-height: 50vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    justify-content: center;
    background: hsl(0, 0%, 100%);
    font-family: "Poppins", sans-serif;
}
  
h1 {
    font-size: xx-large;
    padding: 2%;
}
  
.root {
    background: rgb(60, 125, 60);
    margin: 0 1rem;
    padding: rem;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
    width: 50rem;
    border-radius: 0.5rem;
}
  
.card {
    margin: 5%;
    text-align: centre;
    display: flex;
    flex-wrap: wrap;
}
  
.card-item {
    color: white;
    height: 100px;
    font-size: larger;
    margin: 2%;
    padding: 4%;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
    width: 28%;
    background: rgb(2, 0, 36);
    background: linear-gradient(120deg, rgb(0, 37, 61) 0%
                rgba(45, 128, 97, 0.33657212885154064) 35%,
                  rgba(0, 212, 255, 1) 100%);
}
  
#count {
    font-size: xx-large;
    color: antiquewhite;
}
  
p {
    font-size: x-large;
    font-weight: bolder;
}


Javascript




// script.js
  
let list = [
    "HTML",
    "HTML",
    "CSS",
    "CSS",
    "JavaScript",
    "JavaScript",
    "React",
    "React",
    "Geeks",
    "Geeks",
    "Bootstrap",
    "Bootstrap",
];
  
let match = "";
let click = 0;
let count = 0;
function check() {
    if (count === 6)
        window.alert("You win! your score is :" + click);
}
  
// To shuffle the list
function shuffleList(List) {
    for (let i = List.length - 1; i > 0; i--) {
        let j = Math.floor(Math.random() * (i + 1));
        let temp = List[i];
        List[i] = List[j];
        List[j] = temp;
    }
    return List;
}
  
list = shuffleList(list);
  
// Toggle function to handle moves
let toggle = (text) => {
    click = click + 1;
    document.getElementById("count").innerText =
        "Total Moves: " + click;
          
    // Toogle class and update text visibility
    text.classList.toggle("active");
    if (text.style.display === "block") {
        text.style.display = "none";
        match = "";
    } else if (text.style.display === "none") {
        text.style.display = "block";
        if (match === "") match = text;
        else if (match.innerText === text.innerText) {
            text.style.display = "inline";
            match.style.display = "inline";
            count++;
            match = "";
              
            // Check and display result with .5 sec delay
            setTimeout(() => check(), 500);
        } else {
          
            // Revert back changes if no match
            // found with delay
            setTimeout(() => {
                text.style.display = "none";
                match.style.display = "none";
                match = "";
            }, 500);
        }
    }
};
  
// Create cards
function createCard(e) {
    const cardItem = document.createElement("div");
    cardItem.classList.add("card-item");
    const text = document.createElement("p");
    text.innerText = e;
    text.style.display = "none";
    cardItem.appendChild(text);
    text.style.display = "none";
    cardItem.addEventListener("click", () => toggle(text));
    const card = document.getElementById("card");
    card.appendChild(cardItem);
}
  
// Load all card items
list.map((e, i) => createCard(e, i));


Output:

Peek-2023-07-28-15-57



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads