java中猜拳游戏四个类代码
时间: 2024-11-03 08:21:07 浏览: 17
在Java中实现一个简单的猜拳游戏,通常会涉及以下几个类:
1. **Player** 类:代表玩家,可以有名字和选择(石头、剪刀、布)的方法。
```java
public class Player {
private String name;
public Player(String name) {
this.name = name;
}
public void choose(int choice) {
if (choice == 0 || choice == 1 || choice == 2) {
this.choice = choice; // 假设choice字段用于存储玩家的选择(0 - 石头,1 - 剪刀,2 - 布)
System.out.println(name + "选择了:" + getChoiceName(choice));
} else {
throw new IllegalArgumentException("Invalid choice");
}
}
private String getChoiceName(int choice) {
switch (choice) {
case 0: return "石头";
case 1: return "剪刀";
case 2: return "布";
default: return null;
}
}
}
```
2. **Computer** 类:代表电脑对手,随机生成选择。
```java
import java.util.Random;
public class Computer {
private Random random;
public Computer() {
random = new Random();
}
public int choose() {
return random.nextInt(3); // 返回0到2之间的随机数,对应石头、剪刀、布
}
}
```
3. **Game** 或 **Match** 类:包含游戏规则,处理输入和比较结果。
```java
public class Game {
private Player player;
private Computer computer;
public Game(Player player, Computer computer) {
this.player = player;
this.computer = computer;
}
public void start() {
player.choose();
int computerChoice = computer.choose();
System.out.println("电脑选择了:" + Game.getChoiceName(computerChoice));
// 比较并显示结果
int result = compare(player.choice, computerChoice);
displayResult(result);
}
private static String getChoiceName(int choice) {
// 使用公共静态方法避免每个类实例都创建相同的switch结构
}
private int compare(int playerChoice, int computerChoice) {
// 简单的比较规则,例如0 - 平局,1 - 玩家赢,-1 - 电脑赢
}
private void displayResult(int result) {
// 显示比赛结果
}
}
```
4. **Main** 类(入口点):
```java
public class Main {
public static void main(String[] args) {
Player humanPlayer = new Player("人类");
Computer aiPlayer = new Computer();
Game game = new Game(humanPlayer, aiPlayer);
game.start();
}
}
```
阅读全文