Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. /* Jonathan Strickland
  2. * Advanced Programming */
  3.  
  4. import java.util.Random;
  5. import java.util.Scanner;
  6.  
  7. public class PigGame
  8. {
  9. static Random die = new Random();
  10. static Scanner in = new Scanner(System.in);
  11.  
  12. static final int POINTS_TO_WIN = 100;
  13. static final int DIE_SIDES = 6;
  14.  
  15. public static void main(String[] args)
  16. {
  17. // set both scores to 0
  18. int playerOneScore = 0;
  19. int playerTwoScore = 0;
  20.  
  21. // title
  22. System.out.println("Pig Game");
  23. System.out.println("=======");
  24.  
  25. // main loop
  26. while ((playerOneScore < POINTS_TO_WIN) && (playerTwoScore < POINTS_TO_WIN))
  27. {
  28. System.out.println("\nPlayer 1's turn. You've got " + playerOneScore + " points.");
  29. playerOneScore += playerTurn();
  30. System.out.println("Player 1's score is now " + playerOneScore);
  31.  
  32. if (playerOneScore < POINTS_TO_WIN)
  33. {
  34. System.out.println("\nPlayer 2's turn. You've got " + playerTwoScore + " points.");
  35. playerTwoScore += playerTurn();
  36. System.out.println("Player 2's score is now " + playerTwoScore);
  37. }
  38. }
  39.  
  40. // print the winner
  41. if (playerOneScore >= POINTS_TO_WIN) System.out.println("Player 1 wins!");
  42. else System.out.println("Player 2 wins!");
  43. }
  44.  
  45. public static int roll()
  46. {
  47. return die.nextInt(DIE_SIDES) + 1;
  48. }
  49.  
  50. public static int playerTurn()
  51. {
  52. // start off with no points queued
  53. int score = 0;
  54. // roll the first time
  55. int roll = roll();
  56.  
  57. while (roll != 1)
  58. {
  59. // announce roll
  60. System.out.println("You rolled a " + roll);
  61.  
  62. score += roll;
  63.  
  64. System.out.println("Your roll so far is " + score);
  65.  
  66. System.out.println("Hold? (y/n)");
  67.  
  68. String input = yesOrNoPrompt();
  69.  
  70. if (input.equals("y"))
  71. {
  72. System.out.println("Okay. You got " + score + " points.");
  73. return score;
  74. } else if (input.equals("n")) {
  75. System.out.println("Okay. Let's roll.");
  76. roll = roll();
  77. }
  78. }
  79.  
  80. System.out.println("You rolled a 1.");
  81. System.out.println("Bust! No points.");
  82. return 0;
  83. }
  84.  
  85. public static String yesOrNoPrompt()
  86. {
  87. System.out.print("> ");
  88. String input = in.nextLine();
  89. System.out.println("");
  90.  
  91. while (!(input.equals("y") || input.equals("n")))
  92. {
  93. System.out.println("Enter y or n, please.");
  94.  
  95. System.out.print("> ");
  96. input = in.nextLine();
  97. System.out.println("");
  98. }
  99.  
  100. return input;
  101. }
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement