猜拳游戏代码java
时间: 2024-01-02 22:19:15 浏览: 140
猜拳游戏的Java代码示例如下:
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random rand = new Random();
System.out.println("猜拳游戏开始!请出拳:");
System.out.println("1. 石头");
System.out.println("2. 剪刀");
System.out.println("3. 布");
int playerChoice = scanner.nextInt();
int computerChoice = rand.nextInt(3) + 1;
System.out.println("你选择了:" + getPlayerChoice(playerChoice));
System.out.println("电脑选择了:" + getPlayerChoice(computerChoice));
if (playerChoice == computerChoice) {
System.out.println("平局!");
} else if ((playerChoice == 1 && computerChoice == 2) ||
(playerChoice == 2 && computerChoice == 3) ||
(playerChoice == 3 && computerChoice == 1)) {
System.out.println("你赢了!");
} else {
System.out.println("你输了!");
}
}
public static String getPlayerChoice(int choice) {
switch (choice) {
case 1:
return "石头";
case 2:
return "剪刀";
case 3:
return "布";
default:
return "无效选择";
}
}
}
```
阅读全文