const int buttonPins[] = {2, 3, 4, 5}; // Blue, Red, Green, Yellow buttons const int ledPins[] = {6, 7, 8, 9}; // Blue, Red, Green, Yellow LEDs const int activeLED = 13; int sequence[50]; //sets length of input list int userInput[50]; //Set length of user input list int roundNumber = 1; //set round to round 1 int userInputIndex = 0; bool isGameOver = false; //keeps track of state of game bool isCorrect = true; void setup() { //setup uses for loop to set the pinmodes for the led's and buttonPins for (int i = 0; i < 4; i++) { pinMode(ledPins[i], OUTPUT); pinMode(buttonPins[i], INPUT_PULLUP); } pinMode(activeLED, OUTPUT); Serial.begin(9600); randomSeed(analogRead(0)); //ensures the random sequence does not repeat itself each time the game runs } void loop() { if (isGameOver) {// if the player loses the game, these three for loops run so that // every LED will flash three times, indicating the player has lost for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) digitalWrite(ledPins[j], HIGH); delay(500); for (int j = 0; j < 4; j++) digitalWrite(ledPins[j], LOW); delay(500); } isGameOver = false; //reset game status and round number to 1 if the if statement in line 20 is true isCorrect = true; roundNumber = 1; userInputIndex = 0; return; } for (int i = 0; i < roundNumber; i++) { //for loop runs based off round number if (i == roundNumber - 1) sequence[i] = random(0, 4); // checks the round number, and adds another value to the sequence list digitalWrite(ledPins[sequence[i]], HIGH);//the following lines flash the lights using the sequence list delay(500); digitalWrite(ledPins[sequence[i]], LOW); delay(500); } digitalWrite(activeLED, HIGH); // turn on LED to indicate when the user should press buttons for (int i = 0; i < roundNumber; i++) { //for loop runs based off round number bool buttonPressed = false; while (!buttonPressed) { //while button is not pressed, the if statement checks which button was pressed for (int j = 0; j < 4; j++) { if (digitalRead(buttonPins[j]) == LOW) { delay(50); userInput[userInputIndex++] = j; Serial.println(j); while (digitalRead(buttonPins[j]) == LOW); buttonPressed = true; } } } // for loop compares the list values of sequence and userinput. if values are not equal, player loses if (sequence[userInputIndex-1] != userInput[userInputIndex - 1]) { isCorrect = false; break; } } digitalWrite(activeLED, LOW); // for loop compares the list values of sequence and userinput. if values are not equal, player loses for (int i = 0; i < roundNumber; i++) { if (sequence[i] != userInput[i]) { isCorrect = false; break; } } if (isCorrect) { //If player input matches the sequence, then round number is increased //if "isCorrect is false, the player loses roundNumber++; userInputIndex = 0; } else { isGameOver = true; } delay(1000); }