// Define pin numbers for segments and common pin
int a = 2;
int b = 3;
int c = 4;
int d = 5;
int e = 6;
int f = 7;
int g = 8;
int cc = 9; // common cathode pin
// Define pins for push buttons
int guessButtonPin = 10;
int submitButtonPin = 11;
// Define variables
int randomNumber;
int playerGuess = 0;
bool guessedCorrectly = false;
void setup() {
// Initialize segments pins as outputs
pinMode(a, OUTPUT);
pinMode(b, OUTPUT);
pinMode(c, OUTPUT);
pinMode(d, OUTPUT);
pinMode(e, OUTPUT);
pinMode(f, OUTPUT);
pinMode(g, OUTPUT);
pinMode(cc, OUTPUT);
// Initialize buttons as inputs with pull-up resistors
pinMode(guessButtonPin, INPUT_PULLUP);
pinMode(submitButtonPin, INPUT_PULLUP);
// Generate a random number
randomSeed(analogRead(0)); // seed the random number generator with analog pin 0
randomNumber = random(10); // generate a random number between 0 and 9
// Display the random number on the 7-segment display
displayNumber(randomNumber);
}
void loop() {
// Read player input
int guessButtonState = digitalRead(guessButtonPin);
int submitButtonState = digitalRead(submitButtonPin);
// If the guess button is pressed, increment player guess
if (guessButtonState == LOW) {
playerGuess = (playerGuess + 1) % 10; // wrap around to 0 after 9
delay(200); // debounce delay
displayNumber(playerGuess); // display current guess
}
// If the submit button is pressed, check the guess
if (submitButtonState == LOW) {
if (playerGuess == randomNumber) {
guessedCorrectly = true;
// Display appropriate feedback for correct guess
displayNumber(10); // Display "C" for correct
} else {
// Display appropriate feedback for incorrect guess
displayNumber(11); // Display "E" for wrong guess
}
delay(1000); // Display feedback for 1 second
resetGame(); // Reset game for the next round
}
}
// Function to display a number on the 7-segment display
void displayNumber(int num) {
// Define common cathode values for each digit
byte digitValues[12] = {
B11111100, // 0
B01100000, // 1
B11011010, // 2
B11110010, // 3
B01100110, // 4
B10110110, // 5
B10111110, // 6
B11100000, // 7
B11111110, // 8
B11110110, // 9
B10000001, // C for correct
B10000110 // E for wrong
};
// Display the corresponding segment values for the given number
if (num >= 0 && num <= 11) {
digitalWrite(cc, LOW); // turn on display
for (int i = 0; i < 8; i++) {
digitalWrite(i + 2, bitRead(digitValues[num], i));
}
}
}
// Function to reset the game for the next round
void resetGame() {
playerGuess = 0;
guessedCorrectly = false;
randomNumber = random(10); // generate a new random number
displayNumber(randomNumber); // display the new random number
}