Creating a card-matching game

Loading

That’s a big request, but I’ve got you covered! Below is a detailed, step-by-step guide on Creating a Card-Matching Game Using jQuery.


Creating a Card-Matching Game Using jQuery

Table of Contents

  1. Introduction
  2. Setting Up the Environment
  3. HTML Structure
  4. Styling with CSS
  5. Implementing Game Logic with jQuery
  6. Enhancing the Game with Animations and Sound Effects
  7. Adding a Timer and Score Tracking
  8. Making the Game Responsive
  9. Optimizing Performance
  10. Conclusion

1. Introduction

A card-matching game (also known as a Memory Game) is a simple and fun game where players flip two cards at a time, trying to match pairs. The game is won when all pairs are matched.

In this guide, we’ll build an interactive card-matching game using jQuery, with animations, sounds, and a timer.


2. Setting Up the Environment

Before we start coding, ensure you have:

  • A code editor (VS Code, Sublime, or Notepad++)
  • A web browser (Chrome, Firefox, or Edge)
  • Basic knowledge of HTML, CSS, and JavaScript (jQuery)

We will use:

  • HTML for structure
  • CSS for styling
  • jQuery for interactive behavior

Including jQuery

Make sure to include jQuery in your project. Add this in your <head> section:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

3. HTML Structure

We will create a game board with cards arranged in a grid.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Card Matching Game</title>
    <link rel="stylesheet" href="styles.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script defer src="script.js"></script>
</head>
<body>
    <h1>Card Matching Game</h1>
    <p>Match all the cards to win!</p>
    <div id="game-board"></div>
    <button id="restart">Restart Game</button>
</body>
</html>

4. Styling with CSS

The CSS styles the game grid, cards, and animations.

body {
    text-align: center;
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
}

#game-board {
    display: grid;
    grid-template-columns: repeat(4, 100px);
    grid-gap: 10px;
    justify-content: center;
    margin: 20px auto;
    width: 440px;
}

.card {
    width: 100px;
    height: 140px;
    background-color: #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2em;
    cursor: pointer;
    border-radius: 10px;
}

.card.flipped {
    background-color: white;
}

.card.matched {
    background-color: lightgreen;
    cursor: default;
}

5. Implementing Game Logic with jQuery

Now, let’s create the logic for:

  • Flipping cards
  • Checking matches
  • Restarting the game

Step 1: Define Variables

$(document).ready(function () {
    const cards = ["🍎", "🍎", "🍌", "🍌", "🍇", "🍇", "🍉", "🍉", "🍊", "🍊", "🍒", "🍒", "🥝", "🥝", "🍍", "🍍"];
    let flippedCards = [];
    let matchedPairs = 0;
    let canFlip = true;

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

    function createBoard() {
        let shuffledCards = shuffle(cards);
        $('#game-board').html('');
        shuffledCards.forEach((emoji, index) => {
            $('#game-board').append(`<div class="card" data-id="${index}" data-emoji="${emoji}"></div>`);
        });
    }

    function resetGame() {
        matchedPairs = 0;
        flippedCards = [];
        canFlip = true;
        createBoard();
    }

    $('#restart').click(resetGame);
    resetGame();
});

Step 2: Handle Card Clicks

$(document).on('click', '.card', function () {
    if (!canFlip || $(this).hasClass('flipped')) return;

    let card = $(this);
    card.text(card.data('emoji')).addClass('flipped');

    flippedCards.push(card);
    if (flippedCards.length === 2) {
        canFlip = false;
        setTimeout(checkMatch, 500);
    }
});

Step 3: Check for a Match

function checkMatch() {
    let [first, second] = flippedCards;
    if (first.data('emoji') === second.data('emoji')) {
        first.add(second).addClass('matched');
        matchedPairs++;
        if (matchedPairs === 8) {
            alert("You won!");
        }
    } else {
        first.add(second).removeClass('flipped').text('');
    }
    flippedCards = [];
    canFlip = true;
}

6. Enhancing the Game with Animations and Sound

Adding Flip Animation

Modify the CSS:

.card {
    transition: transform 0.3s ease-in-out;
}

.card.flipped {
    transform: rotateY(180deg);
}

Adding Sound Effects

Include sound effects:

<audio id="flip-sound" src="flip.mp3"></audio>
<audio id="match-sound" src="match.mp3"></audio>

Modify JavaScript:

function playSound(id) {
    document.getElementById(id).play();
}

$(document).on('click', '.card', function () {
    playSound('flip-sound');
});

7. Adding a Timer and Score Tracking

Timer Implementation

let timer;
let timeElapsed = 0;

function startTimer() {
    clearInterval(timer);
    timeElapsed = 0;
    $('#timer').text('Time: 0s');
    timer = setInterval(() => {
        timeElapsed++;
        $('#timer').text(`Time: ${timeElapsed}s`);
    }, 1000);
}

$('#restart').click(function () {
    clearInterval(timer);
    startTimer();
});

Score Tracking

let score = 100;
function updateScore() {
    score -= 5;
    $('#score').text(`Score: ${score}`);
}

$(document).on('click', '.card', function () {
    updateScore();
});

8. Making the Game Responsive

Modify the CSS:

@media (max-width: 600px) {
    #game-board {
        grid-template-columns: repeat(3, 80px);
        width: 280px;
    }

    .card {
        width: 80px;
        height: 120px;
        font-size: 1.5em;
    }
}

9. Optimizing Performance

  • Reduce DOM manipulations
  • Use CSS transitions instead of JavaScript animations
  • Optimize event listeners with on()
  • Preload assets (sounds, images)

You’ve built a fully functional card-matching game with jQuery, including: ✅ Randomized cards
✅ Flip animations
✅ Matching logic
✅ Timer and score tracking
✅ Sound effects

You can further improve it by adding levels, themes, or multiplayer modes.


Next Steps

  • Add difficulty levels (e.g., 4×4, 6×6 grids)
  • Implement local storage to save high scores
  • Make an AI opponent for solo play

Would you like me to help with further enhancements?

Leave a Reply

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