Skip to content
Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones

Categories

  • Automobiles (12)
    • Cars (7)
  • Blog (103)
    • Poems (2)
    • Space (2)
  • Command (2)
  • Education (2)
  • Entertainment (4)
  • Gadgets (9)
    • Phones (8)
      • Android Phones (4)
  • HTML Templates (11)
  • IT Training Institutes (1)
  • Lifestyle (4)
  • News (51)
  • Others (23)
  • Programming (296)
    • API (16)
    • CSS (83)
    • Database (4)
    • Hosting (1)
    • HTML (37)
    • JavaScript (117)
      • JQuery (27)
      • ReactJS (7)
    • PHP (116)
  • Python (3)
  • recipes (1)
  • SEE Result (1)
  • Server (3)
  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones
Close

Search

JavaScript

Memory Game using JavaScript

By Admin
September 27, 2024 4 Min Read
0

Creating games can be a fun way to enhance your coding skills, and one of the simplest yet engaging projects is a Memory Game. In this blog post, we’ll walk through the process of building a Memory Game using HTML, CSS, and JavaScript, using a sample code that I’ve provided below.

What is the Memory Game?

The Memory Game, also known as Concentration, is a card-matching game that challenges players to remember the locations of pairs of cards. The objective is to flip over two cards at a time to find matching pairs. If the cards match, they stay face up; if they don’t, they are flipped back over.

Follow this video for complete guidance

https://www.youtube.com/watch?v=ZdGZFoW6odI

Getting Started

We’ll start with a simple setup that includes HTML for the structure, CSS for styling, and JavaScript for game logic.

HTML Structure

First, let’s define the basic structure of our game in HTML. We’ll include a title, a game board for our cards, and a button to restart the game.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Memory Game</title>
    <!-- CSS Styles Here -->
</head>
<body>

<h1>Memory Game</h1>
<div id="gameBoard"></div>
<button onclick="startGame()">Restart Game</button>

<!-- JavaScript Logic Here -->

</body>
</html>

CSS Styling

Next, we’ll add styles to make our game visually appealing. Here’s a brief overview of the styles:

  • Background Color: A soft background to create a relaxing atmosphere.
  • Card Styles: Cards are given a border, rounded corners, and hover effects to improve interactivity.
  • Button Styles: A button that changes color on hover to enhance user experience.

Here’s the complete CSS:

body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    margin: 0;
}
#gameBoard {
    display: grid;
    grid-template-columns: repeat(4, 100px);
    gap: 10px;
    margin-bottom: 20px;
}
.card {
    width: 100px;
    height: 100px;
    border: 2px solid #333;
    border-radius: 10px;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    cursor: pointer;
    transition: transform 0.2s;
}
.card:hover {
    transform: scale(1.05);
}
.flipped {
    background-color: #4CAF50;
    color: white;
    border-color: #388E3C;
    cursor: default;
}
h1 {
    margin: 0;
    font-size: 2rem;
}
button {
    padding: 10px 20px;
    font-size: 16px;
    border: none;
    border-radius: 5px;
    background-color: #007BFF;
    color: white;
    cursor: pointer;
    transition: background-color 0.3s;
}
button:hover {
    background-color: #0056b3;
}

JavaScript Logic

The heart of the Memory Game lies in the JavaScript code. This is where we handle the game logic, including shuffling cards, flipping them, checking for matches, and resetting the game.

Here’s how we achieve that:

  • Card Array: We define an array of cards, where each letter represents a card that has a pair.
  • Shuffle Function: A function that shuffles the cards randomly.
  • Card Creation: A function that creates card elements and assigns them values.
  • Card Flip Logic: When a card is clicked, it flips and checks for matches.
  • Game Reset: A function to restart the game and reshuffle the cards.

Here’s the complete JavaScript code:

const cards = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'];
let firstCard, secondCard, hasFlippedCard = false;

function shuffle(array) {
    return array.sort(() => Math.random() - 0.5);
}

function createCard(card) {
    const div = document.createElement('div');
    div.className = 'card';
    div.dataset.cardValue = card;
    div.innerText = '?';
    div.onclick = flipCard;
    return div;
}

function flipCard() {
    if (hasFlippedCard || this.classList.contains('flipped')) return;
    this.innerText = this.dataset.cardValue;
    this.classList.add('flipped');

    if (!firstCard) {
        firstCard = this;
        return;
    }

    secondCard = this;
    hasFlippedCard = true;

    if (firstCard.dataset.cardValue === secondCard.dataset.cardValue) {
        firstCard.removeEventListener('click', flipCard);
        secondCard.removeEventListener('click', flipCard);
        resetCards();
    } else {
        setTimeout(() => {
            firstCard.innerText = '?';
            secondCard.innerText = '?';
            firstCard.classList.remove('flipped');
            secondCard.classList.remove('flipped');
            resetCards();
        }, 1000);
    }
}

