我有一个方法processInput
当轮到用户时被激活,变量 prompt
让我知道用户处于游戏的哪个阶段。
所以我有一个提示“找到一个有值(value)的对手按F”。如果用户按“F”,我会生成一个 Enemy
对象,然后随机让用户/对手互相攻击。之后,当再次轮到用户时,它会提示“按 A 进行攻击”,但由于之前的提示( if
)创建了一个对象,所以编译器不知道它是否被执行以允许我引用该对象。
在 processInput
的最后一个 if 子句中在线player.attack(e);
, e
可能还没有初始化,所以我真的不知道如何解决这个问题。
public class inputListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent ae) {
String inputLog = input.getText();
input.setText("");
console.append(input + "\n");
processInput(inputLog);
}
void processInput(String inputLog){
input.setEnabled(false);
Enemy e;
if(prompt.startsWith("What is your name")){
if(inputLog.isEmpty()){
player.setName("Bob");
console.append("...\nYour name therefore is Bob");
}else{
player.setName(inputLog);
console.append("Alright "+player.getName()+"...\n");
}
choosePath();
}else if(prompt.startsWith("If you wish to find a worthy opponent")){
if(inputLog.equalsIgnoreCase("f")){
e = generateEnemy();
console.setText("");
console.append(e.getClass().getSimpleName()+" Level: "+e.getLvl());
console.append("\nHP: "+e.getHP());
console.append("\n\n\n");
if(Math.random()>0.49){
userTurn("Press A to attack");
}else{
e.attack(player);
if(!player.isDead()){
userTurn("Press A to attack");
}
}
}
}else if(prompt.startsWith("Press A to attack")){
player.attack(e);
if(!player.isDead()||!e.isDead()){
e.attack(player);
userTurn("Press A to attack");
}else if(e.isDead()){
console.append("\nYou have killed "+e.getClass().getSimpleName()+"!\n\n");
choosePath();
}
}
}
}
最佳答案
您如何提示用户输入?如果 e 为空,你能排除“攻击”选项吗?否则,如果他们选择“攻击”,则在 e 为空时跳过它。
} else if(prompt.startsWith("Press A to attack")) {
if (e != null) { // enemy might not be initialized yet
player.attack(e);
if (!player.isDead()||!e.isDead()) {
e.attack(player);
userTurn("Press A to attack");
}
else if(e.isDead()) {
console.append("\nYou have killed "+e.getClass().getSimpleName()+"!\n\n");
choosePath();
}
}
}
关于java - 事件驱动的回合制文本游戏,创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39195122/