// Define the pin numbers for the targets and LEDs
const int targetPins[] = {2, 3};
const int ledPins[] = {8, 9};
const int numTargets = sizeof(targetPins)/sizeof(int);
// Variable to keep track of hits and the active target
int hitCount = 0;
int activeTarget = -1;
// Variable to keep track of the game state
unsigned long startTime;
const unsigned long gameTime = 10 * 1000; // 10 seconds
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set the target pins as inputs with pullup resistors
// Set the LED pins as outputs
for (int i = 0; i < numTargets; i++) {
pinMode(targetPins[i], INPUT_PULLUP);
pinMode(ledPins[i], OUTPUT);
digitalWrite(ledPins[i], LOW);
}
// Start the game
startGame();
}
void loop() {
// Check if the game is over
if (millis() - startTime >= gameTime) {
// Print the final score
Serial.print("Game over! Final score: ");
Serial.println(hitCount);
// Print time left
Serial.println("Time left: 0 seconds");
// Wait for the player to reset the game
int resetHits = 0;
while (resetHits < 3) {
for (int i = 0; i < numTargets; i++) {
if (digitalRead(targetPins[i]) == LOW) {
resetHits++;
delay(200); // Debounce the button press
}
}
}
// Reset the game
startGame();
} else {
// Print current score and time left every second
Serial.print("Current score: ");
Serial.println(hitCount);
Serial.print("Time left: ");
Serial.print((gameTime - (millis() - startTime)) / 1000);
Serial.println(" seconds");
delay(1000); // Wait for a second before printing again
}
// Check each target
for (int i = 0; i < numTargets; i++) {
// If the active target is hit (reads LOW because of pullup resistor)
if (i == activeTarget && digitalRead(targetPins[i]) == LOW) {
// Increment the hit count
hitCount++;
// Turn off the current target's LED
digitalWrite(ledPins[activeTarget], LOW);
// Choose a new active target at random
activeTarget = random(numTargets);
// Turn on the new target's LED
digitalWrite(ledPins[activeTarget], HIGH);
// Wait a bit to debounce the button press
delay(100);
// Now wait for the target to be released
while (digitalRead(targetPins[i]) == LOW) {
delay(10);
}
}
}
}
void startGame() {
// Reset the hit count and start time
hitCount = 0;
startTime = millis();
// Turn off all LEDs
for (int i = 0; i < numTargets; i++) {
digitalWrite(ledPins[i], LOW);
}
// Choose an initial active target at random
activeTarget = random(numTargets);
// Turn on the active target's LED
digitalWrite(ledPins[activeTarget], HIGH);
}