首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检验Gomoku胜诉条件的C++准则

检验Gomoku胜诉条件的C++准则
EN

Stack Overflow用户
提问于 2015-06-27 20:58:35
回答 1查看 495关注 0票数 1

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

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

代码语言:javascript
复制
std::string state = "00000x012122x00100x00222x010201"

我要做的是检查当前球员的水平的匹配值为3(稍后我将处理垂直和对角线);比方说,白色,所以我在字符串中依次寻找32s的匹配,而只有32s。

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

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

代码语言:javascript
复制
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列中,它仍然是匹配的。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-27 21:24:36

虽然我不认为使用regex进行此操作有什么意义,但下面的模式与3完全匹配:

代码语言:javascript
复制
std::string playerStr = std::to_string(current_player);
std::string pattern =  "(^|[^" + playerStr + "])(" + playerStr + "{3})($|[^" + playerStr + "])";
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31093441

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档