#include "pitches.h"
// Constants - define pin numbers for LEDs, buttons and speaker
const uint8_t ledPins[] = {9, 10, 11, 12}; // LEDs connected to pins 9-12
const uint8_t buttonPins[] = {2, 3, 4, 5}; // Buttons connected to pins 2-5
#define SPEAKER_PIN 8 // Speaker connected to pin 8
#define MAX_GAME_LENGTH 100
const int gameTones[] = { NOTE_G3, NOTE_C4, NOTE_E4, NOTE_G5};
// Global variables - store the game state
uint8_t gameSequence[MAX_GAME_LENGTH] = {0};
uint8_t gameIndex = 0;
// Setup function to initialize pins
void setup() {
Serial.begin(9600);
for (byte i = 0; i < 4; i++) {
pinMode(ledPins[i], OUTPUT);
pinMode(buttonPins[i], INPUT_PULLUP);
}
pinMode(SPEAKER_PIN, OUTPUT);
randomSeed(analogRead(A3)); // Initialize random number generator
}
void lightLedAndPlayTone(byte ledIndex) {
digitalWrite(ledPins[ledIndex], HIGH);
tone(SPEAKER_PIN, gameTones[ledIndex]);
delay(300);
digitalWrite(ledPins[ledIndex], LOW);
noTone(SPEAKER_PIN);
}
void playSequence() {
for (int i = 0; i < gameIndex; i++) {
lightLedAndPlayTone(gameSequence[i]);
delay(50);
}
}
byte readButtons() {
while (true) {
for (byte i = 0; i < 4; i++) {
if (digitalRead(buttonPins[i]) == LOW) {
return i;
}
}
delay(1);
}
}
void gameOver() {
Serial.print("Game over! Your score: ");
Serial.println(gameIndex);
gameIndex = 0;
delay(200);
// Sound effect for game over...
}
bool checkUserSequence() {
for (int i = 0; i < gameIndex; i++) {
byte expectedButton = gameSequence[i];
byte actualButton = readButtons();
lightLedAndPlayTone(actualButton);
if (expectedButton != actualButton) {
return false;
}
}
return true;
}
void loop() {
// Update the game sequence with a new random color
gameSequence[gameIndex] = random(0, 4);
gameIndex++;
if (gameIndex >= MAX_GAME_LENGTH) {
gameIndex = MAX_GAME_LENGTH - 1; // Limit game length
}
playSequence();
if (!checkUserSequence()) {
gameOver();
}
delay(300);
}