forked from sergeassane/codepipeline-s3-game
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
77 lines (67 loc) · 2.78 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
document.addEventListener('DOMContentLoaded', () => {
const grid = document.querySelector('#game-board');
const startButton = document.getElementById('start-game');
let cardsChosen = [];
let cardsChosenId = [];
let cardsWon = [];
const cardArray = [
{ name: 'card1', img: 'images/distracted.png' },
{ name: 'card1', img: 'images/distracted.png' },
{ name: 'card2', img: 'images/drake.png' },
{ name: 'card2', img: 'images/drake.png' },
{ name: 'card3', img: 'images/fine.png' },
{ name: 'card3', img: 'images/fine.png' },
{ name: 'card4', img: 'images/rollsafe.png' },
{ name: 'card4', img: 'images/rollsafe.png' },
{ name: 'card5', img: 'images/success.png' },
{ name: 'card5', img: 'images/success.png' },
// ...add more pairs as needed
];
function shuffle(array) {
array.sort(() => 0.5 - Math.random());
}
function createBoard() {
shuffle(cardArray);
grid.innerHTML = '';
cardsWon = [];
for (let i = 0; i < cardArray.length; i++) {
const card = document.createElement('img');
card.setAttribute('src', 'images/blank.png');
card.setAttribute('data-id', i);
card.addEventListener('click', flipCard);
grid.appendChild(card);
}
}
function flipCard() {
let cardId = this.getAttribute('data-id');
if (!cardsChosenId.includes(cardId)) {
cardsChosen.push(cardArray[cardId].name);
cardsChosenId.push(cardId);
this.setAttribute('src', cardArray[cardId].img);
if (cardsChosen.length === 2) {
setTimeout(checkForMatch, 500);
}
}
}
function checkForMatch() {
const cards = document.querySelectorAll('#game-board img');
const firstCardId = cardsChosenId[0];
const secondCardId = cardsChosenId[1];
if (cardsChosen[0] === cardsChosen[1] && firstCardId !== secondCardId) {
cards[firstCardId].style.visibility = 'hidden';
cards[secondCardId].style.visibility = 'hidden';
cards[firstCardId].removeEventListener('click', flipCard);
cards[secondCardId].removeEventListener('click', flipCard);
cardsWon.push(cardsChosen);
} else {
cards[firstCardId].setAttribute('src', 'images/blank.png');
cards[secondCardId].setAttribute('src', 'images/blank.png');
}
cardsChosen = [];
cardsChosenId = [];
if (cardsWon.length === cardArray.length / 2) {
alert('Congratulations! You found them all!');
}
}
startButton.addEventListener('click', createBoard);
});