我添加了2个功能:
int aiCheckScore(char arr[7][7], int inp, int height, Player player)
int aiFindMostRelevant(char arr[7][7], Player player)
第一个在2D数组中为给定位置评分。如果我们在此位置添加一个元素(不包括我们现在添加的元素),则该分数等于我们连续有多少个相同种类的元素(垂直,水平或对角线,并保持这3个元素中最好的一个)
第二个功能一次检查7个位置,并找到得分最高的位置并将其返回。我尝试添加一些随机性,以使如果2个位置的分数相同,则程序将在30%的时间内选择最后一个(这样就不会总是取第一个)。
在没有增加随机性的地方,代码可以正常运行。一旦添加它,程序将在第12次调用第一个函数后立即暂停。此外,该程序的CPU使用率突然激增,并从之前的5%降至50%。
我修改了几次创建随机性的代码,但似乎没有任何变化。我什至不明白为什么它会引起这样的问题。
我的2个功能是:
int aiCheckScore(char arr[7][7], int inp, int height, Player player) {
int i, j;
int score[4] = { 0 };
//check horizontal score
for (i = inp - 1; i >= 0; i--) { //everything left
if (arr[height][i] != player.symb)
break;
++score[0];
}
for (i = inp + 1; i <= 6; i) { //everything right
if (arr[height][i] != player.symb)
break;
++score[0];
}
//check vertical score (we only have to check down)
for (i = height + 1; i <= 6; i++) {
if (arr[i][inp] != player.symb)
break;
++score[1];
}
//check diagonal (which starts left and above and goes down and right)
j = height - 1;
for (i = inp - 1; i >= 0 && j >= 0; i--) { //above and left
if (arr[j][i] != player.symb)
break;
++score[2];
--j;
}
j = height + 1;
for (i = inp + 1; i <= 6 && j <= 6; i++) { //down and right
if (arr[j][i] != player.symb)
break;
++score[2];
++j;
}
//check diagonal (which starts left and down and goes up and right)
j = height + 1;
for (i = inp - 1; i >= 0 && j <= 6; i--) { //down and left
if (arr[j][i] != player.symb)
break;
++score[3];
++j;
}
j = height - 1;
for (i = inp + 1; i <= 6 && j >= 0; i++) { //up and right
if (arr[j][i] != player.symb)
break;
++score[3];
--j;
}
int bestscore = score[0];
for (i = 0; i <= 3; i++) {
if (score[i] > bestscore)
bestscore = score[i];
}
printf("%d", bestscore);
return bestscore;
}
int aiFindMostRelevant(char arr[7][7], Player player) {
int i, height;
int score[7] = { 0 };
for (i = 0; i <= 6; i++) {
height = findHeight(arr, i);
if (height == -1) {//skip the columns that are full
score[i] = -100; //and give them a very bad score
}
else {
score[i] = aiCheckScore(arr, i, height, player);
}
}
int bestscore = score[0];
int bestposition = 0;
int num;
for (i = 0; i <= 6; i++) {
num = (int)rand() % 10;
if (score[i] == bestscore) { //if 2 positions have the same score
if (num >= 7) { //there is a 30% chance the ai will take the new one to add some variety
bestposition = i;
}
}
if (score[i] > bestscore) { //always take the position with the best score
bestscore = score[i];
bestposition = i;
}
}
return bestposition;
}
对于解决此问题的任何帮助,我们将不胜感激,并且欢迎总体上改善我的代码的任何建议
答案 0 :(得分:3)
似乎其中一个循环没有增量。 更改:
for (i = inp + 1; i <= 6; i)
至for (i = inp + 1; i <= 6; ++i)
看看是否有帮助。