#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const byte ROWS = 4, COLS = 4;
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys),
rowPins, colPins, ROWS, COLS);
const int BUZZER = 10;
String password;
String entered = "";
int attempts = 5;
bool gameOver = false;
void melody() {
tone(BUZZER, 523, 150);
delay(180);
tone(BUZZER, 659, 150);
delay(180);
tone(BUZZER, 784, 150);
delay(180);
tone(BUZZER, 1047, 300);
delay(350);
noTone(BUZZER);
}
void newGame() {
password = String(random(1000, 10000));
entered = "";
attempts = 5;
gameOver = false;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Guess 4 digits");
lcd.setCursor(0, 1);
lcd.print("Left: 5 A=Check");
melody();
}
void setup() {
pinMode(BUZZER, OUTPUT);
randomSeed(analogRead(A0));
lcd.init();
lcd.backlight();
newGame();
}
void loop() {
char key = keypad.getKey();
if (!key) return;
if (key == 'B') {
newGame();
return;
}
if (gameOver) return;
if (key >= '0' && key <= '9' &&
entered.length() < 4) {
entered += key;
tone(BUZZER, 900, 70);
showInput();
}
if (key == '*') {
entered = "";
tone(BUZZER, 500, 100);
showInput();
}
if (key == 'A') {
if (entered.length() != 4) {
tone(BUZZER, 250, 200);
lcd.setCursor(0, 0);
lcd.print("Enter 4 digits ");
delay(700);
showInput();
return;
}
attempts--;
lcd.clear();
if (entered == password) {
lcd.setCursor(0, 0);
lcd.print("Correct!");
lcd.setCursor(0, 1);
lcd.print("You won!");
tone(BUZZER, 1200, 500);
gameOver = true;
} else {
tone(BUZZER, 200, 400);
lcd.setCursor(0, 0);
lcd.print("Wrong password");
if (attempts > 0) {
lcd.setCursor(0, 1);
lcd.print("Attempts: ");
lcd.print(attempts);
delay(1500);
entered = "";
showInput();
} else {
lcd.setCursor(0, 0);
lcd.print("Game over ");
lcd.setCursor(0, 1);
lcd.print("Code: ");
lcd.print(password);
gameOver = true;
}
}
}
}
void showInput() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Code: ");
lcd.print(entered);
lcd.setCursor(0, 1);
lcd.print("Left: ");
lcd.print(attempts);
lcd.print(" A=Check");
}