-
-
Save JFKingsley/7616259 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
const int LIGHT_PIN = 9; | |
const int BUTTON_PIN = 5; | |
const int DIFFICULTY = 5; | |
int ledSequence[DIFFICULTY]; | |
/** | |
* In this mode, the game shows the user a sequence to copy | |
*/ | |
void speak() { | |
generateSequence(); | |
for(int ii = 0 ; ii < DIFFICULTY ; ii ++) { | |
int led = ledSequence[ii] + LIGHT_PIN; | |
digitalWrite(led, HIGH); | |
delay(1000); | |
digitalWrite(led, LOW); | |
delay(200); | |
} | |
} | |
/** | |
* In this mode, the game listens to the user to see if they got the sequence right | |
*/ | |
void listen() { | |
int fail = 0; | |
int succeed = 0; | |
int ii = 0; | |
while( !fail && !succeed) { | |
int button = listenForButton(); | |
if(button != ledSequence[ii]) { | |
fail = 1; | |
} else { | |
ii++; | |
} | |
if(ii > DIFFICULTY) { | |
succeed = 1; | |
} | |
} | |
if(fail) { | |
showFailure(); | |
} else { | |
showSuccess(); | |
} | |
} | |
/* | |
* Flash all the LEDS | |
*/ | |
void showFailure() { | |
for(int count = 0 ; count < 10 ; count ++ ) { | |
for(int ii = 0 ; ii < 4 ; ii++ ) { | |
digitalWrite(ii, HIGH); | |
} | |
delay(100); | |
for(int ii = 0 ; ii < 4 ; ii++ ) { | |
digitalWrite(ii, LOW); | |
} | |
delay(100); | |
} | |
} | |
/* | |
* Cylon the LEDS | |
*/ | |
void showSuccess() { | |
for(int count = 0 ; count < 10 ; count ++) { | |
// Cycle up | |
for(int ii = 0 ; ii < 4 ; ii++) { | |
int led = LIGHT_PIN + ii; | |
digitalWrite(led, HIGH); | |
digitalWrite(led - 1, LOW); | |
delay(100); | |
} | |
// Cycle down | |
for(int ii = 0 ; ii < 4 ; ii++) { | |
int led = LIGHT_PIN + (3 - ii); | |
digitalWrite(led, HIGH); | |
digitalWrite(led + 1, LOW); | |
delay(100); | |
} | |
} | |
} | |
int listenForButton() { | |
int button = -1; | |
while(button == -1) { | |
for(int ii = BUTTON_PIN ; ii < BUTTON_PIN + 4 ; ii++ ) { | |
int push = digitalRead(ii); | |
if(push == HIGH) { | |
button = ii; | |
} | |
} | |
} | |
int pressed = 1; | |
while(pressed) { | |
pressed = (HIGH == digitalRead(button)); | |
} | |
return button; | |
} | |
void generateSequence() { | |
for(int ii = 0 ; ii < DIFFICULTY ; ii++ ) { | |
int number = random(0, 4); | |
ledSequence[ii] = number; | |
} | |
} | |
void setup() { | |
randomSeed (analogRead (0)); | |
for (int ii = LIGHT_PIN ; ii < LIGHT_PIN + 4 ; ii++) { | |
pinMode(ii, OUTPUT); | |
} | |
for (int ii = BUTTON_PIN ; ii < BUTTON_PIN + 4 ; ii++) { | |
pinMode(ii, INPUT); | |
} | |
} | |
void loop() { | |
// First of all, show the user a sequence | |
speak(); | |
// Then wait for them to follow it | |
listen(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment