Created
September 9, 2016 07:57
-
-
Save idlefingers/eaadff2096b6b0acec365969bbe78d0f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int redLed = 2; | |
int greenLed = 3; | |
int yellowLed = 4; | |
int blueLed = 5; | |
int redButton = 11; | |
int greenButton = 10; | |
int yellowButton = 9; | |
int blueButton = 8; | |
int leds[] = { redLed, greenLed, yellowLed, blueLed }; | |
int buttons[] = { redButton, greenButton, yellowButton, blueButton }; | |
int sequence[100]; | |
int currroundNumber = 0; | |
void setup() { | |
Serial.begin(9600); | |
// Setup pin modes | |
for (int i = 0; i < 4; i++) { | |
pinMode(leds[i], OUTPUT); | |
} | |
for (int i = 0; i < 4; i++) { | |
pinMode(buttons[i], INPUT_PULLUP); | |
} | |
randomSeed(analogRead(0)); | |
restartGame(); | |
} | |
void restartGame() { | |
currroundNumber = 0; | |
for (int i = 0; i < 100; i++) { | |
sequence[i] = random(4); | |
} | |
// Play starting animation | |
for (int i = 0; i < 4; i++) { | |
flashLED(leds[i]); | |
} | |
delay(1000); | |
} | |
void flashLED(int pin) { | |
digitalWrite(pin, HIGH); | |
delay(250); | |
digitalWrite(pin, LOW); | |
delay(250); | |
} | |
void loop() { | |
// Play sequence | |
Serial.println("Flashing sequence"); | |
for (int i = 0; i <= currroundNumber; i++) { | |
flashLED(leds[sequence[i]]); | |
} | |
// Validate user input | |
int userroundNumber = 0; | |
bool dead = false; | |
while(userroundNumber <= currroundNumber && !dead) { | |
for (int i = 0; i < 4; i++) { | |
if (digitalRead(buttons[i]) == LOW) { | |
digitalWrite(leds[i], HIGH); | |
while(digitalRead(buttons[i]) == LOW) { } | |
digitalWrite(leds[i], LOW); | |
if (sequence[userroundNumber] == i) { | |
userroundNumber++; | |
delay(500); | |
} else { | |
// Wrong - start over! | |
Serial.println("Game over!"); | |
restartGame(); | |
dead = true; | |
} | |
} | |
} | |
} | |
// Check if user had it all right | |
if (!dead) { | |
currroundNumber++; | |
} | |
// Check if all buttons in the sequence was pressed | |
if (currroundNumber == 100) { | |
Serial.print("Game complete!"); | |
restartGame(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment