#include <Wire.h> #include <LiquidCrystal_I2C.h> #define NUM_MOLES 5 #define START_BUTTON 13 #define BUZZER_PIN 12 #define GAME_DURATION 20000 LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 16, 2); // Change to (0x27,20,4) for 20x4 LCD. int ledPins[NUM_MOLES] = {7, 8, 9, 10, 11}; int buttonPins[NUM_MOLES] = {2, 3, 4, 5, 6}; int activeMole = -1; int score = 0; bool gameActive = false; unsigned long startTime = 0; void setup() { pinMode(START_BUTTON, INPUT_PULLUP); pinMode(BUZZER_PIN, OUTPUT); lcd.init(); lcd.backlight(); // LCD 백라이트 켜기 lcd.setCursor(0, 0); lcd.print("Whack-a-Mole"); lcd.setCursor(0, 1); lcd.print("Press Start!"); for (int i = 0; i < NUM_MOLES; i++) { pinMode(ledPins[i], OUTPUT); pinMode(buttonPins[i], INPUT_PULLUP); } } void loop() { if (!gameActive && digitalRead(START_BUTTON) == LOW) { gameActive = true; startTime = millis(); score = 0; lcd.clear(); lcd.setCursor(0, 0); lcd.print("Game Started!"); } if (gameActive) { if (millis() - startTime >= GAME_DURATION) { gameActive = false; resetMoles(); lcd.clear(); lcd.setCursor(0, 0); lcd.print("Game Over!"); lcd.setCursor(0, 1); lcd.print("Score: " + String(score)); return; } if (activeMole == -1) { activeMole = random(0, NUM_MOLES); digitalWrite(ledPins[activeMole], HIGH); } for (int i = 0; i < NUM_MOLES; i++) { if (digitalRead(buttonPins[i]) == LOW && i == activeMole) { digitalWrite(ledPins[activeMole], LOW); tone(BUZZER_PIN, 1000, 200); score++; lcd.clear(); lcd.setCursor(0, 0); lcd.print("Score: " + String(score)); Serial.print("Score: "); Serial.println(score); delay(300); activeMole = -1; } } } } // Reset all moles (turn off LEDs) void resetMoles() { for (int i = 0; i < NUM_MOLES; i++) { digitalWrite(ledPins[i], LOW); } }
Code
•