能用java写出这个代码吗
时间: 2023-08-09 14:08:53 浏览: 81
当然可以,下面是使用Java实现一个Dice类和简单的游戏:
```java
import java.util.Random;
import java.util.Scanner;
class Dice {
private int numSides;
private Random random;
public Dice(int numSides) {
this.numSides = numSides;
this.random = new Random();
}
public int roll() {
return random.nextInt(numSides) + 1;
}
}
public class DiceGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of players: ");
int numPlayers = scanner.nextInt();
System.out.print("Enter the number of sides on the dice: ");
int numSides = scanner.nextInt();
System.out.print("Enter the winning score: ");
int winningScore = scanner.nextInt();
Dice[] dice = new Dice[numPlayers];
for (int i = 0; i < numPlayers; i++) {
dice[i] = new Dice(numSides);
}
int[] scores = new int[numPlayers];
int[] rolls = new int[numPlayers];
int winner = -1;
while (winner == -1) {
for (int i = 0; i < numPlayers; i++) {
int roll = dice[i].roll();
scores[i] += roll;
rolls[i]++;
System.out.printf("Player %d rolled a %d. Current score: %d\n", i + 1, roll, scores[i]);
if (scores[i] >= winningScore) {
winner = i;
break;
}
}
}
System.out.printf("\nPlayer %d won with a score of %d after %d rolls.", winner + 1, scores[winner], rolls[winner]);
}
}
```
这个代码中,我们首先定义了一个Dice类,其中包含了掷骰子的方法roll()。然后,我们在主函数中获取用户输入的玩家数量、骰子面数和获胜分数。接下来,我们创建了一个Dice数组、一个分数数组和一个掷骰子次数的数组,用来存储每个玩家的骰子、分数和掷骰子次数。
游戏循环中,我们用for循环遍历每个玩家,掷骰子,更新分数和掷骰子次数,并检查是否达到了获胜分数。如果有玩家达到了获胜分数,我们就通过变量winner记录获胜玩家的索引,并使用break语句跳出循环。
最后,我们根据winner变量输出获胜玩家的信息。
阅读全文