#include <LiquidCrystal.h>
#include <EEPROM.h>
// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
const int buttonLose =  9;   
const int buttonWin =  8;    
const int startGame =  6;
const int buzzer =  10;
int startState = 0;
int winState = 0;
int loseState = 0;
int isPlaying = 0;
float recoder = 0;
int address = 0;
float hiScore ;

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void win(){
   tone(buzzer, 1500);
   delay(400);
   tone(buzzer, 2000);
   delay(400);
   tone(buzzer, 2500);
   delay(350);
   tone(buzzer, 3000);
   delay(200);
   tone(buzzer, 2500);
   delay(200);
   tone(buzzer, 3000);
   delay(200);
   noTone(buzzer);
   
}
void lose(){
   tone(buzzer, 1000);
  
   delay(300);
   noTone(buzzer);
}
void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  pinMode(startGame, INPUT_PULLUP);
  pinMode(buttonWin, INPUT_PULLUP);
  pinMode(buttonLose, INPUT_PULLUP);
  pinMode(buzzer, OUTPUT);
  
EEPROM.write(address, 99);
}

void loop() {
  startState = digitalRead(startGame);
  hiScore = EEPROM.read(address);
  lcd.setCursor(0, 0);
  lcd.print("rc:  ");
  lcd.setCursor(5,0);
  lcd.print(hiScore);

  
  if(isPlaying == 1){
    lcd.setCursor(0, 1);
    lcd.print("free ");
    while(isPlaying == 1){
      winState = digitalRead(buttonWin);
      loseState = digitalRead(buttonLose);
      delay(10);
      lcd.setCursor(5,1);
      lcd.print(recoder);
      recoder += 0.01;
      if(loseState == 0){
        isPlaying = 2;
      }
      if(winState == 0){
        isPlaying = 3;
      }
    }
  }
  else if(isPlaying == 2){
        if(recoder < hiScore){
          hiScore = recoder;
          EEPROM.write(address, hiScore);
        }
        lcd.setCursor(0, 1);
        lcd.print("win ");
        win();
        recoder = 0;
        isPlaying = 0;
  }
  else if(isPlaying == 3){
        lcd.setCursor(0, 1);
        lcd.print("lose");
        lose();
        
        recoder = 0;
        isPlaying = 0;
  }
  else{
    lcd.setCursor(0, 1);
    lcd.print("Press");
  }
  if (startState == 0) {
    isPlaying = 1;
  } 
}