/
game.js
executable file
·78 lines (76 loc) · 2.72 KB
/
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
class Game {
constructor() {
this.firstCardClicked = null;
this.secondCardClicked = null;
this.totalPossibleMatches = 9;
this.matchCounter = 0;
this.images = ['1.png', '2.png', '3.png', '4.jpg', '5.png', '6.png', '7.png', '8.png', '9.png', '1.png', '2.png', '3.png', '4.jpg', '5.png', '6.png', '7.png', '8.png', '9.png'];
this.cardClicked = this.cardClicked.bind(this);
this.hideBothCards = this.hideBothCards.bind(this);
}
shuffleCards(arr) {
let currentIndex = arr.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = arr[currentIndex];
arr[currentIndex] = arr[randomIndex];
arr[randomIndex] = temporaryValue;
}
return arr;
}
renderCards() {
for (let i = 0; i < this.images.length; i++) {
let container = $('<div>').addClass('card-container');
let card = $('<div>').addClass('card');
let front = $('<div>').addClass('front');
let back = $('<div>').addClass('back');
let image = $('<img>').addClass('image-mod').attr('src','images/' + this.images[i]);
front.append(image);
card.append(front,back);
container.append(card);
$('.game-area').append(container);
}
}
cardClicked() {
if($(event.target).hasClass('flipped')) {
return;
}
$(event.target).fadeOut(250).addClass('flipped');
if (this.firstCardClicked === null) {
music.startAudio('click');
this.firstCardClicked = $(event.target).prev().find('img').attr('src');
} else {
music.startAudio('click');
this.secondCardClicked = $(event.target).prev().find('img').attr('src');
stats.attempts++;
if (this.firstCardClicked === this.secondCardClicked) {
music.startAudio('match');
stats.matches++;
this.matchCounter++;
this.firstCardClicked = null;
this.secondCardClicked = null;
stats.accuracyCalculate();
stats.displayStats();
$('.flipped').removeClass('flipped back').prev().find('img');
if(this.matchCounter === this.totalPossibleMatches){ // win
stats.displayWinModalandSound();
$('.game-area').off('click', '.back', this.cardClicked);
}
return;
} else {
$('.game-area').off('click', '.back', this.cardClicked);
stats.accuracyCalculate();
stats.displayStats();
setTimeout(this.hideBothCards, 2000)
}
}
}
hideBothCards() {
music.startAudio('cardover');
$('.flipped').fadeIn(250).removeClass('flipped');
this.firstCardClicked = null;
this.secondCardClicked = null;
$('.game-area').on('click', '.back', this.cardClicked);
}
}