2016-08-28 4 views
0

私は、ユーザーのターンになるとprocessInputというメソッドがアクティブになります。変数promptは、ゲームのどの時点でユーザーがいるかを教えてくれます。オブジェクトを作成するイベントドリブンターンベースのテキストゲーム

私はプロンプト "価値ある対戦相手を探す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(); 
       } 

      } 
     } 

    } 

答えて

1

どのようにユーザーに入力を促しますか? eがnullの場合、 "攻撃"オプションを除外できますか?それ以外の場合は、「攻撃」を選択すると、eがnullの場合はスキップします。

} 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(); 
     } 
    } 
} 
+0

e!= nullは、processinput state敵e = nullの開始時に必要です。それは常にそれをヌルにしてオブジェクトを破壊するでしょう。私は入力のためのプロンプト方法void userTurn(String prompt){ console.append(this.prompt = prompt); input.setEnabled(true); input.requestFocus(); } – Higeath

+0

nullを確認する場合は、nullに設定する必要はありません。既に上で宣言しているので、nullに初期化されます。 – pmcevoy12

+0

私は '変数eが初期化されていない可能性があります' – Higeath

関連する問題