C++tron AI陷入了自己的困境

C++ tron AI stuck in its own trail

本文关键字:自己的 困境 AI C++tron      更新时间:2023-10-16

我在为tron游戏组装AI时遇到了一些麻烦。人工智能应该以某种方式移动,以避开地图的边界和自己的轨迹。问题是,每次人工智能移动时,都会有一条轨迹出现在它的正后方,所以这会导致人工智能根本不移动,因为它会发出if语句"如果轨迹,不要移动",所以我有点困惑在这种情况下该怎么办。

void AIBike(){
        srand(time(0)); // use time to seed random number
        int AI; // random number will be stored in this variable
        AI = rand()%4 + 1; // Selects a random number 1 - 4.
        Map[AIy][AIx]= trail; // trail is char = '*'
        if (AI == 1){
            if(Map[AIy][AIx]!='x' && Map[AIy][AIx]!=trail){
                AIx = AIx - 1;
            }
        }

       else if (AI == 2){
            if(Map[AIy][AIx]!='x' && Map[AIy][AIx]!=trail){
                AIx = AIx + 1;
            }
        }
        else if(AI == 3){
            if(Map[AIy][AIx]!='x' && Map[AIy][AIx]!=trail){
            AIy = AIy + 1;
            }
        }
        else if(AI == 4){
            if(Map[AIy][AIx]!='x' && Map[AIy][AIx]!=trail){
            AIy = AIy - 1;
            }
        }
    }

以下是我的写作方式:

// I prefer arrays of constants instead of the copy-paste technology
const int dx[] = { 1, 0, -1, 0 };
const int dy[] = { 0, 1, 0, -1 };
int newAIx = AIx + dx[AI - 1];
int newAIy = AIy + dy[AI - 1];
if (/* newAIx and newAIy are inside the field and */ Map[newAIy][newAIx] != 'x' && Map[newAIy][newAIx] != trail) {
  Map[AIy][AIx] = trail;
  AIx = newAIx;
  AIy = newAIy;
}

我删除了大量类似的代码,并在检查后移动了踪迹创建,但在实际移动之前。

Map[AIy][AIx]= trail;Map[AIy][AIx]!=trail似乎冲突。。。你需要做什么来检测碰撞是说[例如]:

    else if(AI == 3){
        if(Map[AIy][AIx]!='x' && Map[AIy+1][AIx]!=trail){
        AIy = AIy + 1;
        }
    }

注意,我检测下一个位置是否会发生碰撞,而不是检测你是否在上面。