-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory-game.js
296 lines (250 loc) · 7.29 KB
/
memory-game.js
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// Generate cards for game board
let gameBoard = document.querySelector(".cards-container");
// Possible pairs
let cards = [
[
{ name: 'elephant', content: "<h2>فيل (فيلة)</h2>" },
{ name: 'elephant', image: "./images/elephant.jpg" }
],
[
{ name: 'giraffe', content: "<h2>زرافة (-ات)</h2>" },
{ name: 'giraffe', image: "./images/giraffe.jpg" }
],
[
{ name: 'monkey', content: "<h2>قرد (قرود)</h2>" },
{ name: 'monkey', image: './images/monkey.jpg' }
],
[
{ name: 'cat', content: '<h2>قطة (قطط)</h2>' },
{ name: 'cat', image: './images/cat.jpg' }
],
[
{ name: 'dog', content: '<h2>كلب (كلاب)</h2>' },
{ name: 'dog', image: './images/dog.jpg' }
],
[
{ name: 'bird', content: '<h2>عصفور (عصافير)</h2>' },
{ name: 'bird', image: './images/bird.jpg' }
],
[
{ name: 'ant', content: '<h2>نملة (نمل)</h2>' },
{ name: 'ant', image: './images/ant.jpg' }
],
[
{ name: 'turtle', content: '<h2>سلحفاة (سلاحف)</h2>' },
{ name: 'turtle', image: './images/turtle.jpg' }
],
[
{ name: 'lizard', content: '<h2>سحلية (سحالي)</h2>' },
{ name: 'lizard', image: './images/lizard.jpg' }
],
[
{ name: 'horse', content: '<h2>خيل (خيول)</h2>' },
{ name: 'horse', image: './images/horse.jpg' }
]
];
// Select 10 pairs and shuffle them (NOTE: As it stands there is an unnecessary step. However, if there were more than 10 pairs the current code should draw 10 randomly from the cards array regardless of its length.)
function selectPairs(pairArray) {
let resultArray = [];
for (let i = 0; i < 10; i++) {
for (let x = 0; x < pairArray[i].length; x++) {
resultArray.push(pairArray[i][x]);
}
}
return resultArray;
}
let currentDeck = selectPairs(cards);
// Shuffle function
function shuffle(items) {
for (let i = items.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * i);
[items[i], items[j]] = [items[j], items[i]];
}
return items;
}
let currentDeckShuffled = shuffle(currentDeck);
// Generate divs according to difficulty parameters (NOTE: There are no difficulty parameters currently. In the future I may add that functionality, so I wrote the function to accomodate difficulty levels in the future. Kind of.)
function initializeCardGrid(gridSizeRows, gridSizeCols) {
for (let i = 0; i < gridSizeRows * gridSizeCols; i++) {
let memoryCardContainer = document.createElement('div');
let cardWrapper = document.createElement('div');
let cardFront = document.createElement('div');
let cardBack = document.createElement('div');
memoryCardContainer.classList.add('memory-card-container');
cardWrapper.classList.add('card-wrapper');
cardBack.classList.add('card-back');
cardFront.classList.add('card-front');
cardWrapper.appendChild(cardFront);
cardWrapper.appendChild(cardBack);
memoryCardContainer.appendChild(cardWrapper);
cardWrapper.dataset.animal = currentDeckShuffled[i].name;
gameBoard.appendChild(memoryCardContainer);
if (i < currentDeckShuffled.length) {
if (currentDeckShuffled[i].content) {
cardBack.innerHTML = currentDeckShuffled[i].content;
} else {
let image = document.createElement("img");
image.src = currentDeckShuffled[i].image;
image.classList.add('image-card');
cardBack.appendChild(image);
}
}
}
}
// Flip and check functions
let firstCard, secondCard;
let hasFlippedCard = false;
let score = 0;
let attempts = 0;
let lockBoard = false;
function flipCard() {
if (lockBoard) {
return;
};
if (this === firstCard) {
return;
};
this.classList.add('flipped');
if (!hasFlippedCard) {
firstCard = this;
hasFlippedCard = true;
return;
}
secondCard = this;
checkForMatch();
hasFlippedCard = false;
}
// Checking for match
function checkForMatch() {
lockBoard = true;
if (firstCard.dataset.animal === secondCard.dataset.animal) {
score++;
disableMatches();
updateScore();
} else {
resetCards();
}
attempts++;
updateAttempts();
checkForWin();
}
// Disabling matched cards
function disableMatches() {
setTimeout(() => {
firstCard.removeEventListener('click', flipCard);
secondCard.removeEventListener('click', flipCard);
resetBoard();
}, 1200);
}
// Winning game
function checkForWin() {
if (score >= 10) {
playerWins();
updateBestGame();
}
}
function playerWins() {
createPlayAgainButton();
gameStarted = false;
}
// Reset Cards
function resetCards() {
lockBoard = true;
setTimeout(() => {
firstCard.classList.remove('flipped');
secondCard.classList.remove('flipped');
resetBoard();
}, 1200);
}
function resetBoard() {
firstCard = null;
secondCard = null;
lockBoard = false;
hasFlippedCard = false;
}
// Scoring + attempts
currentScore = document.querySelector('#current-score');
currentAttempts = document.querySelector('#current-attempts');
bestGame = document.querySelector('#best-game');
let bestAttempts;
function updateScore() {
currentScore.textContent = `Found: ${score}/10`;
}
function resetScore() {
score = 0;
updateScore();
}
function updateAttempts() {
currentAttempts.textContent = `Attempts: ${attempts}`;
}
function resetAttempts() {
attempts = 0;
updateAttempts();
}
function updateBestGame() {
if (!bestAttempts || attempts < bestAttempts) {
bestAttempts = attempts;
bestGame.textContent = `${bestAttempts} attempts`;
}
}
// Starting game + buttons
let placeholderText = document.querySelector('#placeholder-text');
startButton = document.querySelector('.start-button');
startButton.addEventListener('click', startGame);
buttonTitle = document.querySelector('.button-title')
let gameStarted = false;
function startGame() {
reShuffleCards();
resetScore();
resetAttempts();
if (!gameStarted) {
placeholderText.style.display = 'none';
gameStarted = true;
initializeCardGrid(4, 5);
let allCards = document.querySelectorAll('.card-wrapper');
allCards.forEach(card => card.addEventListener('click', flipCard));
createStopButton();
return;
}
}
function createStopButton() {
buttonTitle.textContent = 'Stop Game';
startButton.style.backgroundColor = '#FC4A24';
startButton.removeEventListener('click', startGame);
startButton.addEventListener('click', stopGame);
}
function createStartButton() {
buttonTitle.textContent = 'Start Game';
startButton.style.backgroundColor = '#40CE0B';
startButton.removeEventListener('click', stopGame);
startButton.addEventListener('click', startGame);
}
function createPlayAgainButton() {
buttonTitle.textContent = 'Play Again?';
startButton.style.backgroundColor = '#40CE0B';
startButton.removeEventListener('click', stopGame);
startButton.addEventListener('click', playAgain);
}
function playAgain() {
clearBoard();
startGame();
}
function stopGame() {
clearBoard();
createStartButton();
resetScore();
resetAttempts();
placeholderText.style.display = '';
gameStarted = false;
}
// Reset functions
function reShuffleCards() {
currentDeck = selectPairs(cards);
currentDeckShuffled = shuffle(currentDeck);
}
function clearBoard() {
let allBoardElements = document.querySelectorAll('.memory-card-container');
for (let card of allBoardElements) {
card.parentNode.removeChild(card);
}
}