function resetCards() {
    [firstCard, secondCard] = [null, null];
    hasFlippedCard = false;
}

function startGame() {
    const shuffledCards = shuffle(cards);
    const gameBoard = document.getElementById('gameBoard');
    gameBoard.innerHTML = ''; // Clear previous cards
    shuffledCards.forEach(card => {
        gameBoard.appendChild(createCard(card));
    });
}

// Initialize the game
startGame();

Once you have your HTML, CSS, and JavaScript set up, simply open your HTML file in a browser, and you’ll see your Memory Game in action!

Complete Working Source Code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Memory Game</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
        }

        #gameBoard {
            display: grid;
            grid-template-columns: repeat(4, 100px);
            gap: 10px;
            margin-bottom: 20px;
        }

        .card {
            width: 100px;
            height: 100px;
            border: 2px solid #333;
            border-radius: 10px;
            background-color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .card:hover {
            transform: scale(1.05);
        }

        .flipped {
            background-color: #4CAF50;
            color: white;
            border-color: #388E3C;
            cursor: default;
        }

        h1 {
            margin-bottom:40px;
            font-size: 2rem;
        }

        button {
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            border-radius: 5px;
            background-color: #007BFF;
            color: white;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>

    <h1>Memory Game</h1>
    <div id="gameBoard"></div>
    <button onclick="startGame()">Restart Game</button>

    <script>
        const cards = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'];
        let firstCard, secondCard, hasFlippedCard = false;

        function shuffle(array) {
            return array.sort(() => Math.random() - 0.5);
        }

        function createCard(card) {
            const div = document.createElement('div');
            div.className = 'card';
            div.dataset.cardValue = card;
            div.innerText = '?';
            div.onclick = flipCard;
            return div;
        }

        function flipCard() {
            if (hasFlippedCard || this.classList.contains('flipped')) return;
            this.innerText = this.dataset.cardValue;
            this.classList.add('flipped');

            if (!firstCard) {
                firstCard = this;
                return;
            }

            secondCard = this;
            hasFlippedCard = true;

            if (firstCard.dataset.cardValue === secondCard.dataset.cardValue) {
                firstCard.removeEventListener('click', flipCard);
                secondCard.removeEventListener('click', flipCard);
                resetCards();
            } else {
                setTimeout(() => {
                    firstCard.innerText = '?';
                    secondCard.innerText = '?';
                    firstCard.classList.remove('flipped');
                    secondCard.classList.remove('flipped');
                    resetCards();
                }, 1000);
            }
        }

        function resetCards() {
            [firstCard, secondCard] = [null, null];
            hasFlippedCard = false;
        }

        function startGame() {
            const shuffledCards = shuffle(cards);
            const gameBoard = document.getElementById('gameBoard');
            gameBoard.innerHTML = ''; // Clear previous cards
            shuffledCards.forEach(card => {
                gameBoard.appendChild(createCard(card));
            });
        }

        // Initialize the game
        startGame();
    </script>
</body>

</html>

Creating a Memory Game using JavaScript is not only fun but also a great way to practice your coding skills. You can further enhance the game by adding features like a scoring system, different levels of difficulty, or even a timer.

Feel free to modify and expand on this code to make it your own. Happy coding!

Author

Admin

Follow Me
Other Articles
Previous

Create a 3D Rubik’s Cube with HTML and CSS

Next

10 Space Facts That Will Blow Your Mind

No Comment! Be the first one.

Leave a Reply

Your email address will not be published. Required fields are marked *

FIFA World Cup 2026 Predict and Win by SportsGuff

Recent Posts

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide
  • Chiranjibi Adhikari Appointed Acting President of CAN Federation
  • How to Design a Student Marksheet Using HTML and CSS

Tags

adsense ai animate animation animation using HTML and CSS API blog calculator chatgpt Cryptocurrency CSS css animation design Email Facebook featured filemanager file manager free template google htaccess HTML image Instagram interview javascript JQuery jquery ui NADA AutoShow NADA Auto Show 2024 password PHP Progressive Web App PWA QR random react reactjs Rotate travel Twitter vpn youthforum youthsforum youtube

About Us

At Youths Forum, we are passionate about sharing knowledge that empowers students, educators, professionals, and technology enthusiasts.

Our Mission

Our mission is simple: to make technology and education accessible, understandable, and beneficial for everyone. We strive to create content that helps our readers learn new skills and stay updated with industry developments.

RSS RSS

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You Admin
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide Admin
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide Admin

Quick Links

  • Stock Market Live
  • Parliament Election 2082
Copyright 2026 — Youths Forum. All rights reserved. Blogsy WordPress Theme