使用随机数模拟剪刀石头、布游戏,采用五局 三胜制。(do..while语句) 提示:使用Math.randorm()生成随机数。java
时间: 2024-10-08 14:26:06 浏览: 36
在Java中,你可以使用`java.util.Random`类配合`do...while`循环来模拟剪刀石头布游戏。这里是一个简单的示例:
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
String[] choices = {"rock", "paper", "scissors"};
int playerScore = 0;
int aiScore = 0;
// 五局三胜的规则
while (playerScore < 3 && aiScore < 3) {
System.out.println("Player, choose rock, paper, or scissors:");
String playerChoice = scanner.nextLine().toLowerCase();
// 确保玩家输入的是有效选项
if (!choices.contains(playerChoice)) {
System.out.println("Invalid choice, please try again.");
continue;
}
int aiRandomIndex = random.nextInt(choices.length);
String aiChoice = choices[aiRandomIndex];
System.out.println("Computer chose " + aiChoice);
// 判断胜负
if (playerChoice.equals(aiChoice)) {
System.out.println("It's a tie!");
} else if (
(playerChoice.equals("rock") && aiChoice.equals("scissors")) ||
(playerChoice.equals("paper") && aiChoice.equals("rock")) ||
(playerChoice.equals("scissors") && aiChoice.equals("paper"))
) {
System.out.println("Player wins!");
playerScore++;
} else {
System.out.println("Computer wins!");
aiScore++;
}
}
// 游戏结束
if (playerScore == 3) {
System.out.println("Player wins the game!");
} else {
System.out.println("Computer wins the game!");
}
}
}
```
在这个示例中,我们首先初始化玩家和AI分数为0,然后通过`do...while`循环进行五局比赛。每次循环中,先获取玩家的选择,然后让电脑随机选择,最后判断胜负并更新得分。如果玩家赢得三局或AI赢得三局,则跳出循环。
阅读全文