I'm trying to create a memory game called Simon (https://en.wikipedia.org/wiki/Simon_(game))
I've got everything done. The only problem is that whenever the a full sequence has to be shown (when the player presses the wrong button, or if a new sequence has been added), all the sounds are played at the same time and the buttons flash for only a split second. How do I make it so that one button is shown first, the sound for it is played and THEN it goes on to the next? I tried setting setTimeout inside the for loop, but it gives me an error saying that 'btn' is undefined.
Here is my code:
$(document).ready(function(){
var button = $(".buttons");
var redbtn = $("#red");
var bluebtn = $("#blue");
var greenbtn = $("#green");
var yellowbtn = $("#yellow");
var allButtons = [redbtn, bluebtn, greenbtn, yellowbtn];
var sequence, playerTurn, wins, strict, seqPosition;
startGame();
function startGame() {
console.log("Starting game...");
strict = confirm("Would you like to play the difficult mode?");
sequence = [];
playerTurn = false;
wins = 0;
computerTurn();
}
function computerTurn() {
seqPosition = 0; // position of player in sequence
$("#count").html(wins);
console.log("It's the computer's turn");
if (wins === 20) {
alert("You win!");
startGame();
} else {
sequence.push(Math.floor(Math.random() * 4));
console.log("Picked new button");
playSequence();
}
}
function playSequence() {
setTimeout(function(){
console.log("Playing the sequence... " + sequence.toString());
playSound(allButtons[sequence[0]]);
var progress = false;
for (var i = 1; i < sequence.length; i++){
console.log(i);
playSound(allButtons[sequence[i]])
}
playerTurn = true;
}, 1000)
}
function playSound(btn) {
btn.toggleClass("act");
console.log("Playing the sound...");
var link;
switch (parseInt(btn.attr("val"))) {
case 0:
link = "https://s3.amazonaws.com/freecodecamp/simonSound1.mp3";
break;
case 1:
link = "https://s3.amazonaws.com/freecodecamp/simonSound2.mp3";
break;
case 2:
link = "https://s3.amazonaws.com/freecodecamp/simonSound3.mp3";
break;
case 3:
link = "https://s3.amazonaws.com/freecodecamp/simonSound4.mp3";
break;
}
var audio = new Audio(link);
audio.play();
setTimeout(function(){
btn.toggleClass("act")
}, 700);
}
button.on("click", function(){
if (playerTurn) {
var btnVal = parseInt($(this).attr("val"));
if (btnVal === sequence[seqPosition]) {
console.log("Correct button pressed!");
playSound(allButtons[sequence[seqPosition]]);
seqPosition++;
console.log("seq position is " + seqPosition);
setTimeout(function(){
if (seqPosition === sequence.length) {
playerTurn = false;
wins++;
computerTurn();
}
}, 1000);
} else {
playerTurn = false;
if (strict) {
alert("You lose!");
startGame();
} else {
console.log("Incorrect button pressed!");
seqPosition = 0;
var audio = new Audio("horn.mp3");
audio.play();
playSequence();
}
}
}
});
});
Fiddle: https://jsfiddle.net/otep6yx0/