用java实现剪刀石头布
时间: 2023-07-16 15:13:42 浏览: 102
基于java实现剪刀石头布小游戏
好的,以下是Java实现剪刀石头布的代码:
```java
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int playerChoice, computerChoice;
while (true) {
System.out.print("请选择(1:剪刀,2:石头,3:布,0:结束游戏):");
playerChoice = sc.nextInt();
if (playerChoice == 0) {
System.out.println("游戏结束!");
break;
}
computerChoice = (int) (Math.random() * 3) + 1;
System.out.println("电脑出拳:" + getChoice(computerChoice));
if (playerChoice == computerChoice) {
System.out.println("平局!");
} else if ((playerChoice == 1 && computerChoice == 3)
|| (playerChoice == 2 && computerChoice == 1)
|| (playerChoice == 3 && computerChoice == 2)) {
System.out.println("你赢了!");
} else {
System.out.println("你输了!");
}
}
sc.close();
}
private static String getChoice(int choice) {
switch (choice) {
case 1:
return "剪刀";
case 2:
return "石头";
case 3:
return "布";
default:
return "";
}
}
}
```
运行代码后,会提示输入选择,输入1、2、3分别代表剪刀、石头、布,输入0则结束游戏。计算机会随机出拳,并判断胜负。
阅读全文