java做一个猜拳游戏
时间: 2023-07-29 08:11:36 浏览: 154
java猜拳的游戏
好的,下面是一个简单的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 random = new Random();
while (true) {
System.out.println("请选择出拳的类型:1. 石头 2. 剪刀 3. 布");
int player = scanner.nextInt();
if (player < 1 || player > 3) {
System.out.println("无效的选择,请重新输入!");
continue;
}
int computer = random.nextInt(3) + 1;
System.out.println("你出了:" + getType(player));
System.out.println("电脑出了:" + getType(computer));
if (player == computer) {
System.out.println("平局!");
} else if ((player == 1 && computer == 2) || (player == 2 && computer == 3) || (player == 3 && computer == 1)) {
System.out.println("你赢了!");
} else {
System.out.println("你输了!");
}
System.out.println("是否继续游戏?(Y/N)");
String answer = scanner.next();
if ("N".equalsIgnoreCase(answer)) {
break;
}
}
}
private static String getType(int type) {
switch (type) {
case 1:
return "石头";
case 2:
return "剪刀";
case 3:
return "布";
default:
return "";
}
}
}
```
运行程序后,用户可以选择石头、剪刀或布。计算机会随机生成一个选项,然后比较双方的选择,输出胜负结果。用户可以选择继续游戏或退出。
阅读全文