用java实现猜拳游戏
时间: 2023-10-01 13:06:54 浏览: 84
好的,以下是用Java实现的猜拳游戏示例代码:
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random();
String[] options = {"石头", "剪刀", "布"};
int computerScore = 0;
int playerScore = 0;
System.out.println("欢迎来到猜拳游戏!");
while (true) {
System.out.println("\n请选择您要出的手势:");
System.out.println("1. 石头");
System.out.println("2. 剪刀");
System.out.println("3. 布");
System.out.print("请输入数字选择手势(输入 0 结束游戏):");
int playerChoice = input.nextInt();
if (playerChoice == 0) {
break;
}
if (playerChoice < 1 || playerChoice > 3) {
System.out.println("输入无效,请重新输入!");
continue;
}
int computerChoice = random.nextInt(3) + 1;
System.out.println("电脑出了:" + options[computerChoice - 1]);
if (playerChoice == computerChoice) {
System.out.println("平局!");
} else if ((playerChoice == 1 && computerChoice == 2) || (playerChoice == 2 && computerChoice == 3) || (playerChoice == 3 && computerChoice == 1)) {
System.out.println("恭喜您获胜!");
playerScore++;
} else {
System.out.println("很遗憾,您输了!");
computerScore++;
}
System.out.println("您的得分:" + playerScore);
System.out.println("电脑的得分:" + computerScore);
}
System.out.println("游戏结束,谢谢您的参与!");
}
}
```
这个程序使用了while循环,玩家可以选择石头、剪刀或布来进行游戏,电脑会随机出手势。程序会根据出拳的结果判断胜负,并输出得分。当玩家输入 0 时,程序会结束游戏。
阅读全文