0

I am implementing a tic-tac-toe AI in jquery. I am almost done, but I seem to have a problem with my check_winner() function. It is basicly the same thing as the c version. It checks rows, cols, diagonals and returns -1 for player win, 1 for ai win and 0 for no winner yet. I have been going over it for days and I cannot find anything wrong. When playing the game it will return 0 when I have 3 in a row, it will return 1 when the ai does not have 3 in a row. I can't figure it out. Here is the code:

/**
 *  check for winner
 */
function check_winner(hyp_board)
{
    var first_cell, winner, i ,j;
    for (i = 0; i < grid_size; i++){

        // check each row
        first_cell = hyp_board[i][0];
        for (j = 1; j < grid_size; j++){
            winner = hyp_board[i][j];
            if (first_cell != winner){
                winner = 0;
                break;
            }
        }
        if (winner != 0) return winner;

        // check each colum
        first_cell =  hyp_board[0][i];
        for (j = 1; j < grid_size; j++){
            winner = hyp_board[j][i];
            if (first_cell != winner){
                winner = 0;
                break;
            }
        }
        if (winner != 0) return winner;

        // check diagonals
        first_cell = hyp_board[0][0];
        for (j = 1; j < grid_size; j++){
            winner = hyp_board[j][j];
            if (first_cell != winner){
                winner = 0;
                break;
            }
        }
        if (winner != 0) return winner;

        first_cell = hyp_board[0][grid_size - 1];
        for (j = 1; j < grid_size; j++){
            winner = hyp_board[j][grid_size - 1 - j];
            if (first_cell != winner){
                winner = 0;
                break;
            }
        }
        return winner;
    }
}

Please help.

1 Answer 1

1

Assume grid size 3 and hyp_board

0 | 0 | -1
0 | 0 | 0
1 | 0 | 1

The first "check each row" loop will return 1 as the winner. Won't it?

"On paper" from i = 2:

first_node = hyp_board[2][0] = 1.
j = 1.
winner = hyp_board[2][1] = 0.
1 != 0, winner = 0.
j = 2.
winner = hyp_board[2][2] = 1.
1 == 1. winner != 0, return winner (1).

8
  • Thanks, that helped. I added a break after each winner = 0; statement. That catches that. But it still isn't returning a win. It should return 1 when all 3 are 1, but it returns 0? Dec 17, 2016 at 16:46
  • What board layout does not give you the value you expect? Dec 17, 2016 at 16:53
  • -1, -1, -1 should return -1. The code is at github.com/cullian/Tic-Tac-Toe-AI Dec 17, 2016 at 17:16
  • What is the whole board layout (not just one row). Dec 17, 2016 at 17:23
  • different ones, it works for diagonal 1,1,-1,-1,-1,-1,1,0,0 gave me a 0. Dec 17, 2016 at 17:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .