Java猜拳小游戏代码
时间: 2023-08-30 20:11:16 浏览: 90
下面是一个简单的Java猜拳小游戏代码:
```java
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
System.out.println("欢迎来到猜拳游戏!");
System.out.println("请出拳:1.石头 2.剪刀 3.布");
Scanner scanner = new Scanner(System.in);
int userChoice = scanner.nextInt();
int computerChoice = (int) (Math.random() * 3) + 1;
System.out.println("你出了" + choiceToString(userChoice));
System.out.println("电脑出了" + choiceToString(computerChoice));
int result = determineWinner(userChoice, computerChoice);
if (result == 0) {
System.out.println("平局!");
} else if (result == 1) {
System.out.println("你赢了!");
} else {
System.out.println("电脑赢了!");
}
}
public static String choiceToString(int choice) {
switch (choice) {
case 1:
return "石头";
case 2:
return "剪刀";
case 3:
return "布";
default:
return "";
}
}
public static int determineWinner(int userChoice, int computerChoice) {
if (userChoice == computerChoice) {
return 0;
} else if (userChoice == 1 && computerChoice == 2 ||
userChoice == 2 && computerChoice == 3 ||
userChoice == 3 && computerChoice == 1) {
return 1;
} else {
return -1;
}
}
}
```
运行代码后,程序会提示用户出拳,并显示电脑出的拳和胜负结果。其中,`choiceToString`方法将数字转换为对应的拳头名称,`determineWinner`方法根据用户和电脑出的拳来判断胜负。
阅读全文