为了我的学校考试,我必须用 Java 制作一个控制台应用程序的 Hangman 游戏,其中一个玩家应该能够与另一个玩家或计算机(2 个玩家)对战。然而,玩家也应该能够与计算机/人工智能对战。最重要的是,计算机还应该能够与计算机对战。
鉴于上述情况,我定义了 HashMap,其中玩家的名字作为字符串索引,各个对象作为值,如下所示:
private HashMap<String, PlayerHuman> humans = new HashMap<>(2);
private HashMap<String, PlayerComputer> computers = new HashMap<>(2);
由于 2 个玩家和 2 台计算机都可以互相对战,因此两个 HashMap 的容量都是 2。现在创建玩家时,应该输入真实姓名(例如“John”、“Mary”)或简单的姓名如果玩家是由计算机控制的,则为“C”。然后,我检查给定的输入是否是“C”,从而为该玩家创建相应的类,如下所示:
Scanner scanner = new Scanner(System.in);
System.out.println("First create the players for the game!");
//
System.out.println("Type the name of player 1 (type C for computer): ");
String playerName1 = scanner.nextLine();
System.out.println("Type the nam of player 2 (type C for computer): ");
String playerName2 = scanner.nextLine();
if (playerName1.equals("C")) {
PlayerComputer player1 = new PlayerComputer();
player1.setPlayerName(playerName1);
if (playerName2.equals("C")) {
playerName1 = "C1";
playerName2 = "C2";
PlayerComputer player2 = new PlayerComputer();
player1.setPlayerName(playerName1);
player2.setPlayerName(playerName2);
this.computers.put(playerName2, player2);
} else {
PlayerHuman player2 = new PlayerHuman();
player2.setPlayerName(playerName2);
this.humans.put(playerName2, player2);
}
this.computers.put(playerName1, player1);
} else {
PlayerHuman player1 = new PlayerHuman();
player1.setPlayerName(playerName1);
if (playerName2.equals("C")) {
PlayerComputer player2 = new PlayerComputer();
player2.setPlayerName(playerName2);
this.computers.put(playerName2, player2);
} else {
PlayerHuman player2 = new PlayerHuman();
player2.setPlayerName(playerName2);
this.humans.put(playerName2, player2);
}
this.humans.put(playerName1, player1);
}
String startingPlayer = raffle(playerName1, playerName2);
肯定有一种更简单的方法可以做到这一点,我刚刚完全陷入困境,再也看不到出路了。然后我必须随机选择 2 个玩家中的任何一个来第一个玩。我在以下方法“抽奖”中执行此操作。
private String raffle(String nameOne, String nameTwo) {
Random random = new Random();
String raffledName = random.nextBoolean() ? nameOne : nameTwo;
System.out.println(raffledName + " may begin!");
return raffledName;
}
这就是我陷入困境的地方。我从“抽奖”方法中得到了预期的结果;两个给定玩家的名字之一,但是我不知道如何让代码知道从哪个数组检索返回的玩家,因为当两个玩家都被命名为“C”或“C1”和“C2”时,计算机可以被命名为“C”或“C1”和“C2”是计算机控制的,知道哪台计算机代表哪个玩家。如何让我的代码在检索玩家各自的实例时考虑到这一点?
也欢迎任何有关创建播放器的建议,因为我觉得上面编写的代码很脏并且太程序化了。
提前致谢!
最佳答案
我建议您定义一个父类(super class)“Player”,您的两种玩家类型派生自该父类(super class)。
abstract class Player {
private String name;
public void setPlayerName(String name) {
this.name = name;
}
public String getPlayerName() { return name; }
abstract public boolean isCPU();
...
}
class PlayerHuman extends Player {
public boolean isCPU() { return false; }
...
}
class PlayerComputer extends Player {
public boolean isCPU() { return true; }
...
}
HashMap<String, Player> players = ...
或者,您可以只使用玩家数组:
Player[] players = new Player[2];
那么,您不必按名称引用玩家,并且您可以打乱数组来决定谁先走。
关于java - 绞刑吏游戏 : stuck on randomly selecting players,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52862626/