石头剪刀布java五局
时间: 2024-03-09 07:43:43 浏览: 201
石头剪刀布是一种经典的游戏,通常用于两个人之间进行对决。在Java中实现石头剪刀布游戏可以通过以下步骤:
1. 首先,你需要创建一个包含石头、剪刀和布的枚举类型,表示玩家的选择。例如:
```java
enum Choice {
ROCK,
SCISSORS,
PAPER
}
```
2. 接下来,你可以编写一个方法来生成计算机的随机选择。可以使用`java.util.Random`类来实现随机数生成。例如:
```java
import java.util.Random;
public class Game {
private static final Random random = new Random();
public static Choice generateComputerChoice() {
int randomNumber = random.nextInt(3);
return Choice.values()[randomNumber];
}
}
```
3. 然后,你可以编写一个方法来判断胜负。根据石头剪刀布的规则,石头胜剪刀,剪刀胜布,布胜石头。例如:
```java
public class Game {
// ...
public static String determineWinner(Choice playerChoice, Choice computerChoice) {
if (playerChoice == computerChoice) {
return "平局";
} else if ((playerChoice == Choice.ROCK && computerChoice == Choice.SCISSORS)
|| (playerChoice == Choice.SCISSORS && computerChoice == Choice.PAPER)
|| (playerChoice == Choice.PAPER && computerChoice == Choice.ROCK)) {
return "玩家胜利";
} else {
return "计算机胜利";
}
}
}
```
4. 最后,你可以编写一个主程序来进行五局游戏,并输出每局的结果。例如:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Game game = new Game();
int playerWins = 0;
int computerWins = 0;
for (int i = 0; i < 5; i++) {
System.out.println("请输入你的选择(石头、剪刀或布):");
String input = scanner.nextLine();
Choice playerChoice;
switch (input) {
case "石头":
playerChoice = Choice.ROCK;
break;
case "剪刀":
playerChoice = Choice.SCISSORS;
break;
case "布":
playerChoice = Choice.PAPER;
break;
default:
System.out.println("无效的选择");
i--;
continue;
}
Choice computerChoice = game.generateComputerChoice();
String result = game.determineWinner(playerChoice, computerChoice);
System.out.println("玩家选择:" + playerChoice);
System.out.println("计算机选择:" + computerChoice);
System.out.println("结果:" + result);
if (result.equals("玩家胜利")) {
playerWins++;
} else if (result.equals("计算机胜利")) {
computerWins++;
}
}
System.out.println("游戏结束");
System.out.println("玩家胜利次数:" + playerWins);
System.out.println("计算机胜利次数:" + computerWins);
}
}
```
这样,你就可以在Java中实现一个石头剪刀布游戏,并进行五局对决了。
阅读全文