java 编写双骰子游戏
时间: 2024-01-12 16:49:37 浏览: 39
以下是一个简单的双骰子游戏的 Java 代码示例:
```java
import java.util.Random;
public class DoubleDiceGame {
public static void main(String[] args) {
Random random = new Random();
int dice1 = 0, dice2 = 0, total = 0;
int point = 0;
boolean isWin = false;
// 一直循环直到玩家赢或输
while (!isWin) {
dice1 = random.nextInt(6) + 1;
dice2 = random.nextInt(6) + 1;
total = dice1 + dice2;
System.out.println("你掷出了 " + dice1 + " 和 " + dice2 + ",总点数为 " + total);
if (point == 0) { // 第一次掷骰子
if (total == 7 || total == 11) {
isWin = true;
System.out.println("你赢了!");
} else if (total == 2 || total == 3 || total == 12) {
isWin = false;
System.out.println("你输了!");
} else {
point = total;
System.out.println("你的点数是 " + point + ",再来一次掷骰子!");
}
} else { // 不是第一次掷骰子
if (total == point) {
isWin = true;
System.out.println("你赢了!");
} else if (total == 7) {
isWin = false;
System.out.println("你输了!");
} else {
System.out.println("你的点数是 " + point + ",再来一次掷骰子!");
}
}
}
}
}
```
在这个程序中,我们使用了一个 `Random` 对象来生成骰子点数,然后根据点数判断玩家是赢还是输。在第一次掷骰子时,如果点数为 7 或 11 则玩家赢,如果点数为 2、3 或 12 则玩家输,否则玩家会得到一个点数并继续掷骰子。在后续的掷骰子中,如果点数等于第一次掷出的点数则玩家赢,如果点数为 7 则玩家输,否则继续掷骰子直到赢或输。