我目前已经完成了90%的C++版Connect4游戏,但遇到了一个相当烦人的错误。游戏本身运行良好,所有功能都正常工作,只有一件事例外;玩家与电脑对战时,电脑忽略了我为其设定的参数,并在棋盘上的任何位置放置棋子。这可能是我的逻辑错误吗?我知道这不是AI的例子,但这是总结问题的最佳方式。以下是相关函数:
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"));