import java.util.Random; import java.util.Scanner; public class Pig { // this method sleeps for a half second public static void pause() { try { Thread.sleep(500); } catch (InterruptedException e) {} } // returns a random number 1-6 inclusive public static int dieRoll() { Random rng = new Random(); int die = rng.nextInt(6) + 1; return die; } // return true if computer rolls, false if not public static boolean computerRolls(int points, int rolls) { if (points >= 15) { return false; } else { return true; } } // one turn for the computer player, returns points won public static int computerTurn() { int points = 0; int rolls = 0; while (computerRolls(points, rolls)) { int die = dieRoll(); rolls++; System.out.println("Computer rolled a " + die + "."); pause(); if (die == 1) { System.out.println("Computer busted."); pause(); return 0; } points += die; System.out.println("Computer has " + points + " points so far this turn"); pause(); } return points; } // one turn for the human player, returns points won public static int playerTurn() { Scanner in = new Scanner(System.in); boolean rolling = true; int points = 0; while (rolling == true) { int die = dieRoll(); System.out.println("You rolled a " + die + "."); pause(); if (die == 1) { System.out.println("You busted."); return 0; } points += die; System.out.println("You have " + points + " points so far this turn"); System.out.println("Do you want to roll again (Y/N)? "); String response = in.next(); if (response.equalsIgnoreCase("N")) { System.out.println("You finished with " + points + " points."); rolling = false; } } return points; } public static void main(String args[]) { int playerScore = 0; int computerScore = 0; while (playerScore < 100 && computerScore < 100) { playerScore += playerTurn(); System.out.println("You have " + playerScore + " points total.\n"); if (playerScore < 100) { computerScore += computerTurn(); System.out.println("Computer has " + computerScore + " points total.\n"); } } if (playerScore >= 100) { System.out.println("Congratulations, you have won!!"); } else { System.out.println("Sorry, you have lost :("); } } }