用于检查Gomoku获胜条件的C++正则表达式

C++ regex for checking Gomoku win condition

本文关键字:C++ 正则表达式 条件 获胜 检查 Gomoku 用于      更新时间:2023-10-16

我构造了一个字符串,表示我的整个Gomoku游戏板(例如5x5),其中0表示空,1或2表示黑色或白色。

在每一行之间放置一个字符串"x"以分隔行。

std::string state = "00000x012122x00100x00222x010201"

我想做的是检查当前玩家水平的3匹配(稍后我将处理垂直和对角线);比方说,白色,所以我在字符串中寻找三个2的匹配,而只有三个2。

Gomoku不允许上划线,这意味着正则表达式不能匹配4或更多。

以下是我对这个问题的尝试:

bool Game::check_horizontal(std::string state)
// Checks if the current_player (stored in the class) has won horizontally.
{
    std::string pattern = "(" + std::to_string(current_player) + "{3})"; // Current player is white by default.
    std::regex reg1(pattern);
    if (regex_search(state, reg1) == true)
    {
        std::cout << "Match! Someone has won." << std::endl;
        return true;
    }
    else
    {
        std::cout << "No match... keep going." << std::endl;
        return false;
    }
}

到目前为止,代码似乎可以按照上面的状态运行,但如果有4个或更多我想要的,它会保持匹配。如果我在第4行第2列再加2,它仍然会匹配。

我的正则表达式或regex的使用有问题吗?

虽然我认为使用regex没有任何意义,但这里有一个与3:完全匹配的模式

std::string playerStr = std::to_string(current_player);
std::string pattern =  "(^|[^" + playerStr + "])(" + playerStr + "{3})($|[^" + playerStr + "])";