/**
 * Class for simulating volleyball games using rally scoring.
 *   @author Dave Reed
 *   @version 10/25/05
 */
public class VolleyballSim
{
    private Die roller;     // Die for simulating points
    private int ranking1;   // power ranking of team 1
    private int ranking2;   // power ranking of team 2

    /**
     * Constructs a volleyball game simulator.
     *   @param team1Ranking the power ranking (0-100) of team 1, the team that serves first
     *   @param team2Ranking the power ranking (0-100) of team 2, the receiving team
     */
    public VolleyballSim(int team1Ranking, int team2Ranking)
    {
        roller = new Die(team1Ranking+team2Ranking);
        ranking1 = team1Ranking;
        ranking2 = team2Ranking;
    }

    /**
     * Simulates a single rally between the two teams.
     *   @param team the number of the serving team (either 1 or 2)
     *   @return the winner of the rally (either 1 or 2)
     */
    public int serve(int team)
    {
        int winner;
        if (roller.roll() <= ranking1) {
            winner = 1;
        }
        else {
            winner = 2;
        }
        
        System.out.print("team " + team + " serves: team " +
                         winner + " wins the rally");
        return winner;          
    }

    /**
     * Simulates an entire game using the rally scoring system.
     *   @param winningPoints the number of points needed to win the game (winningPoints > 0)
     *   @return the winner of the game (either 1 or 2)
     */
    public int playGameRally(int winningPoints)
    {
        int score1 = 0;
        int score2 = 0;
        int servingTeam = 1;

        int winner = 0;       
        while ((score1 < winningPoints && score2 < winningPoints)
                              || (Math.abs(score1 - score2) <= 1)) {
            winner = serve(servingTeam);            
            if (winner == 1) {
                score1++;
                servingTeam = 1;
            }
            else {
                score2++;
                servingTeam = 2;
            }
                    
            System.out.println(" (" + score1 + "-" + score2 + ")");
        }
        return winner;
    }
}
