用Java做一个石头剪刀布三局两胜
时间: 2024-09-13 08:15:16 浏览: 38
《剪刀石头布(Java)》实验报告
在Java中制作一个石头剪刀布游戏的三局两胜版,首先需要定义一个GamePlayer类来表示玩家,包含选择手势的方法,然后创建一个ComputerPlayer类作为电脑对手,同样有随机出拳的功能。下面是一个简单的示例:
```java
import java.util.Random;
enum Gesture {
ROCK(0), SCISSORS(1), PAPER(2);
int value;
Gesture(int value) {
this.value = value;
}
}
class GamePlayer {
public Gesture chooseGesture() {
// 用户输入,这里简单地获取用户输入并转换成对应的手势
return getValidGesture(System.console().readLine());
}
private Gesture getValidGesture(String input) {
try {
return Gesture.valueOf(input.toUpperCase());
} catch (IllegalArgumentException e) {
System.out.println("无效的选择,请输入 'rock', 'scissors', 或 'paper'!");
return chooseGesture();
}
}
}
class ComputerPlayer {
private Random random = new Random();
public Gesture chooseGesture() {
return Gesture.values()[random.nextInt(Gesture.values().length)];
}
}
public class RockPaperScissors {
public static void main(String[] args) {
GamePlayer human = new GamePlayer();
ComputerPlayer computer = new ComputerPlayer();
int scoreHuman = 0;
int scoreComputer = 0;
for (int i = 1; i <= 6; i++) { // 三局两胜制
System.out.println("第 " + i + " 局:");
Gesture humanGesture = human.chooseGesture();
Gesture computerGesture = computer.chooseGesture();
System.out.println(humanGesture + " 对 " + computerGesture);
if (compareHand Gestures(humanGesture, computerGesture)) {
scoreHuman++;
System.out.println("你赢了这局,当前比分: " + scoreHuman + ":" + scoreComputer);
} else {
scoreComputer++;
System.out.println("电脑赢了这局,当前比分: " + scoreHuman + ":" + scoreComputer);
}
if (scoreHuman >= 2 || scoreComputer >= 2) {
break;
}
}
}
private static boolean compareHand Gestures(Gesture gesture1, Gesture gesture2) {
switch(gesture1) {
case ROCK:
return gesture2 == Gesture.PAPER;
case SCISSORS:
return gesture2 != Gesture.ROCK && gesture2 != Gesture.PAPER;
case PAPER:
return gesture2 == Gesture.ROCK;
default:
throw new IllegalArgumentException("未知的手势");
}
}
}
```
阅读全文