I’m trying to make Simon Says game for the micro:bit, but I have a problem with inputs getting recorded if pressed while the game is running some other code (like displaying the sequence or the game over message).
I tried to disable inputs by using a variable to flag when other code is running. The code for each input first check if that flag is false (0. I didn’t find a way to make a Boolean variable with the blocks), and if so, change it to true and run the main function. This variable is then reset at the end of the main function.
It works for most inputs, but for some reason, the input that was used last to call the main function and set the variable can still be triggered again, which the game react to later as if the variable didn’t existed.
I even tried to make a debug function that records the inputs and call it at the end of the main function before the variable is reset, and it turns out that after each time the input register and the main function is called, it is only “aware” of that input and the next trigger is not taken into account yet, and the variable is indeed set to true.
I also tried to pause the main function before resetting the variable to let the scheduler run the even handlers for the inputs (and hopefully realize that the variable is still true so the if statement should prevent them from calling the main function) but it still didn’t worked.
How can I fix this? Here is the code in JavaScript (I used the blocks to code but the generated JavaScript is easier to share.
“working” is the variable that keeps track if other code is running (or is currently “working”)
Play() is a function to play a sound and display an arrow pointing at an input (because I can’t make the buttons glow like in the real Simon Says).
The main (Check) function:
function Check (num: number) {
if (sequence[index] == num) {
Play(num)
index += 1
if (index >= length) {
sequence.push(randint(0, 3))
length += 1
basic.pause(500)
for (let index = 0; index <= length - 1; index++) {
Play(sequence[index])
basic.pause(100)
}
index = 0
}
} else {
music.play(music.stringPlayable("C5 A B G A F G E ", 120), music.PlaybackMode.LoopingInBackground)
basic.showString("Game Over")
music.stopAllSounds()
basic.showString("Score:")
basic.showString("" + (length - 1))
sequence = [randint(0, 3)]
index = 0
length = 1
Play(sequence[0])
}
basic.pause(100)
Working = 0
Example input:
input.onButtonPressed(Button.B, function () {
if (Working == 0) {
Working = 1
Inputs.push("B")
Check(1)
}