用Java写一个剪刀石头布的游戏,越简单越好
时间: 2024-09-12 10:15:26 浏览: 46
当然,我可以帮你编写一个简单的命令行版的剪刀、石头、布游戏。我们先定义三个选项(剪刀、石头、布),然后让玩家和电脑随机选择,比较结果。这是一个基础版本:
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Let's play Rock, Paper, Scissors!\nChoose one:");
System.out.println("1. Rock\n2. Paper\n3. Scissors");
// 让用户输入他们的选择
int userChoice = scanner.nextInt();
scanner.nextLine(); // 移除上一行的回车
// 定义电脑的选择
Random random = new Random();
int computerChoice = random.nextInt(3) + 1; // 从1到3随机选择
// 比较选择并打印结果
if (userChoice == computerChoice) {
System.out.println("It's a tie! Both chose " + userChoice);
} else if ((userChoice == 1 && computerChoice == 3) ||
(userChoice == 2 && computerChoice == 1) ||
(userChoice == 3 && computerChoice == 2)) {
System.out.println("You win! You chose " + userChoice + ", computer chose " + computerChoice);
} else {
System.out.println("Computer wins! You chose " + userChoice + ", computer chose " + computerChoice);
}
scanner.close();
}
}
```
运行这个程序后,你可以按照提示输入1(Rock)、2(Paper)或3(Scissors)。然后电脑会随机做出选择,根据规则显示胜负。
阅读全文