Skip to content

Instantly share code, notes, and snippets.

@idlefingers
Created September 9, 2016 07:56
Show Gist options
  • Save idlefingers/350bacf032c191797005e4e57c1966ef to your computer and use it in GitHub Desktop.
Save idlefingers/350bacf032c191797005e4e57c1966ef to your computer and use it in GitHub Desktop.
int redLed = 2;
int redButton = 11;
int greenLed = 3;
int greenButton = 10;
int yellowLed = 4;
int yellowButton = 9;
int blueLed = 5;
int blueButton = 8;
int leds[] = { redLed, greenLed, yellowLed, blueLed };
int buttons[] = { redButton, greenButton, yellowButton, blueButton };
int sequence[100];
int currentRound;
int currentPosition;
bool waitingForInput;
void setupNewGame() {
for (int i = 0; i < 100; i++) {
sequence[i] = random(4);
}
currentRound = 1;
currentPosition = 0;
waitingForInput = false;
}
void setup() {
randomSeed(analogRead(0));
for (int i = 0; i < 4; i++) {
pinMode(leds[i], OUTPUT);
pinMode(buttons[i], INPUT_PULLUP);
}
setupNewGame();
blinkAllLeds(2);
delay(500);
Serial.begin(9600);
}
void loop() {
if (waitingForInput) {
readInput();
} else {
playSequence();
waitingForInput = true;
}
}
void readInput() {
for(int i = 0; i < 4; i++) {
if (digitalRead(buttons[i]) == LOW) {
digitalWrite(leds[i], HIGH);
while (digitalRead(buttons[i]) == LOW) {
// Chillax
delay(50);
}
digitalWrite(leds[i], LOW);
checkIfLastInputCorrect(i);
}
}
}
void checkIfLastInputCorrect(int buttonIndex) {
if (buttonIndex == sequence[currentPosition]) {
currentPosition++;
Serial.print("Correct. next in sequence is: ");
Serial.println(sequence[currentPosition]);
if (currentPosition >= currentRound) {
currentRound++;
currentPosition = 0;
waitingForInput = false;
delay(500);
}
} else {
Serial.print("*Wrong* last: ");
Serial.print(sequence[buttonIndex]);
Serial.print(" expected: ");
Serial.println(sequence[currentPosition]);
gameOver();
}
}
void playSequence() {
Serial.print("Playing sequence for round ");
Serial.println(currentRound);
for (int i=0; i < currentRound; i++) {
blinkLed(leds[sequence[i]]);
}
}
void gameOver() {
blinkAllLeds(5);
setupNewGame();
delay(1000);
}
void blinkLed(int led) {
digitalWrite(led, HIGH);
delay(500);
digitalWrite(led, LOW);
delay(500);
}
void blinkAllLeds(int numberOfTimes) {
for (int x = 0; x < numberOfTimes; x++) {
for (int i = 0; i < 4; i++) {
digitalWrite(leds[i], HIGH);
}
delay(100);
for (int i = 0; i < 4; i++) {
digitalWrite(leds[i], LOW);
}
delay(100);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment