Programming Our Game

Write the program to play the game.

In our game so far, we play a tone to signal the start and generate a random sequence. The next step is to get the input from the player and see if it matches our sequence. We will do this by looping through our pattern and checking if the input from the player matches the value in the pattern. We will delete the test flashes that we wrote in the last step and work on our loop.

// Use arrays to hold our pin numbers and the pattern.
// This will let us use a loop to go through the values.
int speaker = 9;
int ledPin[] = { 67 };
int inPin[] = { 24 };
int pattern[5];  // This array will hold the pattern we generate.

// Need some notes
int C = 523;
int F = 698;

void setup() {
pinMode(speakerOUTPUT);
pinMode(ledPin[0], OUTPUT);
pinMode(ledPin[1], OUTPUT);
pinMode(inPin[0], INPUT);
pinMode(inPin[1], INPUT);
randomSeed(analogRead(0));  // Ensures that pattern is different at every reset
}

void loop() {
play_start_tones();
generate_pattern();

// Go through each note in the pattern and see if the player matches it
for (int i = 0i < 5i++) {
// Until the player pushes a button, do nothing
digitalWrite(ledPin[0], HIGH);
delay(250);
digitalWrite(ledPin[0], LOW);
delay(250);
if (pattern[i] == 1) {
break;
}
}
digitalWrite(ledPin[1], HIGH);
delay(250);
digitalWrite(ledPin[1], LOW);
delay(250);
if (pattern[i] == 0) {
break;

}
}
}
}

void play_start_tones() {
for (int i = 0i < 3i++) {
tone(speakerC);
delay(350);
noTone(speaker);
delay(350);
}
tone(speakerF);
delay(350);
noTone(speaker);
}

void generate_pattern() {
// Generate random pattern
for (int i = 0i < 5i++) {
int number = random(0,2);
pattern[i] = number;
digitalWrite(ledPin[number], HIGH);
delay(500);
digitalWrite(ledPin[number], LOW);
delay(500);
}
}

The first thing to do inside our loop is to wait for the player to push a button. The

`while ((digitalRead(inPin[0])) == LOW && (digitalRead(inPin[1]) == LOW)) { }`
line just waits for the user to push a button. Once a button is pushed, we need to determine which one. The two if statements take care of that. Then, depending on which button was pushed, we light up the led, to give the user some feedback and then check if this was the correct button to push or not. If it is incorrect, we break out of our loop and the game starts over. If it is correct, the program then waits for the next button push.

As in our other steps, once we have our code working, it's a good idea to move it into a function. In this case, we can also look at some other features of functions, namely, the ability to send variables to it and getting return values from them.