编写一个剪刀石头布游戏的程序
时间: 2024-09-24 21:10:31 浏览: 43
创建一个简单的剪刀、石头、布(Scissors, Paper, Stone或Rock, Paper, Scissors)游戏,你可以使用控制台应用或者图形用户界面(GUI)。这里我会提供一个基本的控制台版本的Java代码示例:
```java
import java.util.Scanner;
public class RockPaperScissors {
enum Choice {SCISSORS, PAPER, ROCK}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Rock-Paper-Scissors game!\nChoose one:");
System.out.println("1. Rock\n2. Paper\n3. Scissors");
// 获取玩家选择
int playerChoice = scanner.nextInt();
Choice player = getEnumChoice(playerChoice);
// 计算电脑随机选择
Random random = new Random();
int computerChoice = random.nextInt(3) + 1;
Choice computer = getEnumChoice(computerChoice);
// 比较结果并打印
if (player == computer) {
System.out.println("It's a tie!");
} else if ((player == Choice.ROCK && computer == Choice.PAPER) ||
(player == Choice.PAPER && computer == Choice.SCISSORS) ||
(player == Choice.SCISSORS && computer == Choice.ROCK)) {
System.out.println("You lose! " + computer + " beats " + player);
} else {
System.out.println("You win! " + player + " beats " + computer);
}
scanner.close();
}
private static Choice getEnumChoice(int input) {
switch (input) {
case 1:
return Choice.ROCK;
case 2:
return Choice.PAPER;
case 3:
return Choice.SCISSORS;
default:
throw new IllegalArgumentException("Invalid choice. Please choose 1, 2 or 3.");
}
}
}
```
在这个程序中,我们首先定义了一个枚举类型`Choice`来表示三种可能的选择。然后,在`main`方法中,获取用户的输入并将其转换为`Choice`实例。电脑则随机生成一个选择。比较玩家和电脑的选择,根据规则决定胜负并输出结果。
运行这个程序后,玩家可以通过键盘输入数字1(Rock)、2(Paper)或3(Scissors),然后与电脑进行一场模拟的游戏。
阅读全文