package l02; import java.util.Arrays; import java.util.Random; /** * The game manager for a simple dice game. Tidied up a bit. * * @author Michael Albert */ public class TidyManager implements Manager { private Player a; private Player b; private Player currentPlayer; private int[] aDice = new int[3]; private int[] bDice = new int[3]; private boolean oldRollAvailable; private boolean oldRollTaken; private int oldRoll; public TidyManager(Player a, Player b) { this.a = a; this.b = b; initialiseGame(); } private void initialiseGame() { a.setManager(this); b.setManager(this); currentPlayer = a; for(int i = 0; i < 3; i++) { aDice[i] = Die.roll(); bDice[i] = Die.roll(); } Arrays.sort(aDice); Arrays.sort(bDice); oldRollAvailable = false; } public void runGame() { while(true) { // Exit will be handled by end of game check inside the loop announceDice(); if (oldRollAvailable) offerOldRoll(); if (!oldRollTaken) offerNewRoll(); if (gameOver()) { congratulations(); return; } switchPlayers(); } } public void announceDice() { System.out.println(currentPlayer + ", your dice are: " + Arrays.toString(getDice(currentPlayer)) + "."); } public void offerOldRoll() { int index = currentPlayer.takeOldRoll(oldRoll); oldRollTaken = isValid(index); if (oldRollTaken) { System.out.println(currentPlayer + " takes an old roll of " + oldRoll + " and exchanges for die " + index); adjustDice(oldRoll, index); oldRollAvailable = false; } else { System.out.println(currentPlayer + " refuses an old roll of " + oldRoll); } } public void offerNewRoll() { int roll = Die.roll(); int index = currentPlayer.takeNewRoll(roll); if (isValid(index)) { System.out.println(currentPlayer + " takes a roll of " + roll + " and exchanges for die " + index); adjustDice(roll, index); oldRollAvailable = false; } else { System.out.println(currentPlayer + " refuses a roll of " + roll); oldRoll = roll; oldRollAvailable = true; } } public boolean isValid(int index) { return 0 <= index && index < 3; } private void adjustDice(int value, int index) { if (currentPlayer == a) { aDice[index] = value; Arrays.sort(aDice); } else { bDice[index] = value; Arrays.sort(bDice); } } private boolean gameOver() { if (currentPlayer == a) { return isSet(aDice); } else { return isSet(bDice); } } private boolean isSet(int[] dice) { Arrays.sort(dice); if (dice[0] == dice[2]) return true; if (dice[0] == dice[1] || dice[1] == dice[2]) return false; return dice[2] - dice[0] == 2; } public int[] getDice(Player p) { if (p == a) return aDice; if (p == b) return bDice; return null; } private void switchPlayers() { if (currentPlayer == a) { currentPlayer = b; } else { currentPlayer = a; } } private void congratulations() { System.out.println("Congratulations " + currentPlayer + " you win!"); System.out.println("The winning dice were " + Arrays.toString(getDice(currentPlayer))); } }