-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
106 lines (94 loc) · 2.81 KB
/
script.js
File metadata and controls
106 lines (94 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
$(document).ready(function () {
const images = [
'images/bear.webp',
'images/cat.webp',
'images/dog.webp',
'images/duck.webp',
'images/elephant.webp',
'images/giraffe.jpg',
'images/hamster.jpg',
'images/horse.jpg',
'images/lion.jpg',
'images/monkey.jpg',
'images/rabbit.webp',
'images/snake.jpg',
'images/tiger.jpeg',
'images/turtle.jpg',
'images/zebra.jpg',
];
// Game state variables
let firstCard = null;
let secondCard = null;
let moves = 0;
let matches = 0;
let waitingForThirdCard = false;
// Initialize the game board
function initializeGame() {
$('.grid').empty();
const shuffledImages = [...images, ...images].sort(() => 0.5 - Math.random());
shuffledImages.forEach((imgSrc) => {
const card = $(`
<div class="card" data-image="${imgSrc}">
<div class="front"><img src="${imgSrc}" alt="card" style="display: none;"></div>
<div class="back"></div>
</div>
`);
$('.grid').append(card);
});
// Reset variables
firstCard = null;
secondCard = null;
moves = 0;
matches = 0;
waitingForThirdCard = false;
$('#moves').text('Moves: 0');
$('#matches').text('Matches: 0');
}
// Handle card click
function flipCard($card) {
if ($card.hasClass('flipped') || waitingForThirdCard) return;
$card.addClass('flipped');
$card.find('img').show();
moves++;
$('#moves').text(`Moves: ${moves}`);
if (!firstCard) {
firstCard = $card; // First card flipped
} else {
secondCard = $card; // Second card flipped
checkForMatch();
}
}
// Check if two cards match
function checkForMatch() {
if (firstCard.data('image') === secondCard.data('image')) {
matches++;
$('#matches').text(`Matches: ${matches}`);
firstCard = null;
secondCard = null;
if (matches === images.length) {
alert('Congratulations! You matched all the cards!');
}
} else {
waitingForThirdCard = true;
}
}
// Handle third card selection to reset mismatched cards
function resetMismatchedCards() {
firstCard.removeClass('flipped').find('img').hide();
secondCard.removeClass('flipped').find('img').hide();
firstCard = null;
secondCard = null;
waitingForThirdCard = false;
}
// Attach event listener for card clicks
$('.grid').on('click', '.card', function () {
if (waitingForThirdCard) {
resetMismatchedCards();
}
flipCard($(this));
});
// Reset the game on New Game button click
$('#new-game-button').on('click', initializeGame);
// Initialize the game on page load
initializeGame();
});