我添加了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使用率突然飙升,并保持在50%以下,低于之前的5%。
我已经修改了几次创建随机性的代码,但似乎没有任何改变。我甚至无法理解为什么会导致这样的问题。
我的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;
}
任何帮助解决这个问题将不胜感激,欢迎任何通常改进我的代码的建议
看起来其中一个循环没有增量。更改:
for (i = inp + 1; i <= 6; i)
到for (i = inp + 1; i <= 6; ++i)
并看看它是否有帮助。