import java.util.Random; import java.util.Scanner; public class Pig { public static int dieRoll() { Random rng = new Random(); pause(); return rng.nextInt(6) + 1; } public static void pause() { try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println("Got interrupted!"); } } public static boolean aiKeepRolling(int userScore, int aiScore, int roundScore) { int goal = 10; if (100 - aiScore < 10) { goal = 100 - aiScore; } // if losing by at least 15 if (userScore - aiScore >= 15) { goal = 15; } if (roundScore >= goal) { return false; } else { return true; } } public static boolean userKeepRolling(int userScore, int aiScore, int roundScore) { Scanner in = new Scanner(System.in); // print the state so they can decide System.out.println("You have " + userScore + " points and the computer has " + aiScore + " points."); System.out.println("You have " + roundScore + " points so far in this round."); System.out.print("Do you want to keep rolling (y/n)? "); String answer = in.next(); if (answer.equalsIgnoreCase("y")) { return true; } else if (answer.equalsIgnoreCase("n")) { return false; } else { return userKeepRolling(userScore, aiScore, roundScore); } } // run one round of the game, and return points gotten for the round public static int round(boolean userTurn, int userScore, int aiScore) { int roundScore = 0; if (userTurn) { System.out.println("\nIt is your turn"); } else { System.out.println("\nIt is the computer's turn"); } boolean keepRolling = true; while (keepRolling) { int roll = dieRoll(); System.out.println((userTurn ? "You" : "The computer") + " rolled a " + roll); if (roll == 1) { System.out.println((userTurn ? "You" : "The computer") + " busted!"); return 0; } else { roundScore += roll; } if (userTurn) { keepRolling = userKeepRolling(userScore, aiScore, roundScore); } else { keepRolling = aiKeepRolling(userScore, aiScore, roundScore); } } System.out.println((userTurn ? "You" : "The computer") + " receive " + roundScore + " points this round."); return roundScore; } public static void game() { int userScore = 0; int aiScore = 0; boolean userTurn = true; while (userScore < 100 && aiScore < 100) { int roundScore = round(userTurn, userScore, aiScore); if (userTurn) { userScore += roundScore; } else { aiScore += roundScore; } userTurn = !userTurn; } if (userScore >= 100) { System.out.println("Congratulations! You have won!!"); } else { System.out.println("Aww you have lost :("); } } public static void main(String args[]) { game(); } }