java实现剪刀石头布功能
时间: 2024-09-24 18:28:09 浏览: 34
在Java中实现剪刀石头布游戏,通常会涉及到用户输入、随机选择电脑选项以及判断胜负规则。下面是一个简单的步骤概述:
1. **创建类**:首先创建一个`Game`类,包含玩家和电脑的选择。
```java
public class Game {
// 玩家和电脑的选择枚举
public enum Choice { ROCK, PAPER, SCISSORS }
private Player player;
private Computer computer;
public Game(Player player) {
this.player = player;
this.computer = new Computer();
}
// 方法...
}
```
2. **用户输入**:定义一个`Player`类,其中包含获取用户输入的方法。
```java
class Player {
public Choice getUserChoice() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入(rock/paper/scissors):");
return scanner.nextLine().toUpperCase().equals("ROCK") ? Choice.ROCK :
scanner.nextLine().toUpperCase().equals("PAPER") ? Choice.PAPER : Choice.SCISSORS;
}
}
```
3. **电脑选择**:创建`Computer`类,这里可以用随机数生成器。
```java
class Computer {
public Choice getComputerChoice() {
Random random = new Random();
int index = random.nextInt(3);
return index == 0 ? Choice.ROCK :
index == 1 ? Choice.PAPER : Choice.SCISSORS;
}
}
```
4. **游戏逻辑**:在`Game`类中添加一个方法来比较两个选择并显示结果。
```java
public void play() {
playerChoice = player.getUserChoice();
computerChoice = computer.getComputerChoice();
if (playerChoice.equals(computerChoice)) {
System.out.println("平局!");
} else if (compare(playerChoice, computerChoice) == 1) {
System.out.println("你赢了," + computerChoice.name() + " 对 " + playerChoice.name());
} else {
System.out.println("你输了," + playerChoice.name() + " 对 " + computerChoice.name());
}
}
private int compare(Choice a, Choice b) {
// 判断规则...
}
```
5. **循环和结束条件**:为了使游戏可以多次进行,可以在`main`方法中设置一个循环,并提供退出游戏的选项。
```java
public static void main(String[] args) {
Game game = new Game(new HumanPlayer()); // 使用HumanPlayer代替Player,用于演示
while (true) {
game.play();
System.out.println("是否继续?(y/n)");
String input = scanner.nextLine();
if (!input.equalsIgnoreCase("y")) break;
}
}
```
阅读全文