Memory Game using JavaScript

0
175

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

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.

ALSO READ  Image Size Compression Tool using JavaScript

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.

ALSO READ  Building Your Own Chatbot with Gemini API: A Step-by-Step Guide

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

Comments are closed.