-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
83 lines (60 loc) · 2.03 KB
/
script.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
import {cardArray} from './beerList.js';
const cardContainer = document.getElementById('card-container');
const resultDisplay = document.getElementById('result');
let scorePoints = 0;
resultDisplay.textContent = scorePoints;
let cardsChosen = [];
let cardsChosenIds = [];
let cardsFound = [];
function gameBoard() {
for (let i = 0; i < cardArray.length; i++) {
const card = document.createElement('img');
card.src = "images/cardCover.png";
card.setAttribute('data-id', i);
card.addEventListener('click', cardFlip);
cardContainer.append(card);
}
}
gameBoard();
function checkMatch() {
const cards = document.querySelectorAll('img');
console.log("Checking card match");
if (cardsChosen[0] == cardsChosen[1]) {
cards[cardsChosenIds[0]].removeEventListener('click', cardFlip);
cards[cardsChosenIds[1]].removeEventListener('click', cardFlip);
cardsFound.push(cardsChosen)
scorePoints += 10;
}
else {
cards[cardsChosenIds[0]].setAttribute('src', 'images/cardCover.png');
cards[cardsChosenIds[1]].setAttribute('src', 'images/cardCover.png');
scorePoints -= 5;
}
if (cardsFound.length === cardArray.length / 2) {
if(scorePoints > 0) {
alert(`CONGRATZ! You finished with ${scorePoints} points!`);
}
else {
alert(`YOU LOSE! ${scorePoints} points...`);
}
for(let card of cards) {
card.setAttribute('src', 'images/cardCover.png');
card.addEventListener('click', cardFlip);
}
cardsFound = [];
scorePoints = 0;
}
cardsChosen = [];
cardsChosenIds = [];
resultDisplay.textContent = scorePoints;
}
function cardFlip() {
let cardId = this.getAttribute('data-id')
cardsChosen.push(cardArray[cardId].name);
cardsChosenIds.push(cardId);
console.log(cardsChosenIds);
this.setAttribute('src', cardArray[cardId].img);
if (cardsChosen.length === 2) {
setTimeout(checkMatch, 500);
}
}