用java编写,写一个剪刀、石头、布的小游戏 程序启动后会随机生成0-2的随机整数,分别代表剪刀、石头和布,玩家通过键盘输入剪刀、石头和布与电脑进行3轮游戏,赢的次数多的一方为赢家。若3局皆为平局,则最终结果判为平局。
时间: 2024-10-10 09:07:25 浏览: 26
在Java中创建这个小游戏,我们可以使用`Random`类生成随机数,以及`Scanner`类获取用户输入。以下是简单的步骤和部分代码示例:
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissorsGame {
enum Gesture { ROCK(0), PAPER(1), SCISSORS(2);
private int value;
Gesture(int value) {
this.value = value;
}
public static Gesture getRandomGesture() {
Random random = new Random();
return values()[random.nextInt(values().length)];
}
public boolean beats(Gesture other) {
// 石头胜剪刀,剪刀胜布,布胜石头
return (this == ROCK && other != SCISSORS) ||
(this == SCISSORS && other != ROCK) ||
(this == PAPER && other != PAPER);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int playerWins = 0, computerWins = 0, ties = 0;
for (int round = 1; round <= 3; round++) {
System.out.println("Round " + round + ":");
Gesture playerChoice = Gestures.valueOf(scanner.nextLine().toUpperCase());
Gesture computerChoice = Gesture.getRandomGesture();
if (playerChoice.beats(computerChoice)) {
System.out.println("You win with " + playerChoice.name());
playerWins++;
} else if (computerChoice.beats(playerChoice)) {
System.out.println("Computer wins with " + computerChoice.name());
computerWins++;
} else {
System.out.println("It's a tie!");
ties++;
}
}
if (playerWins > computerWins) {
System.out.println("Player wins the game!");
} else if (computerWins > playerWins) {
System.out.println("Computer wins the game!");
} else {
System.out.println("It's a draw!");
}
scanner.close();
}
}
```
在这个例子中,我们首先定义了一个枚举`Gesture`来表示三种手势,然后有一个`beats()`方法用于判断胜负。主函数中,我们循环三次让用户和计算机各自选择,并根据规则计算胜利次数。最后根据获胜次数判断输赢。
阅读全文