1
votes

Hi I want to make a four connect game for 2 local players. I created everything but im not sure if my code for win condition is okay and i have no idea how to check the condition for diagonal win. my Code for the win condition:

int checkIfWon(array<array <char, cols>, rows> board) {
    //Check for Horizontal
    int countP1 = 0;
    int countP2 = 0;
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            if (board.at(i).at(j) == p1Color) {
                ++countP1;
                countP2 = 0;
            }
            else if (board.at(i).at(j) == p2Color) {
                ++countP2;
                countP1 = 0;
            }
            if (countP1 >= 4) {
                return 1;
            }
            if (countP2 >= 4) {
                return 2;
            }
        }
    }
    //Check for Vertical
    countP1 = 0;
    countP2 = 0;
    for (int i = 0; i < cols; ++i) {
        for (int j = 0; j < rows; ++j) {
            if (board.at(j).at(i) == p1Color) {
                ++countP1;
                countP2 = 0;
            }
            else if (board.at(j).at(i) == p2Color) {
                ++countP2;
                countP1 = 0;
            }
            if (countP1 >= 4) {
                return 1;
            }
            if (countP2 >= 4) {
                return 2;
            }
        }
    }
    return 0;
}
You never reset the counters at the start of a row/column so if there are 2 cells of one color at the end of row 0 and 2 cells of the same color at the start of row 1, you consider this a win for this color...fabian
and i have no idea how to check the condition for diagonal win -- No idea whatsoever? Then how did you come up with the code you have now?PaulMcKenzie
@fabian thanks i forgot this.Nexxizz