Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

5. Write a method public char checkWinner(char[] [] grid) to identify the winner

ID: 665711 • Letter: 5

Question

5. Write a method public char checkWinner(char[] [] grid) to identify the winner from a given game state in a TicTacToe game. The game is played on a square grid of size at least 3 x 3. Every position in the grid contains one of the characters 'X', 'O' or ' '. The method checkWinner should return the winner's character ('X' or 'O') if any row, column, or corner-to-corner diagonal in its argument array grid contains all the same non-blank character; it should return ' ' otherwise. Write helper methods to make your code readable.

Explanation / Answer


public class TickTackMethod {
  
// global variables declared
     
   public static final int R = 3, C = 3;
  

   public static char P1 = 'X';
   public static char P2 = 'O';
   public static char EMPTY = '.';
   public static char[][] grid = new char[R][C];
  
  
   public static int r, c;
   public static int stat_curr;
   public static char play_curr;
   public static int R_curr, C_curr;
  
  
  
   public static final int G_BEG = 0;
   public static final int NO_RES = 1;
   public static final int P_X = 2;
   public static final int P_O = 3;
  
  
   //Method to check if it's a draw
   public static boolean stalemate()
   {
       for (int i = 0; i < R; ++i) {
   for (int j = 0; j < C; ++j) {
   if (grid[i][j] == EMPTY) {
   return false;
   }
   }
   }
   return true;
   }
  
   //Method to find winner
   public static boolean checkWinner(char[][] grid)
   {
       char player=play_curr;
       if(hasWon(player))
       {
           stat_curr = (player == P1) ? P_X : P_O;
           return true;
       }
       else if (stalemate())
       { // check for draw
   stat_curr = NO_RES;
   return false;
   }
       return false;
      
   }
  
  
   //Method to check winning condition
   public static boolean hasWon(char player) {
   return (grid[R_curr][0] == player // 3-in-the-row
   && grid[R_curr][1] == player
   && grid[R_curr][2] == player
   || grid[0][C_curr] == player // 3-in-the-column
   && grid[1][C_curr] == player
   && grid[2][C_curr] == player
   || R_curr == C_curr // 3-in-the-diagonal
   && grid[0][0] == player
   && grid[1][1] == player
   && grid[2][2] == player
   || R_curr + C_curr == 2 // 3-in-the-opposite-diagonal
   && grid[0][2] == player
   && grid[1][1] == player
   && grid[2][0] == player);
   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote