-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
319 lines (283 loc) · 9.64 KB
/
game.js
File metadata and controls
319 lines (283 loc) · 9.64 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
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
const container = document.querySelector(".container");
const history = document.querySelector(".history");
const score = document.querySelector(".score-points");
const lives = document.querySelector(".live-points");
const remaining = document.querySelector(".match-points");
const gameInfoBottom = document.querySelector(".game-info-bottom");
const gameInfoTop = document.querySelector(".game-info-top");
const modal = document.querySelector(".modal");
const bonus = document.querySelector(".bonus");
const modalTitle = document.querySelector(".modal-title");
const modalText = document.querySelector(".modal-text");
const backFaceImageSource = "./images/front-image.png";
const date = new Date();
//game variables
let clickedCardsArray = [];
let scorePoints = 0;
let remainingPoints = 8;
let livePoints = 6;
let hits = 0;
const imagesArray = [
{ name: "Alhamra", source: "./images/alhamra_tower.jpeg" },
{ name: "Biza", source: "./images/biza.jpeg" },
{ name: "Burj Khalifa", source: "./images/burj_khalifa.jpeg" },
{ name: "CN", source: "./images/cn_tower.jpeg" },
{ name: "Liberty", source: "./images/liberty_tower.jpeg" },
{ name: "Big Ben", source: "./images/big_ben.jpeg" },
{ name: "Eifel", source: "./images/eifel_tower.jpeg" },
{ name: "Turning Torso", source: "./images/turning_torso.jpeg" },
{ name: "Alhamra", source: "./images/alhamra_tower.jpeg" },
{ name: "Biza", source: "./images/biza.jpeg" },
{ name: "Burj Khalifa", source: "./images/burj_khalifa.jpeg" },
{ name: "CN", source: "./images/cn_tower.jpeg" },
{ name: "Liberty", source: "./images/liberty_tower.jpeg" },
{ name: "Big Ben", source: "./images/big_ben.jpeg" },
{ name: "Eifel", source: "./images/eifel_tower.jpeg" },
{ name: "Turning Torso", source: "./images/turning_torso.jpeg" }
];
const newGameButton = document.querySelectorAll(".new-game-button");
newGameButton.forEach(button => {
button.addEventListener("click", () => {
// scorePoints = 0;
// remainingPoints = 8;
// livePoints = 6;
// hits = 0;
// handleScore(0);
// handleLives(6);
// handleRemainingMatches(8);
// resetBoard();
// toggleElements();
location.reload();
});
});
const clearHistoryButon = document.querySelector(".clear-history-button");
clearHistoryButon.addEventListener("click", () => {
const isHistoryExist = Object.keys(localStorage).filter(key => key.includes("history")).length;
if (isHistoryExist) {
for (const key in localStorage) {
if (key.includes("history")) {
localStorage.removeItem(key);
}
}
history.classList.add("hidden");
}
})
const shuffleArray = (array) => {
array.sort(() => Math.random() - 0.5)
return array;
}
createElementWtihAttributes = (element, attributes) => {
const HTMLElement = document.createElement(element); //element = div
for (let key in attributes) {
HTMLElement.setAttribute(key, attributes[key]);
}
return HTMLElement;
}
const createCards = () => {
const cards = createElementWtihAttributes("div", { class: "cards" });
const shuffeledCards = shuffleArray(imagesArray);
for (let i = 0; i < shuffeledCards.length; i++) {
const card = createElementWtihAttributes("div", { class: "card", "name": shuffeledCards[i].name });
//face
const cardFace = createElementWtihAttributes("div", { class: "face" });
const faceImage = createElementWtihAttributes("img", { class: "front-face-image", src: shuffeledCards[i].source });
cardFace.appendChild(faceImage);
//back
const cardBack = createElementWtihAttributes("div", { class: "back" });
const backImage = createElementWtihAttributes("img", { class: "back-face-image", src: backFaceImageSource });
cardBack.appendChild(backImage);
card.appendChild(cardFace);
card.appendChild(cardBack);
card.addEventListener("click", (event) => {
card.classList.toggle("show-face");
compareTwoCards(event);
})
cards.appendChild(card);
container.insertBefore(cards, gameInfoBottom); //insert cards before gemInBottom
}
}
const handleBonus = () => {
if (hits === 2) {
livePoints = livePoints + 1;
handleLives(livePoints);
bonus.classList.remove("invisible");
bonus.classList.add("visible");
hits = 0;
setTimeout(() => {
bonus.classList.add("invisible");
bonus.classList.remove("visible");
}, 2000);
}
}
const isMatch = (array) => {
scorePoints++;
remainingPoints--;
hits = hits + 1;
const cards = array[0].parentNode;
array.forEach((card) => {
const placeHolder = createElementWtihAttributes("div", { class: "placeholder" });
setTimeout(() => {
cards.replaceChild(placeHolder, card);
}, 2000);
});
setTimeout(() => {
handleScore(scorePoints);
handleRemainingMatches(remainingPoints);
}, 2000);
handleBonus();
}
const isDifferent = (array) => {
scorePoints--;
livePoints--;
hits = 0; // empty hits
array.forEach((card) => {
setTimeout(() => {
card.classList.remove("show-face");
}, 1000);
});
setTimeout(() => {
handleScore(scorePoints);
handleLives(livePoints);
}, 1000);
}
const compareTwoCards = (evt) => {
const clickedCard = evt.target;
clickedCardsArray.push(clickedCard);
if (clickedCardsArray.length === 2) {
if (clickedCardsArray[0] !== clickedCardsArray[1]) {
if (clickedCardsArray[0].getAttribute("name") === clickedCardsArray[1].getAttribute("name")) {
isMatch(clickedCardsArray);
}
else {
isDifferent(clickedCardsArray);
}
}
clickedCardsArray = []; //empty cardsArray
}
}
const handleScore = (value) => {
score.innerText = value;
}
const handleRemainingMatches = (value) => {
remaining.innerText = value;
if (value === 0) {
handleWin();
}
}
const handleLives = (value) => {
lives.innerText = value;
if (value === 6 || value === 5) {
lives.style.background = "dodgerblue";
}
else if (value === 4 || value === 3) {
lives.style.background = "rgb(255 197 0)";
} else if (value === 2 || value === 1) {
lives.style.background = "rgb(224, 7, 81)";
}
else if (value === 0) {
handleGameOver();
}
}
const resetBoard = () => {
const cards = document.querySelector(".cards");
container.removeChild(cards);
createCards();
}
const handleGameOver = () => {
modal.classList.remove("hidden");
modalTitle.innerText = "The game is over";
modalText.innerText = "You have no more lives. Start a new game to play again";
const stats = { state: false, lives: livePoints, score: scorePoints };
const time = date.getTime();
localStorage.setItem("history" + time.toString(), JSON.stringify(stats)); // dont site an item in storge()
handleHistory();
}
const handleWin = () => {
modal.classList.remove("hidden");
modalTitle.innerText = "Congrats. You won the game";
modalText.innerText = "Start a new game to play again";
gameInfoBottom.classList.add("hidden");
gameInfoTop.classList.add("hidden");
const stats = { state: true, lives: livePoints, score: scorePoints }; // statstic
const time = date.getTime();
localStorage.setItem("history" + time.toString(), JSON.stringify(stats)); //don't returen so therefore use reload
handleHistory();
}
const toggleElements = () => {
if (!modal.classList.contains("hidden")) {
modal.classList.add("hidden");
}
if (gameInfoBottom.classList.contains("hidden")) {
gameInfoBottom.classList.toggle("hidden");
}
if (gameInfoTop.classList.contains("hidden")) {
gameInfoTop.classList.toggle("hidden");
}
}
const handleStats = (array) => {
const historyWin = document.querySelector(".history-win");
const historyLose = document.querySelector(".history-lose");
let nbrOfWins = 0;
let numberOfLoses = 0;
for (let i = 0; i < array.length; i++) {
const state = array[i];
if (state === true) {
nbrOfWins = nbrOfWins + 1;
} else {
numberOfLoses = numberOfLoses + 1;
}
}
historyWin.innerText = `Wins: ${nbrOfWins}`;
historyLose.innerText = `Loses: ${numberOfLoses}`;
}
const handleTopScore = (array) => {
const scoreSpan = document.querySelector(".top-score");
let topScore = -6;
let temp = 0;
for (let i = 0; i < array.length; i++) {
const score = array[i];
temp = score;
if (temp > topScore) {
topScore = temp;
}
}
scoreSpan.innerText = `Top score: ${topScore}`;
}
const handleTopLives = (array) => {
const livesSpan = document.querySelector(".top-lives");
let topLives = 0;
let temp = 0;
for (let i = 0; i < array.length; i++) {
const live = array[i];
temp = live;
if (temp > topLives) {
topLives = temp;
}
}
livesSpan.innerText = `Top lives: ${topLives}`;
}
const handleHistory = () => {
const isHistoryExist = Object.keys(localStorage).filter(key => key.includes("history")).length;
if (isHistoryExist) {
if (history.classList.contains("hidden")) {
history.classList.remove("hidden");
}
const statsArray = [];
const scoresArray = [];
const livesArray = [];
for (const key in localStorage) {
if (key.includes("history")) {
const historyObject = JSON.parse(localStorage[key]);
const { state, score, lives } = historyObject;
statsArray.push(state);
scoresArray.push(score);
livesArray.push(lives);
}
}
handleStats(statsArray);
handleTopScore(scoresArray);
handleTopLives(livesArray);
}
}
createCards();
handleHistory();