Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Jonathan Strickland
- * Advanced Programming */
- import java.util.Random;
- import java.util.Scanner;
- public class PigGame
- {
- static Random die = new Random();
- static Scanner in = new Scanner(System.in);
- static final int POINTS_TO_WIN = 100;
- static final int DIE_SIDES = 6;
- public static void main(String[] args)
- {
- // set both scores to 0
- int playerOneScore = 0;
- int playerTwoScore = 0;
- // title
- System.out.println("Pig Game");
- System.out.println("=======");
- // main loop
- while ((playerOneScore < POINTS_TO_WIN) && (playerTwoScore < POINTS_TO_WIN))
- {
- System.out.println("\nPlayer 1's turn. You've got " + playerOneScore + " points.");
- playerOneScore += playerTurn();
- System.out.println("Player 1's score is now " + playerOneScore);
- if (playerOneScore < POINTS_TO_WIN)
- {
- System.out.println("\nPlayer 2's turn. You've got " + playerTwoScore + " points.");
- playerTwoScore += playerTurn();
- System.out.println("Player 2's score is now " + playerTwoScore);
- }
- }
- // print the winner
- if (playerOneScore >= POINTS_TO_WIN) System.out.println("Player 1 wins!");
- else System.out.println("Player 2 wins!");
- }
- public static int roll()
- {
- return die.nextInt(DIE_SIDES) + 1;
- }
- public static int playerTurn()
- {
- // start off with no points queued
- int score = 0;
- // roll the first time
- int roll = roll();
- while (roll != 1)
- {
- // announce roll
- System.out.println("You rolled a " + roll);
- score += roll;
- System.out.println("Your roll so far is " + score);
- System.out.println("Hold? (y/n)");
- String input = yesOrNoPrompt();
- if (input.equals("y"))
- {
- System.out.println("Okay. You got " + score + " points.");
- return score;
- } else if (input.equals("n")) {
- System.out.println("Okay. Let's roll.");
- roll = roll();
- }
- }
- System.out.println("You rolled a 1.");
- System.out.println("Bust! No points.");
- return 0;
- }
- public static String yesOrNoPrompt()
- {
- System.out.print("> ");
- String input = in.nextLine();
- System.out.println("");
- while (!(input.equals("y") || input.equals("n")))
- {
- System.out.println("Enter y or n, please.");
- System.out.print("> ");
- input = in.nextLine();
- System.out.println("");
- }
- return input;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement