2017-11-29 10 views
0

私は作成しているゲームでC++でAスターアルゴリズムを実装しようとしていますが、それは動作しません。コードについて忘れたものがあるかどうか、アルゴリズム。私はそれらがソートされ、戻り値が私が訪問しなければならないノードを持つベクトルであるので、セットを使用しました。私はおそらく私はいくつかの種類のエラーを持っている前に、このアルゴリズムを使用したことがない。Aスターサーチを実装する問題C++

struct node { 
    Pos pos; 
    int f; //the sum of the distance from the goal to succcessor 
    int g; // the sum of the cost of the current plus the one from the successor 
    int h; //distance from goal to successor 

friend bool operator< (node right, node left) { 
     return (right.f < left.f); 
    } }; 



vector<node> search(Pos inicio,Pos desti){ 

    set<node> opennodes; 
    vector<node> closednodes; 
    node inici; 
    node successor; 
    inici.pos = inicio; 
    inici.h = heuristic(inicio,desti); 
    inici.g = getcost(inicio); 
    inici.f = inici.g + inici.h; 
    opennodes.insert(inici); 
    closednodes.push_back(inici); 
    while(not opennodes.empty()){ 
     node current = *(opennodes.begin()); 
     opennodes.erase(opennodes.begin()); 
     if(current.pos == desti) cerr<<"encontrao"; 
     Dir direccio; 
     for(int i = 0; i < 4;++i){ 
      if(i==0){ 
        direccio = LEFT; 

      } 
      else if(i==1){ 
        direccio = RIGHT; 
      } 
      else if(i==2){ 
        direccio = TOP; 
      } 
      else { 
        direccio = BOTTOM; 
      } 

       successor.pos = current.pos + direccio; 
       if(successor.pos == desti) return closednodes; 
       if(pos_ok(successor.pos)){ 
        successor.g = current.g + getcost(successor.pos); 
        successor.h = heuristic(successor.pos,desti); 
        successor.f = successor.g + successor.h; 

        node n1 = checkposition(successor.pos, opennodes); //I had to create two checkposition just to know if there's the node in the set or in the vector 
        node n2 = checkposition2(successor.pos, closednodes); 

        if (n1.f != -1 and n1.f < successor.f); 
        else if (n2.f != -1 and n2.f < successor.f); 
        else opennodes.insert(successor); 

       } 
     } 
      closednodes.push_back(current); 
     } 

    return closednodes; 
} 
+0

"動作していません"どのように動作しないのですか? – UKMonkey

+0

opennodeが空でないか何かが無限ループのように続きます –

+0

opennodeのように 'まったく空ではありません'まあ、デバッガはあなたに何を伝えましたか?あなたの挿入メソッドにブレークポイントを入れて、非常に簡単なテストケースを作ってみてください。それであなたが期待するアイテムを追加しているかどうかを確認できます。 – UKMonkey

答えて

0

だから、最初:

if(current.pos == desti) cerr<<"encontrao"; 

はbreak文は、ここではそこではないでしょうか? cerr関数はあなたのループを壊すことはなく、単にstdoutにエラーメッセージをスローします。

whileの中のforステートメントは常に4まで実行されます。したがって、direccioは常にBOTTOMに設定されます。 それ以外は、ヒューリスティックは問題ないと思いますが、問題はコード構造内にあり、デバッグして結果を投稿することをお勧めします。

+0

本当にそうですが、ここではデバッグする出力メッセージだったはずです。しかし、私のプログラムはまだ失敗します。私はdireccioについてのあなたの点を見ません、私は最後の反復が底であることを知っていますが、各 "子"(次のセル)は既に設定されていますか? –

関連する問題