用java实现剪刀石头布小游戏:编写一个剪刀石头布游戏的程序。程序启动后会随机生成0~2的随机数,分别代表剪刀、石头和布,玩家通过键盘输入剪刀、石头和布与电脑进行3轮的游戏,赢的次数多的一方为赢家。若三局皆为平局,则最终结果判为平局。
时间: 2024-09-25 14:06:07 浏览: 41
以下是使用Java实现剪刀石头布小游戏的基本步骤:
1. **创建抽象基类 Player**[^2]:
```java
abstract class Player {
public abstract String makeChoice(); // 基类定义选择行为
}
```
2. **定义具体玩家类 (Computer)**:
```java
class Computer extends Player {
private static final int[] choices = {0, 1, 2}; // 剪刀(0), 石头(1), 布(2)
@Override
public String makeChoice() {
return "Scissors", "Stone", "Paper"[choices[new Random().nextInt(choices.length)]];
}
}
```
3. **创建玩家类 (Human)**:
```java
class Human extends Player {
@Override
public String makeChoice() {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose: 1 for Rock, 2 for Paper, 3 for Scissors");
int input = scanner.nextInt();
return "Rock", "Paper", "Scissors"[input - 1]; // 用户输入映射到游戏选项
}
}
```
4. **主游戏循环**:
```java
public class Game {
public static void main(String[] args) {
Player computer = new Computer();
Player human = new Human();
int rounds = 3;
int humanWins = 0, computerWins = 0;
for (int i = 0; i < rounds; i++) {
String humanChoice = human.makeChoice();
String computerChoice = computer.makeChoice();
if (humanChoice.equals(computerChoice)) {
System.out.println("It's a tie!");
} else if (isWinningMove(humanChoice, computerChoice)) {
humanWins++;
System.out.println("You win this round!");
} else {
computerWins++;
System.out.println("Computer wins this round!");
}
}
if (humanWins > computerWins) {
System.out.println("You are the winner!");
} else if (humanWins < computerWins) {
System.out.println("Computer is the winner!");
} else {
System.out.println("It's a draw!");
}
}
private static boolean isWinningMove(String human, String computer) {
// 判断胜负逻辑:石头胜剪刀,剪刀胜布,布胜石头
return human.equals("Stone") && !computer.equals("Scissors") ||
human.equals("Scissors") && !computer.equals("Paper") ||
human.equals("Paper") && !computer.equals("Rock");
}
}
```
阅读全文