Emmanuel
Emmanuel

Reputation: 453

gomoku diagonal winning condition

am currently working on a Gomoku game for windows and am using MFC. Am currently working on the winning algorithm for diagonals. My horizontal and vertical work just fine. Am hoping someone can help shade some light on where my logic is wrong. here is the code:

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;
        }
    }
 }
}

It only works in the diagonal connected to the top left corner. Fairly new to programming so any help will greatly be appreciated.

Upvotes: 0

Views: 2839

Answers (1)

Barmak Shemirani
Barmak Shemirani

Reputation: 31669

The rules of this game is that 5 items should match in a row, or in a column, or in a diagonal line. Just compare each row, column, and diagonal line to see if 5 items match, and return true. Otherwise the function should return 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;
}

Upvotes: 3

Related Questions