用Java语言编写剪刀石头布游戏的程序。 需求:随机生成1~3的随机数,分别代表剪刀、石头、布,玩家通过键盘输入剪刀、石头、布与电脑进行5游戏,赢的次数多的一方为赢家。
时间: 2024-10-23 14:16:24 浏览: 27
在Java中,你可以创建一个简单的命令行界面游戏来实现剪刀石头布。这里提供一个基本的框架代码示例:
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissorsGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int playerWins = 0;
int computerWins = 0;
for (int i = 0; i < 5; i++) {
System.out.println("Round " + (i+1) + ":");
System.out.println("Choose 1 for Rock, 2 for Paper, or 3 for Scissors:");
int userInput = scanner.nextInt();
int computerChoice = random.nextInt(3) + 1; // 1-3
if (userInput == computerChoice) {
System.out.println("It's a tie!");
} else if ((userInput == 1 && computerChoice == 3) ||
(userInput == 2 && computerChoice == 1) ||
(userInput == 3 && computerChoice == 2)) {
System.out.println("You win this round!");
playerWins++;
} else {
System.out.println("Computer wins!");
computerWins++;
}
System.out.println("Player wins: " + playerWins + ", Computer wins: " + computerWins);
}
scanner.close();
System.out.println("Game over! Final score: Player - " + playerWins + ", Computer - " + computerWins);
}
}
```
这个游戏会提示用户输入,然后随机选择一种手势。根据规则判断胜负,并更新分数。每轮比赛结束后都会显示当前比分。
阅读全文