mercredi 26 avril 2017

Why does my function always return 1?

I'm writing a function that's supposed to check whether there is a winner or not in a game of "noughts and crosses", or "three in a row".

The game works by first drawing out 3 x 3 squares in the command prompt. The user then moves the cursor between the squares, and presses enter to place an "X". The next selected square gets an "O" placed in it, and then an "X" again, and so on. After turn 5 (the first possible turn there could be a winner) the program checks if there is a winner after every turn, and if none is found after 9 turns (when all squares have something in them) the program declares a draw.

However, the function I've written to check for a winner always returns 1 when it's called, which means there is a winner (X more specifically, since thatäs the one that made the last move). Therefore the game ends on turn 5, no matter what the squares contain.

Here is my code:

int control(char p[3][3]) {
    int i;
    for (i = 0; i <= 3; i++)    //Checks if any of the horizontals have 3 of the same markers in a row
        if (p[i][1] == p[i][2] && p[i][2] == p[i][3]) 
            return 1;

    for (i = 0; i <= 3; i++)    //Checks if any of the vertical columns have 3 of the same markers
        if (p[1][i] == p[2][i] && p[2][i] == p[3][i])
            return 1;
        else if (p[1][1] == p[2][2] && p[2][2] == p[3][3])    //Checks if top left, middle and bottom right squares have the same marker
            return 1;
        else if (p[3][1] == p[2][2] && p[2][2] == p[1][3])    //Checks if the top right, middle and bottom left have the same marker
            return 1;
        else               //If none of the above have the same 3 markers, the game keeps going
            return 0;
}

Aucun commentaire:

Enregistrer un commentaire