// Pin definitions
const int ledPins[] = {3, 4, 5, 6}; // Pins for LEDs
const int buttonPins[] = {9, 10, 11, 12}; // Pins for buttons
const int numLeds = 4;
const int numButtons = 4;
// Game variables
int currentLed = -1;
int score = 0;
unsigned long previousMillis = 0;
unsigned long interval = 4000; // 4 seconds
unsigned long gameStartTime = 0;
unsigned long gameDuration = 300000; // 5 minutes
bool gameRunning = false;
void setup() {
// Initialize LEDs as outputs
for (int i = 0; i < numLeds; i++) {
pinMode(ledPins[i], OUTPUT);
}
// Initialize buttons as inputs with pull-up resistors
for (int i = 0; i < numButtons; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
// Start serial communication
Serial.begin(9600);
// Seed random number generator
randomSeed(analogRead(0));
// Start game
startGame();
}
void loop() {
// Check if the game is running
if (gameRunning) {
// Check if it's time to change the LED
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
changeLed();
previousMillis = currentMillis;
}
// Check if any button is pressed
for (int i = 0; i < numButtons; i++) {
if (digitalRead(buttonPins[i]) == LOW) {
// Button is pressed
if (i == currentLed) {
// Correct button pressed
score++;
if (interval > 1000) {
interval -= 500; // Reduce interval by 500 milliseconds
}
Serial.println("Correct! Score: " + String(score));
} else {
// Wrong button pressed
endGame();
Serial.println("Game Over! Final Score: " + String(score));
}
}
}
// Check if game time is up
if (currentMillis - gameStartTime >= gameDuration) {
endGame();
Serial.println("Time's up! Final Score: " + String(score));
}
}
}
void changeLed() {
// Turn off all LEDs
for (int i = 0; i < numLeds; i++) {
digitalWrite(ledPins[i], LOW);
}
// Generate random LED
currentLed = random(0, numLeds);
// Turn on the random LED
digitalWrite(ledPins[currentLed], HIGH);
}
void startGame() {
gameRunning = true;
score = 0;
interval = 4000; // Reset interval to 4 seconds
previousMillis = millis();
gameStartTime = millis();
Serial.println("Game Started!");
}
void endGame() {
gameRunning = false;
// Turn off all LEDs
for (int i = 0; i < numLeds; i++) {
digitalWrite(ledPins[i], LOW);
}
}