Advertisement
Guest User

Craps Game Simulation

a guest
Nov 1st, 2016
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.04 KB | None | 0 0
  1.  
  2. import java.util.*;
  3.  
  4. public class CrapsSimulation {
  5.    // constant variables for game status
  6.    final static int WON = 0, LOST = 1, CONTINUE = 2;
  7.    public static Random r = new Random();
  8.    
  9.    public static void main(String args[]) {
  10.       Scanner sc = new Scanner(System.in);
  11.       String again;
  12.       do {
  13.          simulateCrapsGame(sc);
  14.          System.out.print("Do another simulation? ");
  15.          again = sc.nextLine();
  16.       } while (again.equalsIgnoreCase("Y"));   
  17.    }
  18.    
  19.    public static void simulateCrapsGame(Scanner sc) {
  20.       System.out.print("Enter number of games: ");
  21.       int games = sc.nextInt();
  22.       sc.nextLine();
  23.       int woncount = 0;
  24.       for (int i = 0; i < games; i++)
  25.          if (playCraps() == WON)
  26.             woncount++;
  27.       double average = 100 * (double)woncount / games;
  28.       System.out.println("Percentage of Wins: " + average);
  29.    }
  30.    
  31.    public static int playCraps() {
  32.       int gameStatus;
  33.       int myPoint = 0;
  34.       int sumOfDice = rollDice();
  35.       switch ( sumOfDice ) {
  36.          // win on first roll
  37.          case 7:
  38.          case 11:        
  39.             gameStatus = WON;
  40.             break;
  41.  
  42.          // lose on first roll
  43.          case 2:
  44.          case 3:
  45.          case 12:
  46.             gameStatus = LOST;
  47.             break;
  48.  
  49.          default:                
  50.             gameStatus = CONTINUE;
  51.             myPoint = sumOfDice;
  52.             break;
  53.          }
  54.       while (gameStatus == CONTINUE) {
  55.          sumOfDice = rollDice();
  56.          if ( sumOfDice == myPoint )  // win by making point
  57.             gameStatus = WON;
  58.          else if ( sumOfDice == 7 )     // lose by rolling 7
  59.             gameStatus = LOST;
  60.       }
  61.  
  62.       return gameStatus;
  63.    }
  64.  
  65.    // roll dice, calculate sum and display results
  66.    public static int rollDice() {
  67.       // pick random die values
  68.       int die1 = 1 + r.nextInt( 6 );  
  69.       int die2 = 1 + r.nextInt( 6 );
  70.       int sum = die1 + die2;   // sum die values
  71.       return sum;  // return sum of dice
  72.    }
  73.    
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement