我有一个方法processInput,它在轮到用户时被激活,变量prompt让我知道用户在游戏的哪个点。
所以我有一个提示“找到一个有价值的对手按F”。如果用户按下"F“,我会生成一个Enemy对象,然后随机让用户/对手互相攻击。之后,当再次轮到用户时,它会提示"Press A to attack“,但因为前面的提示(if)创建了一个对象,所以编译器不知道它是否被执行以允许我引用该对象。
在processInput中player.attack(e);行的最后一个if-子句中,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();
}
}
}
}发布于 2016-08-29 03:54:38
您是如何提示用户输入的?如果e为空,你能排除"attack“选项吗?否则,如果他们选择了“攻击”,而不是跳过它,如果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();
}
}
}https://stackoverflow.com/questions/39195122
复制相似问题