有没有办法在TicTacToe中实现AI到计算机?



我有一个运行Tictactoe游戏的程序,但我想将AI添加到计算机功能中,这样

玩起来可能会更困难我尝试了 rand(); 但它只是让计算机将决定放在任何可用的插槽中。

void ia_turn(){
while (true){
int ia_tu = (rand() % 9) +1;
int ia_op = ia_tu - 1;
int row = ia_op / 3;
int column = ia_op % 3;
char matrix_pos = matrix[row][column];
if (matrix_pos == 'X' || matrix_pos == 'O'){ 
continue;
}else{
cout << "The AI selected the position: "<<ia_tu<<endl;
matrix[row][column] = 'O';
break;
}
}
}

我希望 ComputerAI 的动作会阻止我的动作,但不能用 rand() 函数来完成。

这是我拥有的检查胜利功能

void checking_for_wins(){
const char* wins_possibilities[8] = {"123","456","789","159","753","147","258","369"};
for (int i =0;i<8;i++){
bool win = true;
char prev_op = '0';
const char* win_possibility = wins_possibilities[i]; //funciona como puntero en caso de que se cumpla uno de las wins_possibilities[]
for (int rcl = 0;rcl<dim_m;rcl++){
char alphaChar = win_possibility[rcl];
int intr_number = alphaChar - '0';
int op_sp = intr_number - 1;
int row = op_sp / dim_m;    //busca la posición de la fila
int column = op_sp % dim_m; //busca la posición de la columna
char current_op = matrix[row][column];
if (prev_op == '0'){
prev_op = current_op;
}else if (prev_op == current_op){
continue;
}else{
win = false;
break;
}
}
if (win){
cout << "Felicidades, ganaste!! n";
cout << "El jugador "<<prev_op<<" gana, felicidades! n";
exit(0);
break;
}
}
}

最好的开始方法是编写一个函数来寻找可能的胜利(而不是查看是否连续有三个,而是检查是否连续有两个)。然后让函数返回将是胜利的空间,并让 AI 移动到那里。例如:如果矩阵看起来像

X X _
_ _ _
_ O O

让函数返回 0,2 和 2,0。 然后让你的AI从中随机选择。

之后,您可以修改该函数以返回谁可能获胜,然后让您的AI始终更喜欢去它会赢的地方。

实现可能如下所示:

#include <vector> // Vector comes from this
#include <utility> // Pair comes from this
std::vector<std::pair<bool, Point>> GetPossibleVictories()
{
std::vector<std::pair<bool, Point>> retVal;
// Check for two in a row Horitzontally, Vertically, and Diagonally.
{
if (/*IsPossibleWin*/)
{
retVal.push_back(std::pair<bool, Point>(isAIsVictory, Point{ X, Y }));
}
}
return retVal;
}

此外,我还会研究更现代的C++结构,这些结构可以帮助你,比如容器(std::vector,std::list,std::set等),它可以帮助你以更容易操作的方式存储矩阵。

在上面的例子中,我使用了一个自定义类型(Point),它可以以最简单的方式进行如下编程:

struct Point
{
int X = 0;
int Y = 0;
};

通过使用结构(或默认情况下每个成员都是公共的类),您可以将矩阵的坐标存储在单个对象中。此外,我正在使用一个类似于自动调整大小数组的向量。您可以像这样遍历向量中的每个内容:

for(const auto& possibleWin : possibleWins) // possibleWins is the vector returned from the previous example.
{
// possibleWin in this block will be the same value as if you used a for loop and did possibleWins[x]
}

最后,上面的例子使用了 Pair,它只包含两种不同类型的东西。它可以按如下方式使用:

std::pair<bool, Point> myPair;
myPair.first = true;
myPair.second = Point{0, 2};

如需更多阅读(滚动到底部以获取有关如何使用它们的示例):

  • 向量

希望这可以给你一些关于如何开始让你的人工智能更聪明的想法。

最新更新