If you are a beginner in Javascript, you need to know this. Javascript is a basic programming language to hone a skill in your logic. There are many simple projects in Javascript, like calculators, games, memory cards, and so on. But, this time, we are learning about how to make a simple game project, this is a memory card project. Oke, let's get started!
First, prepare your text editor as usual and type HTML code (don't forget to connect CSS & Javascript files).
Listen, your code can different from mine. But, you must remember your tag id
or class
for we use it later in the Javascript file.
This is my code:
<!DOCTYPE html>
<html>
<head>
<title>Game Memory Card</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="game-board">
<div class="card" onclick="flipCard(this)">
<img src="card-back.png" class="card-back" alt="Card Back">
<img src="card-front-1.png" class="card-front" alt="Card Front 1">
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Then, create your code CSS for give the styling to your HTML.
.game-board {
display: flex;
flex-wrap: wrap;
width: 500px;
margin: 0 auto;
}
.card {
width: 100px;
height: 100px;
perspective: 600px;
}
.card img {
width: 100%;
height: 100%;
backface-visibility: hidden;
}
.card-back {
transform: rotateY(180deg);
}
.matched {
opacity: 0.6;
}
Oke, here we are! we will give the function to the project us!
let flippedCards = [];
let matchedCards = [];
function flipCard(card) {
if (card.classList.contains('matched')) {
return;
}
card.classList.add('flipped');
flippedCards.push(card);
if (flippedCards.length === 2) {
setTimeout(checkForMatch, 1000);
}
}
function checkForMatch() {
const card1 = flippedCards[0];
const card2 = flippedCards[1];
if (card1.firstChild.src === card2.firstChild.src) {
card1.classList.add('matched');
card2.classList.add('matched');
matchedCards.push(card1, card2);
} else {
card1.classList.remove('flipped');
card2.classList.remove('flipped');
}
flippedCards = [];
if (matchedCards.length === 8) {
alert('Congratulations! You win!');
}
}
In the above example, there are 8 pairs of cards (a total of 16 cards). When a card is clicked, the flipCard
function will be called to flip the card and check if there is a matching pair of cards using the checkForMatch
function. If there is a match, both cards will be marked with the "matched" class, and if all pairs are matched, a message 'Congratulations! You win!' will be displayed.
Make sure to provide the appropriate card images and replace them with valid image sources in the HTML code.
Then, you can create image files named "card-back.png", "card-front-1.png", and so on for each different front card. You can also modify the CSS style to customize the appearance of the game according to your preferences.
I hope this helps you create a simple website for a memory card game! If you have any further questions, please let me know.