-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
112 lines (89 loc) · 2.67 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
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
(function memoryGame(that) {
var $game = document.getElementById('game');
var $win = document.getElementById('win');
var $flippedCard = null;
var flippedCard = null;
var cardsPairToFlip;
// Non cheattare.
that.addEventListener('selectstart', function(evt) {
evt.preventDefault();
});
var generateCardValues = function() {
var sequentialValues = ['💋', '🚦', '⚽', '📦', '😊', '👮'];
var sequentialPairs = sequentialValues.concat(sequentialValues);
var randomValues = randomizeValues(sequentialPairs);
return randomValues;
};
var cardSelectorHandler = function(value) {
switch (flippedCard) {
case null:
flippedCard = value;
return 'FLIPPED';
default:
var status = '';
if (flippedCard == value) {
console.log(value, flippedCard, 'matched');
status = 'MATCHED';
} else {
console.log(value, flippedCard, 'mismatch!');
status = 'MISMATCHED';
}
flippedCard = null;
return status;
}
};
function randomizeValues(seqVals) {
var vals = seqVals.concat();
var randomVals = [];
seqVals.forEach(function() {
var randomIndex = Math.floor(Math.random() * vals.length);
randomVals.push(vals.splice(randomIndex, 1)[0]);
});
return randomVals;
}
function renderCards($game, values) {
$game.innerHTML = null;
values.forEach(function(value) {
var $card = document.createElement('div');
$card.innerHTML = value;
$card.classList.add('card');
$card.onclick = function(evt) {
var status = cardSelectorHandler(evt.target.innerText);
switch (status) {
case 'MISMATCHED':
$flippedCard.classList.remove('FLIPPED');
break;
case 'MATCHED':
if (evt.target.classList.contains('FLIPPED')) {
$flippedCard.classList.remove('FLIPPED');
break;
}
isGameFinished();
evt.target.classList.add('MATCHED');
$flippedCard.classList.add('MATCHED');
break;
case 'FLIPPED':
evt.target.classList.add('FLIPPED');
$flippedCard = evt.target;
break;
}
};
$game.appendChild($card);
});
}
function renderVictory() {
$win.classList.add('really');
}
function isGameFinished() {
cardsPairToFlip--;
if (cardsPairToFlip === 0) {
renderVictory();
}
}
that.startMemoryGame = function() {
var randomValues = generateCardValues();
cardsPairToFlip = randomValues.length / 2;
renderCards($game, randomValues);
};
})(this);
startMemoryGame();