C++游戏、线程和并发编程

C++ game, threads and concurrent programming

本文关键字:并发 编程 线程 游戏 C++      更新时间:2023-10-16

我迫切需要一些指导。我需要编写一个Connect 4的游戏程序,其中将应用线程并行编程。我需要自己学习,并在一周内写出这样的程序。我现在不知道如何实现并发部分,我应该寻找什么资源。。。希望你能对此有所了解…

这个想法似乎是计算机玩家本身就是一个线程,主线程处理游戏,即协调人类玩家和机器人玩家。

下面是一些(伪)代码,可以帮助您入门。

std::mutex m;
std::queue<int> from_opponent;
std::queue<int> from_robot;
void robotplayer(bool& go_on)
{
    bool wait_for_opponent = true;
    while (go_on)
    {
        int opponents_move;
        while (wait_for_opponent)
        {
            // Spend x milliseconds planning next move
            // ...
            // ...
            m.lock();
            if (!from_opponent.empty())
            {
                opponents_move = from_opponent.front();
                from_opponent.pop();
                wait_for_opponent = false;
            }
            m.unlock();
        }
        // ... calculate robots move
        // ...
        m.lock();
        from_robot.push(row_number);
        m.unlock();   
        wait_for_opponent = true;
    }
}
int main()
{
    bool go_on = true;
    std::thread robot(robotplayer, go_on);
    while(go_on)
    {
        // Wait for input from user (e.g. via cin)
        // Send move to robot
        m.lock();
        from_opponent.push(row_number);
        m.unlock();   
        // Update display
        // Check for a winner (i.e. set go_on = false)
        // Wait for input from robot
        // Update display
        // Check for a winner (i.e. set go_on = false)
    }
    robot.join();
}