-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.js
79 lines (72 loc) · 2.23 KB
/
memory.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
let startButton = document.querySelector('.start-game');
let squares = document.getElementsByClassName('square');
displayCurrent = document.querySelector('.result__current');
displayBest = document.querySelector('.result__best');
let level = 1;
let activeRow = [];
let currentPoints = 0;
let record = 0;
let currentEl = 0;
startButton.addEventListener('click', function() {
startButton.classList.toggle('start-game_visible');
activeRow = generateAndHighlight(level);
console.log(activeRow);
});
function generateAndHighlight(n) {
let row = new Array(n);
for (let i = 0; i < n; i++) {
row[i] = getRandomInt(0, 9);
}
highlight(row, 0);
return row;
}
function highlight(row, start){
if (start < row.length) {
squares[row[start]].classList.toggle('square_right');
setTimeout(function() {
squares[row[start]].classList.toggle('square_right');
}, 300);
setTimeout(function() {
highlight(row, start + 1);
}, 450);
}
}
function getRandomInt(min, max){
return Math.floor(Math.random() * (max - min)) + min;
}
for (let i = 0; i < squares.length; i++) {
squares[i].addEventListener('click', checkAnswer);
}
function checkAnswer(evt){
if (Number(evt.target.id) === activeRow[currentEl]) {
evt.target.classList.toggle('square_right');
setTimeout(function() {
evt.target.classList.toggle('square_right');
}, 200);
currentPoints += 1;
displayCurrent.innerText = currentPoints;
if (currentPoints > record) {
record = currentPoints;
displayBest.innerText = record;
}
currentEl += 1;
if (currentEl === activeRow.length) {
currentEl = 0;
level += 1;
setTimeout(function() {
activeRow = generateAndHighlight(level);
}, 300);
}
} else {
evt.target.classList.toggle('square_wrong');
setTimeout(function() {
evt.target.classList.toggle('square_wrong');
}, 200);
currentPoints = 0;
displayCurrent.innerText = 0;
currentEl = 0;
level = 1;
activeRow = [];
startButton.classList.toggle('start-game_visible');
}
}