Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class CrapsSimulation {
- // constant variables for game status
- final static int WON = 0, LOST = 1, CONTINUE = 2;
- public static Random r = new Random();
- public static void main(String args[]) {
- Scanner sc = new Scanner(System.in);
- String again;
- do {
- simulateCrapsGame(sc);
- System.out.print("Do another simulation? ");
- again = sc.nextLine();
- } while (again.equalsIgnoreCase("Y"));
- }
- public static void simulateCrapsGame(Scanner sc) {
- System.out.print("Enter number of games: ");
- int games = sc.nextInt();
- sc.nextLine();
- int woncount = 0;
- for (int i = 0; i < games; i++)
- if (playCraps() == WON)
- woncount++;
- double average = 100 * (double)woncount / games;
- System.out.println("Percentage of Wins: " + average);
- }
- public static int playCraps() {
- int gameStatus;
- int myPoint = 0;
- int sumOfDice = rollDice();
- switch ( sumOfDice ) {
- // win on first roll
- case 7:
- case 11:
- gameStatus = WON;
- break;
- // lose on first roll
- case 2:
- case 3:
- case 12:
- gameStatus = LOST;
- break;
- default:
- gameStatus = CONTINUE;
- myPoint = sumOfDice;
- break;
- }
- while (gameStatus == CONTINUE) {
- sumOfDice = rollDice();
- if ( sumOfDice == myPoint ) // win by making point
- gameStatus = WON;
- else if ( sumOfDice == 7 ) // lose by rolling 7
- gameStatus = LOST;
- }
- return gameStatus;
- }
- // roll dice, calculate sum and display results
- public static int rollDice() {
- // pick random die values
- int die1 = 1 + r.nextInt( 6 );
- int die2 = 1 + r.nextInt( 6 );
- int sum = die1 + die2; // sum die values
- return sum; // return sum of dice
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement