使用java编写程序实现“剪刀石头布”的游戏,相信大家都不陌生,本案例要求编写一个剪刀石头布游戏的程序。程序启动后会随机生成1~3的随机数,分别代表剪刀、石头和布,玩家通过键盘输入剪刀、石头和布与电脑进行5轮的游戏,赢的次数多的一方为赢家。若五局皆为平局,则最终结果判为平局。
时间: 2024-10-15 10:30:34 浏览: 47
为了编写一个简单的剪刀石头布游戏,你可以按照以下步骤进行:
首先,创建一个GameRound类来表示一轮游戏:
```java
import java.util.Random;
public class GameRound {
private enum Choice {SCISSORS, STONE, PAPER}
public Choice getUserChoice() {
Scanner scanner = new Scanner(System.in);
System.out.println("请选择剪刀(1)、石头(2)或布(3):");
int input = scanner.nextInt();
return input == 1 ? Choice.SCISSORS : input == 2 ? Choice.STONE : Choice.PAPER;
}
public Choice getComputerChoice() {
Random random = new Random();
return Choice.values()[random.nextInt(Choice.values().length)];
}
public boolean isWinning(Choice user, Choice computer) {
return (user == Choice.SCISSORS && computer != Choice.SCISSORS) ||
(user == Choice.STONE && computer != Choice.PAPER) ||
(user == Choice.PAPER && computer != Choice.STONE);
}
public int play() {
Choice user = getUserChoice();
Choice computer = getComputerChoice();
System.out.printf("您出的是:%s, 电脑出了:%s\n", user, computer);
return isWinning(user, computer) ? 1 : isWinning(computer, user) ? -1 : 0;
}
}
```
接着,在主程序中设置循环来运行5轮游戏并计算总分数:
```java
public class RockPaperScissorsGame {
public static void main(String[] args) {
GameRound game = new GameRound();
int playerScore = 0;
int computerScore = 0;
int round = 1;
while (round <= 5) {
int result = game.play();
if (result == 1) {
playerScore++;
System.out.println("恭喜,第" + round++ + "轮您赢了!");
} else if (result == -1) {
computerScore++;
System.out.println("很遗憾,第" + round++ + "轮电脑赢了!");
} else {
System.out.println("平局!第" + round++ + "轮双方持平。");
}
}
if (playerScore > computerScore) {
System.out.println("恭喜,您赢得了比赛,总分:" + playerScore + "对" + computerScore);
} else if (computerScore > playerScore) {
System.out.println("电脑赢了比赛,总分:" + computerScore + "对" + playerScore);
} else {
System.out.println("游戏结束,双方打成平局,总分:" + playerScore + "对" + computerScore);
}
}
}
```
当用户运行这个程序时,他们将能够与计算机玩5轮剪刀石头布游戏,并看到每轮的结果。
阅读全文