gomoku对角线胜利条件

时间:2017-12-11 14:10:08

标签: c++ visual-c++ mfc

我目前正在使用Gomoku游戏进行Windows并使用MFC。我目前正致力于对角线的获胜算法。我的水平和垂直工作都很好。我希望有人可以帮助掩盖我逻辑错误的地方。这是代码:

bool CMainFrame::isWinner(int player){
for (int row = 0; row < data.size(); row++) {
    for (int col = 0; col < data.size(); col++) {
        if (data[row][col].color == player && data[row + 1][col + 1].color == player && data[row + 2][col + 2].color == player && data[row + 3][col + 3].color == player && data[row + 4][col + 4].color == player) {
            CheckForGameOver(player); //function that simply shows message box of winning piece
            return true;
        }
    }
 }
}

它仅适用于连接左上角的对角线。编程相当新,所以任何帮助都将受到极大的赞赏。

1 个答案:

答案 0 :(得分:2)

这个游戏的规则是5个项目应该在一行,一列或一条对角线上匹配。只需比较每一行,每列和对角线,看看是否有5个项匹配,并返回true。否则该函数应返回false。

bool won(std::vector<std::vector<data_t>> &data, int color)
{
    //check each row:
    for(int row = 0; row < 15; row++)
        for(int col = 0; col < 10; col++)
        {
            bool match = true;
            for(int i = 0; i < 5; i++)
                if(color != data[row][col + i].color)
                    match = false;
            if(match) return true;
        }
    //check each column:
    for(int col = 0; col < 10; col++)
        for(int row = 0; row < 15; row++)
        {
            bool match = true;
            for(int i = 0; i < 5; i++)
                if(color == data[row + i][col].color)
                    match = false;
            if(match) return true;
        }
    //check diagonal lines from top-left to bottom-right
    for(int col = 0; col < 10; col++)
        for(int row = 0; row < 10; row++)
        {
            bool match = true;
            for(int i = 0; i < 5; i++)
                if(color == data[row + i][col + i].color)
                    match = false;
            if(match) return true;
        }
    //lastly check diagonal lines from top-right to bottom-left
    return false;
}