c++ - 为什么我的 TicTacToe 游戏在生成随机移动时会卡住

标签 c++

对于我的 Tic Tac Toe AI,只需生成随机移动。我有一个带有 makeAMove 函数的 AIPlayer 类。它只是生成 0 - 3 之间的两个随机数(行和列)并检查单元格是否已被占用。它似乎工作得很好,但由于某种原因,它永远不会采取获胜的行动。在命令行上,当我试图让它获胜并且只剩下获胜的 Action 可供它采取时,它不会采取这些 Action - 它只是被卡住了。

此外,我认为使用 AI 时使用一维数组会更容易,但我尝试坚持使用二维数组。

我认为最好以某种方式收集另一个数组中的可用单元并从这些单元生成随机移动。

欢迎任何建议。

这是我的人工智能类(class):

实现文件:

#include <stdlib.h> // rand, srand
#include <time.h> // time
#include "AIPlayer.h"

AIPlayer::AIPlayer(char token) : Player(token)
{
}

void AIPlayer::makeAMove(Board &myBoard)
{
    int row;
    int column;

    bool done = false;
    do
    {
        srand (time(0));
        row = rand() % 3;
        column = rand() % 3;

        if (myBoard.getCell(row, column) == ' ')
        { 
            myBoard.setCell(row, column, getToken());
            done = true;
        }
    }
    while (!done);

    std::cout <<    "\nComputer move (" << getToken() << ")\n"
                    "row " << row << ", column " << column;
}

头文件:

#pragma once // include guard
#include "Player.h"

class AIPlayer: public Player
{
    public:
        AIPlayer(char token);
        virtual void makeAMove(Board &myBoard);
};

最佳答案

在循环的每次迭代中,您调用 srand(time(0))。

这会根据经过的秒数重置随机数生成。

这意味着每次计算机都会选择相同的随机位置进行移动(直到秒数发生变化)

大约一分钟后它可能会真正起作用,但最好将 srand 移出循环。

关于c++ - 为什么我的 TicTacToe 游戏在生成随机移动时会卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20618792/

相关文章:

c++ - 优化 Dijkstra 算法

c++ - Cuda NVCC 编译器 - 如何/showincludes?

c# - 使用系统;在 C# 中与使用命名空间标准;在 C++ 中

c++ - 获取[e][wifigeneric.cpp :739] hostbyname(): dns failed when performing POST request

c++ - 访问另一个程序的值

c++ - Qt5-QML : How to modify bindings to change Text after ProgressBar finishes loop

c++ - 创建全局常量 C 字符串的正确方法

c++ - int 和 double 的区别

c++ - `std::sample()`的输出序列是否遵循输入序列的顺序?

c++ - 当我从 cron 运行通常会核心的东西时,我怎么还能得到我的核心转储?