
/**
 * Class that simulates the dice game Pig.
 *   @author Dave Reed 
 *   @version 9/15/17
 */
public class PigGame {
    private final static int GOAL_POINTS = 100;
    private Die roller = new Die();
    private int threshold;

    /**
     * Constructs a PigGame object.
     */
    public PigGame(int cutoff) {
        this.threshold = cutoff;
        this.roller = new Die();
    }

    /**
     * Simulates a player's turn in Pig, updating their score.
     */
    public int playTurn() {
        int turnPoints = 0;
        
        while (turnPoints < this.threshold) {
            int roll = this.roller.roll();
            //System.out.println(roll);
            if (roll == 1) {
                return 0;
            }
            else {
                turnPoints += roll;
            }
        }
        return turnPoints;
    }
    
    /**
     * Simulates a 1-player game of Pig.
     *   @param cutoff the point total at which the player holds (cutoff > 0)
     *   @return the number of turns it takes the player to win 
     */
    public int playGame() {
        int totalPoints = 0;
        int turn = 0;
        while (totalPoints < PigGame.GOAL_POINTS) {            
            totalPoints += this.playTurn();
            //System.out.println(totalPoints);
            turn++;
        } 
        return turn;
    }
 
    /**
     * Simulates repeated games of 1-player Pig.
     *   @param numGames the number of games to simulate (numGames > 0)
     *   @param cutoff the point total at which the player holds (cutoff > 0)
     *   @return the average number of rounds required to win
     */
    public double averageLengthOfGame(int numGames) {
        int totalRounds = 0;
        for (int i = 0; i < numGames; i++) {
            totalRounds += this.playGame();
        }
        return (double)totalRounds/numGames;
    }
}
