#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);

const int buttonPinA = 2; //ปุ่มทีม
const int buttonPinB = 3; 
const int resetPin = 4;  

int scoreTeamA = 0; 
int scoreTeamB = 0; 

bool teamAWon = false; 
bool teamBWon = false; 

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Team A: 0");
  lcd.setCursor(0, 1);
  lcd.print("Team B: 0");

  pinMode(buttonPinA, INPUT_PULLUP);
  pinMode(buttonPinB, INPUT_PULLUP);
  pinMode(resetPin, INPUT_PULLUP);
}

void loop() {
  if (!teamAWon && digitalRead(buttonPinA) == LOW) {
    delay(100);
    scoreTeamA++;
    ScoreDisplay();
    check();
  }

  if (!teamBWon && digitalRead(buttonPinB) == LOW) {
    delay(100);
    scoreTeamB++;
    ScoreDisplay();
    check();
  }

  if (digitalRead(resetPin) == LOW) {
    delay(100);
    scoreTeamA = 0;
    scoreTeamB = 0;
    teamAWon = false;
    teamBWon = false;
    lcd.clear(); //รีเซ็ตข้อมูลของ lcd
    lcd.setCursor(0, 0);
    lcd.print("Team A: 0"); // รีเซ็ตคะแนนและข้อความทีม
    lcd.setCursor(0, 1);
    lcd.print("Team B: 0"); 
  }
}

void ScoreDisplay() {
  lcd.setCursor(8, 0);
  lcd.print("     "); // ลบคะแนนทีม
  lcd.setCursor(8, 0);
  lcd.print(scoreTeamA); // แสดงคะแนนทีม

  lcd.setCursor(8, 1);
  lcd.print("     "); 
  lcd.setCursor(8, 1);
  lcd.print(scoreTeamB); 
}

void check() {
    if (scoreTeamA >= 10 && (scoreTeamA - scoreTeamB) >= 2) {
    teamAWon = true;
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Team A WINNER");
  }

  if (scoreTeamB >= 10 && (scoreTeamB - scoreTeamA) >= 2) {
    teamBWon = true;
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Team B WINNER");
  }
}