我在为我的 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/