5. Write a method public char checkWinner(char grid) to identify the winner from
ID: 663341 • 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
I have defined following function as mentioned in the above question.As it is mentioned in question that function should get character type datatype and it should return type character datatype.I hope this function will help in solving your problem.This code has been coded in C++.
char checkWinner(char arr[][4])
{
//variable to hold result
char result='B';
//variable to hold counter
int i=1;
//Check player 1 status
for(i=1; i<4; i++) /* check rows */
{
if(arr[i][1]=='X' && arr[i][2]== 'X' && arr[i][3]=='X') // it is for the drows
{
result='X';
}
}
for(i=1; i<4; i++) /* check columns */
{
if(arr[1][i]=='X' && arr[2][i]== 'X' && arr[3][i]=='X')
{
result='X';
}
}
/* test diagonals */
if(arr[1][1]=='X' && arr[2][2]== 'X' && arr[3][3]=='X')
{
result='X';
}
if(arr[1][3]=='X' && arr[2][2]=='X' && arr[3][1]=='X')
{
result='X';
}
//Check player 2 status
for(i=1; i<4; i++) /* check rows */
{
if(arr[i][1]=='O' && arr[i][2]== 'O' && arr[i][3]=='O')
{
result='O';
}
}
for(i=1; i<4; i++) /* check columns */
{
if(arr[1][i]=='O' && arr[2][i]=='O' && arr[3][i]=='O')
{
result='O';
}
}
/* test diagonals */
if(arr[1][1]=='O' && arr[2][2]== 'O' && arr[3][3]=='O')
{
result='O';
}
if(arr[1][3]=='O' && arr[2][2]=='O' && arr[3][1]=='O')
{
result='O';
}
return result;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.