/** * This class implements the rules to play a * craps game. */ public class CrapsGame { public CrapsGame() { gameState = COME_OUT_STATE; boxPoints = 0; numRolls = 0; dieRoller = new Die(); } /** * getGameState() - returns the current state. * * @return current state */ public String getGameState() { String stateText; switch( gameState ) { case COME_OUT_STATE: stateText = "COME_OUT"; break; case SHOOTING_STATE: stateText = "SHOOTING"; break; case WON_STATE: stateText = "WON"; break; case LOST_STATE: stateText = "LOST"; break; default: stateText = "undefined"; break; } return stateText; } public void shoot() { switch( gameState ) { case WON_STATE: case LOST_STATE: break; case COME_OUT_STATE: firstRoll(); break; case SHOOTING_STATE: nextRoll(); break; } } public void play() { do { shoot(); } while( !isGameOver() ); } public boolean isGameWon() { return gameState == WON_STATE; } public boolean isGameLost() { return gameState == LOST_STATE; } public boolean isGameOver() { return isGameWon() || isGameLost(); } private int rollDice() { int die1 = dieRoller.roll(); int die2 = dieRoller.roll(); numRolls ++; return die1 + die2; } private void firstRoll() { int points = rollDice(); switch( points ) { case 7: case 11: gameState = WON_STATE; break; case 2: case 3: case 12: gameState = LOST_STATE; break; default: boxPoints = points; gameState = SHOOTING_STATE; break; } } private void nextRoll() { int points = rollDice(); if( points == boxPoints ) gameState = WON_STATE; else if( points == 7 ) gameState = LOST_STATE; } private static final int COME_OUT_STATE = 0; private static final int SHOOTING_STATE = 1; private static final int WON_STATE = 2; private static final int LOST_STATE = 3; private int gameState; private int boxPoints; private int numRolls; private Die dieRoller; }