In this article, we'll look at how to create a simple memory game using HTML, CSS, and JavaScript. We will explain each piece of code step by step so that even those who are new to programming can understand and replicate the result. We'll look at how to create a page structure, style it, and add game logic to bring your cards to life. Let's get started! 🚀

1. What is a memory game? 🧠
Memory Game is a classic game in which the player must find pairs of identical cards, opening them in turn. The main task is to remember the location of each card in order to successfully find pairs. This is a great exercise for training memory and concentration.
2. Project structure 📁
Our project consists of three main files:
index.html: the structure of the game, what the user sees.
style.css: styles that make the game beautiful and pleasant to look at.
script.js: game logic that determines the behavior of cards when interacting with the user.
We also have a folder images, containing images of cards that will be used in the game.
3. HTML: creating the basis of the page 📝
Let's start with the HTML file. It contains the basic structure of our game, which is a game board and connected style and script files:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Игра на память</title>
</head>
<body>
<div class="game-board">
<!-- Карты будут генерироваться здесь -->
</div>
<script src="script.js"></script>
</body>
</html>Code explanation
<div class="game-board">: This is the container in which all the cards will be located. Later we will add them dynamically using JavaScript. This is the main place for user interaction with the game.<link rel="stylesheet" href="style.css">: We connect the CSS file to style our game and make it visually appealing.<script src="script.js">: We connect JavaScript to add game logic and make the game interactive.
4. CSS: adding beauty 🎨
Now let's move on to CSS. Let's style our game to make it look attractive and be comfortable for the player.
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
font-family: Arial, sans-serif;
margin: 0;
}
.game-board {
display: grid;
grid-template-columns: repeat(4, 100px);
grid-gap: 10px;
}
.card {
width: 100px;
height: 150px;
background-color: #ffffff;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
}
.card img {
max-width: 100%;
max-height: 100%;
display: none;
}
.card.flipped img {
display: block;
}Code explanation
body: We center all the content on the screen so that the game looks nice and is in the center. This will create a pleasant user experience..game-board: We use grid layout for organizing cards in a grid. This helps to make the arrangement of the cards neat and even..card: Styles for cards. They will have a beautiful white background, shadow and rounded corners, which will make them visually appealing. When the user hovers the mouse, the map should appear interactive..card img: By default, the card images are hidden, as the player first sees only the card's back..flipped: When the card is flipped, we show the image so that the player can see what is hidden under it.
5. JavaScript: adding game logic 🧩
Now the most interesting thing — let's add the logic of the game using JavaScript. JavaScript is responsible for the player's interaction with the cards, checking matches and controlling the game. Let's take a look at each function:
const cardsArray = [
{ name: 'card1', img: 'images/card1.png' },
{ name: 'card2', img: 'images/card2.png' },
// Add the remaining pairs of cards
];
let firstCard = null;
let secondCard = null;
let lockBoard = false;
function createBoard() {
const gameBoard = document.querySelector('.game-board');
const shuffledCards = [...cardsArray, ...cardsArray].sort(() => 0.5 - Math.random());
shuffledCards.forEach(card => {
const cardElement = document.createElement('div');
cardElement.classList.add('card');
cardElement.dataset.name = card.name;
const cardImage = document.createElement('img');
cardImage.src = card.img;
cardElement.appendChild(cardImage);
cardElement.addEventListener('click', flipCard);
gameBoard.appendChild(cardElement);
});
}
function flipCard() {
if (lockBoard) return;
if (this === firstCard) return;
this.classList.add('flipped');
if (!firstCard) {
firstCard = this;
return;
}
secondCard = this;
checkForMatch();
}
function checkForMatch() {
if (firstCard.dataset.name === secondCard.dataset.name) {
disableCards();
} else {
unflipCards();
}
}
function disableCards() {
firstCard.removeEventListener('click', flipCard);
secondCard.removeEventListener('click', flipCard);
resetBoard();
}
function unflipCards() {
lockBoard = true;
setTimeout(() => {
firstCard.classList.remove('flipped');
secondCard.classList.remove('flipped');
resetBoard();
}, 1000);
}
function resetBoard() {
[firstCard, secondCard, lockBoard] = [null, null, false];
}
document.addEventListener('DOMContentLoaded', createBoard);Code explanation
Array
cardsArray: Contains objects with information about cards, including their name and image. We duplicate each card to create pairs.Variables
firstCard,secondCard,lockBoard: These variables help to track the state of the game.firstCardandsecondCardstore information about the current flipped cards, andlockBoardprevents other cards from being flipped while matches are being checked.Function
createBoard(): Creates a game board. We shuffle the cards to make each game unique and interesting, and then add the cards to the board.Function
flipCard(): Controls the flipping of the card. If this is the first flipped card, it is saved infirstCard. If this is the second card, check if they match.Function
checkForMatch(): Compares two flipped cards. If they match,disableCards()is called to disable the ability to flip these cards.Functions
disableCards()andunflipCards(): If the cards match, we leave them open and disable the click event. If they do not match, we turn them back in a second.Function
resetBoard(): Resets the values of the variables so that the game can continue without errors.Event
DOMContentLoaded: Ensures that ourcreateBoard()function is called when all HTML is loaded.
6. Conclusion 🎉
Congratulations! Now you have a complete understanding of how to create a simple memory game using HTML, CSS, and JavaScript. We have gone from a basic HTML structure to complex game logic using JavaScript. This game is a great way to practice the basics of programming and improve your DOM skills. Don't be afraid to experiment and add new features, such as a score counter or timer! 😊
