-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimonsays.js
More file actions
83 lines (75 loc) · 2.45 KB
/
simonsays.js
File metadata and controls
83 lines (75 loc) · 2.45 KB
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
window.onload = SimonSays;
function SimonSays() {
//Initialize variables
var quads = document.getElementsByClassName('quad'),
statusDisplay = document.getElementById('status'),
startBttn = document.createElement('button'),
colors = [],
simonColors = [],
clickCounter = 0;
//Set up start button created in variables above
//Button is created here instead of being added directly to the markup like the other elements because it makes it easier to attach the simonsTurn function. Alternatives required defining the function globally to make it accessible outside of the scope of SimonSays
startBttn.id = "startButton";
startBttn.onclick = function() {
simonsTurn();
};
startBttn.innerHTML = "Start";
startBttn.setAttribute('class', 'btn btn-default');
statusDisplay.appendChild(startBttn);
for (var i = 0; i < 4; i++) {
//Get quad ID's and assign as colors
//This ensures quads can be named anything and will still match colors indices
colors[i] = quads[i].id;
quads[i].addEventListener("click", getColorClicked, false);
};
function getColorClicked() {
//If color doesn't match Simon's reset all
//Ideally would be broken out into a separate function to be reused by a reset button
if (colors.indexOf(this.id) !== simonColors[clickCounter]) {
statusDisplay.innerHTML = "Wrong <br/>";
simonColors = [];
clickCounter = 0;
statusDisplay.appendChild(startBttn);
}
//If correct and number of clicks is less than number of Simon's colors,
// increment user's clicks
else if (clickCounter !== simonColors.length - 1) {
statusDisplay.innerHTML = "Correct...";
clickCounter++;
}
//If correct and end of user's turn
// reset clickcounter, and start Simon's turn
else {
statusDisplay.innerHTML = "Simon's Turn.";
clickCounter = 0;
simonsTurn();
};
}//End of getColorClicked
function addSimonColor() {
//Adds random color index for Simon
var i = Math.floor(Math.random() * 4);
simonColors.push(i);
}
function flashColor(index) {
var originalClass = quads[index].className;
quads[index].className += " quadactive";
setTimeout(function() {
quads[index].className = originalClass;
}, 1000);
}
function simonsTurn() {
addSimonColor();
var i = 0;
var turn = setInterval(function() {
//Flash only if
if (i < simonColors.length) {
flashColor(simonColors[i]);
i++;
}
else {
clearInterval(turn);
statusDisplay.innerHTML = "Your turn";
};
}, 1500);
}
}//End SimonSays()