Build a simple Memory Game with HTML, CSS, and JavaScript

Simple Memory Game | Coding Zemigle

Welcome to this tutorial on building a simple memory game using HTML, CSS, and JavaScript! This classic game is not only a fun way to challenge your memory but also an excellent project for honing your web development skills.

A memory game, also known as a concentration game, involves a set of cards placed face down. The objective is to find pairs of matching cards by flipping them over. Players must remember the locations of previously revealed cards to successfully match pairs. The game continues until all pairs are found, and the player with the fewest moves or fastest time wins.

By the end of this guide, you'll have a fully functional memory game that you can further customize and enhance. Whether you're a beginner looking to apply your basic skills or an experienced developer seeking a fun project, this tutorial will provide you with a solid foundation in game development with web technologies.

Step 01: Project setup

To get started on building your memory game, you'll first need to set up your project files and structure. Follow these steps to create the basic framework for your game:


Create a new folder on your computer where you’ll store all the project files. You can name it something like memory-game.
  • Inside the project folder, create a file named index.html. This file will contain the structure of your game.
  • Create a file named style.css in the same folder. This file will handle the styling of your game.
  • Create a file named script.js. This file will contain the JavaScript needed to make your game interactive.
Step 02: Building the Game Board

Now that your project setup is complete, it’s time to build the game board. This involves creating the HTML structure for the cards, styling them with CSS, and preparing them for interaction with JavaScript.

✲    index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Simple Memory Game | Coding Zemigle</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>

  <div class="game-container">
    <div class="game-board">
      <!-- Cards will be inserted here by JavaScript -->
    </div>
  </div>

  <script src="script.js"></script>
</body>
</html>



With this setup, you’ll have a functional game board with interactive cards. The next steps will involve adding more features, such as a scoring system and game timer, to enhance the gameplay experience.


Step 03: Styling the Game

Now that you have the basic game structure and logic in place, it’s time to focus on styling the game to make it visually appealing and interactive. We’ll add styling for the game board, cards, and animations.

✲    style.css
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: 'Arial', sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.game-container {
  text-align: center;
}

.game-board {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  max-width: 600px;
  margin: 0 auto;
}

.card {
  width: 100px;
  height: 100px;
  background-color: #bada55;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: transparent;
  transition: transform 0.3s;
  border-radius: 8px;
}

.card.flipped, .card.matched {
  background-color: #fff;
  color: #333;
  transform: rotateY(180deg);
}

@media (max-width: 600px) {
  .game-board {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 400px) {
  .card {
    width: 80px;
    height: 80px;
    font-size: 18px;
  }
}



With these styles in place, your memory game will not only be functional but also visually engaging. Feel free to experiment with colors, fonts, and animations to match your design preferences.

Step 04: Adding Game logic

With the basic structure and styling of your memory game complete, it's time to integrate the game logic using JavaScript. This will involve handling card interactions, checking for matches, and managing game states.

✲    script.js
const cardsArray = [
  { name: 'A', id: 1 },
  { name: 'B', id: 2 },
  { name: 'C', id: 3 },
  { name: 'D', id: 4 },
  { name: 'E', id: 5 },
  { name: 'F', id: 6 }
];

// Duplicate cards and shuffle them
const gameCards = [...cardsArray, ...cardsArray].sort(() => Math.random() - 0.5);

const gameBoard = document.querySelector('.game-board');
let flippedCards = [];
let matchedCards = [];

// Create the cards
function createBoard() {
  gameCards.forEach(card => {
    const cardElement = document.createElement('div');
    cardElement.classList.add('card');
    cardElement.setAttribute('data-id', card.id);
    cardElement.innerHTML = `<span>${card.name}</span>`;
    cardElement.addEventListener('click', flipCard);
    gameBoard.appendChild(cardElement);
  });
}

// Flip a card
function flipCard() {
  const clickedCard = this;

  // Prevent flipping more than two cards at once
  if (flippedCards.length < 2 && !flippedCards.includes(clickedCard) && !clickedCard.classList.contains('matched')) {
    clickedCard.classList.add('flipped');
    flippedCards.push(clickedCard);

    if (flippedCards.length === 2) {
      checkForMatch();
    }
  }
}

// Check for a match
function checkForMatch() {
  const [firstCard, secondCard] = flippedCards;

  if (firstCard.dataset.id === secondCard.dataset.id) {
    firstCard.classList.add('matched');
    secondCard.classList.add('matched');
    matchedCards.push(firstCard, secondCard);
  } else {
    setTimeout(() => {
      firstCard.classList.remove('flipped');
      secondCard.classList.remove('flipped');
    }, 1000);
  }

  flippedCards = [];

  // Check for game over
  if (matchedCards.length === gameCards.length) {
    setTimeout(() => alert('Congratulations, you won!'), 500);
  }
}

// Start the game
createBoard();



With these additions, your memory game will have complete functionality, including card flipping, matching logic, game state management, and optional timer features. You can further enhance it by adding more features or customizing the design to suit your preferences.

Conclusion 

Review your game to ensure all functionalities are working as expected. Test different scenarios to verify game logic, styles, and interactions.


Consider gathering feedback from users to identify any areas for improvement. You might also want to add additional features, such as sound effects, difficulty levels, or leaderboards.

Create documentation for your game, including a brief description, how to play, and any credits or acknowledgments. This can be added to a README file in your GitHub repository.PromotionShare your memory game with others through social media, forums, or other platforms. Highlight any unique features or challenges in your game to attract players.

Keep an eye on any bugs or issues reported by players. Plan for future updates and enhancements based on user feedback and your own ideas.By following these steps, you’ll have a fully deployed memory game that’s ready for players to enjoy. Congratulations on completing your project!