C++ tron AI 坚持自己的道路

标签 c++ if-statement

我在为我的 Tron 游戏组装 AI 时遇到了一些麻烦。人工智能应该以一种避开 map 边界和它自己的轨迹的方式移动。问题是,每次移动时,一条轨迹应该出现在 AI 的正后方,所以这会导致 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;
}

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

关于C++ tron AI 坚持自己的道路,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20035494/

相关文章:

c++ - Visual Studio 2017 控制台应用程序 : precompiled header

python - 如何在 PLY 中做一个 IF 语句?

c++ - 无符号字符数组的十进制 ascii 值

c++ - 使用辅助类接口(interface)写入文件,在哪里打开 ofstream?

php - MySQL基于IF的Join

java - 比 Java 中的 If(x instanceof y) 更好的方法?

r - 在 apply 内使用 ifelse

if-statement - if 和 else if 做同样的事情

我可以从程序 (DLL) 调用的 C++ 或 C 编译器

c++ - 在 C++ 代码中使用字符 `$` 或 `@` 有什么问题吗?