程序启动后随机生成1-3的随机数,分别代表剪刀,石头,布,玩家通过键盘输入剪刀,石头和布与电脑进行五轮游戏,赢得次数多的一方为赢家。若五局皆为平局,则最终结果判为平局
时间: 2024-09-23 20:09:34 浏览: 42
使用C++程序实现的石头剪刀布游戏代码(调试通过)
4星 · 用户满意度95%
要实现这样的程序,你可以使用Java编写一个控制台交互的游戏。这里是一个基本框架:
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissorsGame {
private static final String[] choices = {"剪刀", "石头", "布"};
private static int playerWins = 0, computerWins = 0, ties = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
for (int round = 1; round <= 5; round++) {
System.out.printf("\n第 %d 轮:\n", round);
int randomComputerMove = random.nextInt(3) + 1;
String computerMove = choices[randomComputerMove - 1];
System.out.println("电脑出拳:" + computerMove);
System.out.print("请输入你的选择(剪刀 - 1, 石头 - 2, 布 - 3):");
int playerMove = scanner.nextInt() - 1;
if (playerMove < 0 || playerMove > 2) {
System.out.println("无效输入,请重新选择!");
continue;
}
String playerMoveName = choices[playerMove];
if (playerMove == randomComputerMove) {
ties++;
System.out.println("平局!");
} else if (calculateResult(playerMove, computerMove)) {
playerWins++;
System.out.println("恭喜你,你赢了这局!");
} else {
computerWins++;
System.out.println("很遗憾,你输了这局。电脑出了:" + computerMove);
}
System.out.println("当前战绩:你胜 " + playerWins + " 局,电脑胜 " + computerWins + " 局,平 " + ties + " 局");
}
if (ties == 5) {
System.out.println("平局,双方各赢" + playerWins + "局,打成平手。");
} else if (playerWins > computerWins) {
System.out.println("恭喜你,你赢得了比赛!");
} else {
System.out.println("电脑赢了比赛!");
}
scanner.close();
}
private static boolean calculateResult(int playerMove, String computerMove) {
return (playerMove == 0 && computerMove.equals("石头")) ||
(playerMove == 1 && computerMove.equals("布")) ||
(playerMove == 2 && computerMove.equals("剪刀"));
}
}
```
在这个程序中,首先初始化玩家和电脑的胜利次数以及平局次数。接着,在每一轮游戏中,电脑随机选择一种动作,然后等待玩家输入。如果输入有效,计算结果并更新比分;否则提示重新输入。最后,根据五局的最终得分判定胜负或平局。
阅读全文