I am trying to code (Newbie) a 501 darts game scoreboard all works so far except when i press the reset button it goes to player 1 displays ok then player 2 is missing, everything is ok after that, any help is appreciated.
thanks in advance
Brian
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
// Initialize the LCD (I2C address: 0x27, size: 20x4)
LiquidCrystal_I2C lcd(0x3F, 20, 4);
// Keypad configuration
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] = {7, 6, 5, 4}; // Connect keypad ROW0, ROW1, ROW2, ROW3 to these pins
byte colPins[COLS] = {3, 2, 1, 0}; // Connect keypad COL0, COL1, COL2, COL3 to these pins
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Game variables
int numPlayers = 1; // Number of players
int scores[4] = {501, 501, 501, 501}; // Scores for up to 4 players
int currentPlayer = 0; // Current player's turn
void setup() {
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the backlight
lcd.clear();
selectPlayers();
}
void loop() {
playGame();
}
void selectPlayers() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Select Players:");
lcd.setCursor(0, 1);
lcd.print("1-4: Press Key");
char key;
while (true) {
key = keypad.getKey();
if (key >= '1' && key <= '4') {
numPlayers = key - '0'; // Convert char to int
break;
}
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Players Selected:");
lcd.setCursor(0, 1);
lcd.print(numPlayers);
delay(2000);
lcd.clear();
}
void playGame() {
showScores();
char key;
lcd.setCursor(0, 0);
lcd.print("P ");
lcd.print(currentPlayer + 1);
lcd.print("'s Turn");
lcd.setCursor(0, 1);
lcd.print("Score: ");
;
int score = 0;
while (true) {
key = keypad.getKey();
if (key >= '0' && key <= '9') {
score = score * 10 + (key - '0'); // Build the score from multiple digits
lcd.setCursor(7, 1);
lcd.print(score);
} else if (key == '#') { // Confirm the score with '#'
scores[currentPlayer] -= score;
break;
} else if (key == '*') { // Clear the entered score with '*'
score = 0;
lcd.setCursor(7, 1);
lcd.print(" "); // Clear display area
lcd.setCursor(7, 1);
} else if (key =='D'){
resetGame();
}
}
// Display updated scores
showScores();
// Move to the next player
currentPlayer = (currentPlayer + 1) % numPlayers;
}
void showScores() {
lcd.clear();
lcd.setCursor(0, 0);
//lcd.print("Scores:");
for (int i = 0; i < numPlayers; i++) {
lcd.setCursor(11, i );
lcd.print("P");
lcd.print(i + 1);
lcd.print(": ");
lcd.print(scores[i]);
}
}
void resetGame() {
for (int i = 0; i < 4; i++) {
scores[i] = 501; // Reset scores
}
lcd.clear();
lcd.setCursor(4, 0);
lcd.print("Game Reset!!");
delay(2500);
lcd.clear();
currentPlayer = 0;
playGame();
showScores();
}