Search code examples
javatic-tac-toe

How I do check_game_state method in tictactoe game?


I want to understand whether the game is finished or drawn or still playable. But I want to do it with dynamic code.

For example I do it static for 3*3 tictactoe game like this :

private static boolean check_game_state(char[] board)
{
    if (    (board[0]==cSymbol && board[1]==cSymbol && board[2]==cSymbol) 
         || (board[3]==cSymbol && board[4]==cSymbol && board[5]==cSymbol) 
         || (board[6]==cSymbol && board[7]==cSymbol && board[8]==cSymbol)
         || (board[0]==cSymbol && board[3]==cSymbol && board[6]==(cSymbol))
         || (board[1]==(cSymbol) && board[4]==(cSymbol) && board[7]==(cSymbol))
         || (board[2]==(cSymbol) && board[5]==(cSymbol) && board[8]==(cSymbol))
         || (board[0]==(cSymbol) && board[4]==(cSymbol) && board[8]==(cSymbol))
         || (board[2]==(cSymbol) && board[4]==(cSymbol) && board[6]==(cSymbol)))
    {
        if (cSymbol == 'X')
        {
            state = 5;  //player 1 win
        }
        else if (cSymbol == 'O')
        {
            state = 4; player 2 win
        } 
    }
}

I want to it dynamically for a 4*4 or 5*5 or higher board. But how can I do it? Is it possible?


Solution

  • Instead of hard-coding the indices, you need to access the elements in a loop. E.g. instead of

    boolean test = (board[0]==cSymbol && board[1]==cSymbol && board[2]==cSymbol);
    

    You would do something like

    boolean test = true;
    for (int i = 0; i < length; ++i) {
      test = test && board[i] == cSymbol ;
    }
    

    where length is the size of the board (e.g. 5, 6), same as square root of the board.length You need to either calculate this from the array length or pass it to the function along with the array itself

    This will set test to true only if all elements were equal to cSymbol, false otherwise.

    Update: I give you the calculation for the rows; you will need to adopt this to the columns (hint: calculate index i+j*length), main dialonal (index: i*length+i) and sub-diagonal (index: i*length+(length-1-i)). The index i*length + j translates to the ith row, jth column:

    private static boolean check_game_state(char[] board, int length) 
    { 
      bool row = false;
      for (int i = 0; i < length; ++i) {
        bool innerRow = true;
        for (int j = 0; j < length; ++j) { // calculate the ith row
          innerRow = innerRow && board[i*length+j] == cSymbol;
        }
        row = row || innerRow;
      }
      if (row) 
      { 
        // somebody won...
      } 
    }