public class DotRace {
  private Dot redDot;
  private Dot blueDot;    
  private Dot greenDot;
  private int goalDistance;

  public DotRace(int maxStep, int distance) {
    this.redDot = new Dot("red", maxStep);
    this.blueDot = new Dot("blue", maxStep);
    this.greenDot = new Dot("green", maxStep);
    this.goalDistance = distance;
  }
  
  private int getRedPosition() {
    return this.redDot.getPosition();
  }
    
  private int getBluePosition() {
    return this.blueDot.getPosition();
  }   

  private int getGreenPosition() {
    return this.greenDot.getPosition();
  }  
  
  private void step() {
    if (this.keepRacing()) {
            this.redDot.step();
            this.blueDot.step();
            this.greenDot.step(); 
        }
        else {
            System.out.println("Stop hitting Step - the race is over!");
        }
    }
       
  private void showStatus() {
    this.redDot.showPosition();
    this.blueDot.showPosition();
    this.greenDot.showPosition();
    
    if (this.getRedPosition() >= this.goalDistance && 
        this.getBluePosition() < this.goalDistance &&
        this.getGreenPosition() < this.goalDistance) {
        System.out.println("RED wins");
    }
    else if (this.getBluePosition() >= this.goalDistance &&
             this.getRedPosition() < this.goalDistance &&
             this.getGreenPosition() < this.goalDistance) {
        System.out.println("BLUE wins");
    }
    else if (this.getGreenPosition() >= this.goalDistance &&
             this.getRedPosition() < this.goalDistance &&
             this.getBluePosition() < this.goalDistance) {
        System.out.println("GREEN wins");
    }
    else if (this.getGreenPosition() >= this.goalDistance ||
        this.getBluePosition() >= this.goalDistance ||
        this.getRedPosition() >= this.goalDistance) {
        System.out.println("It's a tie!");
    }
  }
  
  public void runRace() {
      this.reset();
      while ( this.keepRacing() ) {
          this.step();
          this.showStatus();
      }
  }
  
  private boolean keepRacing() {
      return (this.getGreenPosition() < this.goalDistance &&
              this.getBluePosition() < this.goalDistance &&
              this.getRedPosition() < this.goalDistance);
  }
    
  private void reset() {
    this.redDot.reset();
    this.blueDot.reset();
    this.greenDot.reset();
  }
}
