-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
84 lines (69 loc) · 1.97 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
let buttonColors = ["red", "blue", "green", "yellow"];
let gamePattern = [];
let userClickedPattern = [];
let level = 0;
let started = false;
let timeout;
$("body").on("keydown", function () {
if (!started) {
$(".title").html("Level 0");
nextSequence();
started = true;
}
});
function playSound(name) {
let audioElement = document.createElement("audio");
audioElement.setAttribute("src", `sounds/${name}.mp3`);
audioElement.play();
}
function animatePress(currentColor) {
$(`#${currentColor}`).addClass("pressed");
timeout = setTimeout(function () {
$(`#${currentColor}`).removeClass("pressed");
}, 100);
}
clearTimeout(timeout);
function checkAnswer(currentLevel) {
console.log(gamePattern);
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
if (gamePattern.length === userClickedPattern.length) {
timeout = setTimeout(function () {
nextSequence();
}, 1000);
}
} else {
let audioElement = document.createElement("audio");
audioElement.setAttribute("src", "sounds/wrong.mp3");
audioElement.play();
$("body").addClass("game-over");
timeout = setTimeout(function () {
$("body").removeClass("game-over");
}, 200);
$(".title").html("Game Over, Press Any Key to Restart");
startOver();
}
}
clearTimeout();
function nextSequence() {
userClickedPattern = [];
level++;
$(".title").html(`Level ${level}`);
let randomNumber = Math.floor(Math.random() * 4);
let randomChosenColor = buttonColors[randomNumber];
gamePattern.push(randomChosenColor);
$(`#${randomChosenColor}`).fadeIn(100).fadeOut(100).fadeIn(100);
playSound(randomChosenColor);
}
function startOver() {
started = false;
userClickedPattern = [];
gamePattern = [];
level = 0;
}
$(".btn").on("click", function () {
let userChosenColor = this.id;
userClickedPattern.push(userChosenColor);
playSound(userChosenColor);
animatePress(userChosenColor);
checkAnswer(userClickedPattern.length - 1);
});