请你用java编写一个剪刀石头布的游戏,程序启动后会生成1~3的随机数,分别代表剪刀,石头,布,玩家通过键盘输入剪刀,石头和布与电脑进行五轮游戏,赢的次数多的一方是赢家,若无论都为平局,则最终结果为平局
时间: 2024-06-15 21:04:34 浏览: 68
基于java实现剪刀石头布小游戏
好的,下面是用Java编写剪刀石头布游戏的示例代码:
```java
import java.util.Scanner;
public class RockPaperScissorsGame {
public static void main(String[] args) {
int rounds = 5; // 游戏轮数
int playerScore = 0; // 玩家得分
int computerScore = 0; // 电脑得分
System.out.println("欢迎来到剪刀石头布游戏!");
for (int i = 1; i <= rounds; i++) {
System.out.println("第 " + i + " 轮游戏开始,请输入你的选择(剪刀、石头、布):");
String playerChoice = getPlayerChoice();
String computerChoice = getComputerChoice();
System.out.println("你选择了:" + playerChoice);
System.out.println("电脑选择了:" + computerChoice);
String result = getResult(playerChoice, computerChoice);
if (result.equals("玩家赢")) {
playerScore++;
} else if (result.equals("电脑赢")) {
computerScore++;
}
System.out.println("本轮游戏结果:" + result);
System.out.println("--");
}
System.out.println("游戏结束!");
System.out.println("玩家得分:" + playerScore);
System.out.println("电脑得分:" + computerScore);
if (playerScore > computerScore) {
System.out.println("玩家是赢家!");
} else if (playerScore < computerScore) {
System.out.println("电脑是赢家!");
} else {
System.out.println("最终结果为平局!");
}
}
// 获取玩家选择
public static String getPlayerChoice() {
Scanner scanner = new Scanner(System.in);
String choice = scanner.nextLine().toLowerCase();
while (!choice.equals("剪刀") && !choice.equals("石头") && !choice.equals("布")) {
System.out.println("输入无效,请重新输入(剪刀、石头、布):");
choice = scanner.nextLine().toLowerCase();
}
return choice;
}
// 获取电脑选择
public static String getComputerChoice() {
int randomNum = (int) (Math.random() * 3) + 1;
if (randomNum == 1) {
return "剪刀";
} else if (randomNum == 2) {
return "石头";
} else {
return "布";
}
}
// 判断游戏结果
public static String getResult(String playerChoice, String computerChoice) {
if (playerChoice.equals(computerChoice)) {
return "平局";
} else if ((playerChoice.equals("剪刀") && computerChoice.equals("布"))
|| (playerChoice.equals("石头") && computerChoice.equals("剪刀"))
|| (playerChoice.equals("布") && computerChoice.equals("石头"))) {
return "玩家赢";
} else {
return "电脑赢";
}
}
}
```
阅读全文