#include <LiquidCrystal.h>
#include <Keypad.h>
// WELCOME!!! PLAY THE GUESSING GAME
// PRESS # TO START THE GAME
// CHOOSE THE NUMBER FROM 0 - 9
// THE GAME WILL SAY HIGHER OR LOWER IF INCORRECT
// YOU ONLY HAVE 3 CHANCES PER GAME
// Click # to play again after the screen is blank
LiquidCrystal lcd(8, 9, 10, 11, 12, 13);
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {26, 22, 21, 20}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {19, 18, 17, 16}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
int secretNumber;
int attempts = 3;
bool gameActive = false;
void setup() {
randomSeed(analogRead(0));
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print("Play Guess the #");
lcd.setCursor(0, 1);
lcd.print("Press # to play");
delay(2000);
lcd.clear();
}
void loop() {
if (!gameActive) {
char key = keypad.getKey();
if (key == '#') {
startGame();
}
} else {
char key = keypad.getKey();
if (key >= '0' && key <= '9') {
int guess = key - '0';
checkGuess(guess);
}
}
}
void startGame() {
secretNumber = random(10);
attempts = 3;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Choose your");
lcd.setCursor(0, 1);
lcd.print("answer: ");
gameActive = true;
}
void checkGuess(int guess) {
if (guess == secretNumber) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Congratulations!");
delay(3000);
gameActive = false;
lcd.clear();
} else {
lcd.clear();
lcd.setCursor(0, 1);
if (guess < secretNumber) {
lcd.print("Higher");
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Lower");
}
attempts--;
if (attempts == 0) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Game Over!");
lcd.setCursor(0, 1);
lcd.print("Answer: ");
lcd.print(secretNumber);
delay(3000);
gameActive = false;
lcd.clear();
}
}
}