使用随机数模拟剪刀、石头、布游戏,采用五局三胜制。(do...while语句) 提示:使用Math.randorm()生成随机数。JAVA
时间: 2024-09-30 16:07:11 浏览: 33
在Java中,你可以使用do...while循环和Math.random()函数来创建一个模拟剪刀、石头、布游戏的五局三胜制。以下是一个简单的示例代码:
```java
import java.util.Random;
public class RockPaperScissors {
enum Choice {SCISSORS(0), PAPER(1), ROCK(2);
private int value;
Choice(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
Random rand = new Random();
void playGame(Choice playerChoice, Choice computerChoice) {
System.out.println("Player chooses: " + playerChoice.name());
System.out.println("Computer chooses: " + computerChoice.name());
if (playerChoice.getValue() == computerChoice.getValue()) {
System.out.println("It's a tie!");
} else if ((playerChoice.getValue() - computerChoice.getValue()) % 3 == 1) {
System.out.println("Player wins!");
} else {
System.out.println("Computer wins!");
}
}
void fiveRoundGame() {
int scorePlayer = 0;
int scoreComputer = 0;
do {
int randomNum = rand.nextInt(Choice.values().length); // Generate random number from 0 to 2
Choice playerChoice = Choice.values()[randomNum];
Choice computerChoice = getRandomComputerChoice(); // Your function to generate random computer choice
playGame(playerChoice, computerChoice);
if (scorePlayer >= 3 || scoreComputer >= 3) {
break; // End the game when one reaches three victories
}
scorePlayer += checkVictory(playerChoice); // Update player's score based on their win or loss
scoreComputer += checkVictory(computerChoice); // Update computer's score
} while (true);
System.out.println("Final score: Player - " + scorePlayer + ", Computer - " + scoreComputer);
}
// Function to randomly select a computer choice (not shown here)
private int checkVictory(Choice choice) {
if (choice.getValue() == 0) {
return choice == Choice.SCISSORS ? 1 : 0; // Player wins with rock and loses with scissors
} else if (choice.getValue() == 1) {
return choice == Choice.PAPER ? 1 : 0; // Player wins with scissors and loses with paper
} else {
return choice == Choice.ROCK ? 1 : 0; // Player wins with paper and loses with rock
}
}
public static void main(String[] args) {
RockPaperScissors game = new RockPaperScissors();
game.fiveRoundGame();
}
}
```
在这个代码里,我们首先定义了游戏的三种选择`Choice`枚举,然后创建了一个`playGame`方法来模拟一场比赛。接着,在`fiveRoundGame`中,通过do...while循环进行五局比赛,并检查是否有人达到胜利条件(三胜)。每次比赛结束后,更新双方分数。
注意这里没有提供`getRandomComputerChoice()`的具体实现,你需要自行实现这个函数来随机选择电脑的选择。你可以参考玩家的选择规则来进行电脑的选择。
阅读全文