#include <LiquidCrystal.h>
#include <Keypad.h>
// LCD pin configuration
LiquidCrystal lcd(7, 8, 5, 4, 3, 2); // RS, E, D4, D5, D6, D7
const byte ROWS = 4; // Four rows
const byte COLS = 4; // Four columns
// Define the keymap
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
// Keypad pin configuration
byte rowPins[ROWS] = {23, 25, 27, 29}; // Connect to the row pinouts of the keypad
byte colPins[COLS] = {31, 33, 35, 37}; // Connect to the column pinouts of the keypad
// Initialize the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
lcd.begin(16, 2); // Initialize the LCD (16 characters and 2 lines)
}
void loop() {
static String sequence = ""; // Holds the current sequence
static unsigned long levelDelay = 1000; // Delay between levels, decreases to make the game faster
static int level = 1; // Current level
sequence += String(random(1, 10)); // Append a new random number (1-9) to the sequence
lcd.clear();
lcd.print("Memorize:");
delay(1000); // Wait before showing the sequence
lcd.setCursor(0, 1);
for (int i = 0; i < sequence.length(); i++) {
lcd.print(sequence.charAt(i));
delay(1000); // Wait a second before showing the next number
lcd.clear();
lcd.print("Memorize:");
lcd.setCursor(0, 1);
}
lcd.clear();
lcd.print("Your turn:");
lcd.setCursor(0, 1);
String inputSequence = "";
unsigned long startTime = millis();
while (inputSequence.length() < sequence.length() && millis() - startTime < levelDelay + 5000) { // 5 extra seconds to start typing
char key = keypad.getKey();
if (key) {
inputSequence += key;
lcd.print(key); // Echo the key pressed
}
}
if (inputSequence == sequence) {
lcd.clear();
lcd.print("Correct! Next");
level++;
levelDelay = max(500, (int)levelDelay - 50); // Make the game faster, but not less than 500ms
} else {
lcd.clear();
lcd.print("Wrong! Game Over");
sequence = ""; // Reset the sequence for the next game
level = 1; // Reset to the first level
levelDelay = 1000; // Reset the delay to the initial value
}
delay(2000); // Wait a bit before starting the next level or restarting the game
lcd.clear();
}