So I'm trying to emulate that old memory-based game Simon with Javascript.
I'm currently trying to have 'Simon' generate randomized commands to be 'played' back (lighting up a div, and playing back audio). I wrote a function which takes a list/array of commands as input, which Simon plays back with 1 second in between each command playback using setInterval.
function go_simon(simon_array) {
var counter = 0;
var interval = setInterval( function() {
var current_val = parseInt(simon_array[counter]);
switch (current_val) {
case 1:
TL_lightOn();
var interval_1 = setTimeout( function() { TL_lightOff() }, 600);
break;
case 2:
BL_lightOn();
var interval_2 = setTimeout( function() { BL_lightOff() }, 600);
break;
case 3:
BR_lightOn();
var interval_3 = setTimeout( function() { BR_lightOff() }, 600);
break;
case 4:
TR_lightOn();
var interval_4 = setTimeout( function() { TR_lightOff() }, 600);
break;
}
counter++;
if (counter >= simon_array.length)
clearInterval(interval);
}, 1000);
}
I have this function placed inside a do-while loop which serves as the main game loop, in which a random command is generated and appended to the ongoing list of commands, and the 'go-simon' function is called which plays back the current list of commands.
I had intended for each loop iteration to consist of:
•Generate random command (1-4)
•Append to running array of commands
•Playback array of commands over time duration - # of commands * seconds
Instead, the loop... loops without executing the go_simon function over however many seconds. I capped the loop to 10 iterations with an alert() for each iteration. This results in the alert being called 10 times in rapid succession and go_simon() being called just once at the end, playing back the array filled with 10 commands.
do {
// create int 1-4 and append to global array
generate_value();
alert(simon_array);
go_simon(simon_array);
if (simon_array.length >= 10) {
alert(simon_array);
condition = false;
}
} while (condition);
Any suggestions on how to get this do-while loop to have the go_simon function properly execute for each iteration?
Many thanks