This article describes a simple dice roll game implemented in Java. Share it for your reference, as follows:
Require:
Roll two dice, each dice has six sides,
They are 1, 2, 3, 4, 5 and 6 respectively. Check the sum of these two dices.
If it is 2, 3 or 12, you lose; if the sum is 7 or 11, you win.
But if the sum is another number (for example 4, 5, 6, 8, 9 or 10),
Just confirmed a point. Continue to roll the dice until a 7 is thrown or the same number of points as before. If you throw a 7, you lose.
If the number of points thrown is the same as the number of points you threw before,
You win.
Java implementation code:
enum Status { Win, Lose, Goon;}public class DiceGame { public static int GetScore() { return (int) (1 + Math.random() * 6); } public static int Start() { int score1 = GetScore(); int score2 = GetScore(); return score1 + score2; } public static Status judge(int sum1) { if (sum1 == 7 || sum1 == 11) { return Status.Win; } else if (sum1 == 2 || sum1 == 3 || sum1 == 12) { return Status.Lose; } else return Status.Goon; } public static void main(String[] args) { int sum1 = Start(); int pre = sum1; switch (judge(sum1)) { case Win: System.out.println("You threw "+sum1+"point"); System.out.println("Congratulations! You won!"); break; case Lose: System.out.println("You threw "+sum1+"point"); System.out.println("Sorry! You lost!"); break; case Goon: int sum2 = Start(); while (true) { if (sum2 == pre) { System.out.println("You threw out the "+sum1+" point"); System.out.println("You threw out the "+sum2+" point"); System.out.println("Congratulations! You won!"); break; } else if (sum2 == 7) { System.out.println("You threw out the "+sum1+" point"); System.out.println("Spitched again "+sum2+"point"); System.out.println("Sorry! You lost!"); break; } else { pre = sum2; sum2 = Start(); } } break; } ; }}Running results:
For more information about Java algorithms, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.