AI 忽略 Connect4 中的设置参数

AI is ignoring set parameters in Connect4

本文关键字:设置 参数 忽略 Connect4 AI      更新时间:2023-10-16

我目前完成了 90% 的 Connect4 游戏C++,但我遇到了一个相当烦人的错误。游戏玩得很好,除了一件事之外,一切都很好;玩家与计算机对战,但计算机忽略我为其设置的参数,并将其棋子放在棋盘上的任何位置。这可能是我的逻辑错误吗?我知道这不是人工智能的例子,但它是总结它的最佳方式。 这是函数:

void columnChoiceComputer(int computer)
{
int number = 0;
srand(time(0));
cout << (rand() % 6 + 1) << endl;
if (cin.fail())
{
cout << "Error!";
srand(time(0));
cout << (rand() % 6 + 1) << endl;
}
while ((rand() % 6 + 1) > WIDTH || (rand() % 6 + 1) <= 0)
{
cout << "Please select a different column.";
srand(time(0));
cout << (rand() % 6 + 1) << endl;
}
while (boardMatrix[(HEIGHT - 1) - number][((rand() % 6 + 1) - 1)] != 0)
{
number++;
if (number > (HEIGHT - 1))
{
cout << "Please select a different column.";
srand(time(0));
cout << (rand() % 6 + 1) << endl;
number = 0;
}
};

boardMatrix[(HEIGHT - 1) - number][(rand() % 6 + 1) - 1] = computer;
lastMoveY = (HEIGHT - 1) - number;
lastMoveX = ((rand() % 6 + 1)) - 1;
(system("cls"));

}

首先,非常感谢那些帮助过我的人。解决方案非常简单,而不是每次调用函数时都调用 (rand(( % 6 + 1(,我只需要将随机数的第一次迭代设置为一个名为"computerChoice"的变量,然后简单地调用该变量。以下是更新的代码:

int number = 0;
srand(time(0));
int computerChoice = (rand() % 6 + 1);
while (computerChoice > WIDTH || computerChoice <= 0)
{
cout << "Please select a different column.";
srand(time(0));
cout << (rand() % 6 + 1) << endl;
}
while (boardMatrix[(HEIGHT - 1) - number][(computerChoice - 1)] != 0)
{
number++;
if (number > (HEIGHT - 1))
{
cout << "Please select a different column.";
srand(time(0));
cout << (rand() % 6 + 1) << endl;
number = 0;
}
};
boardMatrix[(HEIGHT - 1) - number][computerChoice - 1] = computer;
lastMoveY = (HEIGHT - 1) - number;
lastMoveX = (computerChoice) - 1;
(system("cls"));