would appreciate if anyone could look through my tic tac toe code and what I possibly do to improve upon it.
Initializing the Board
void BoardInitializer(char board[HORIZONTAL][VERTICAL])
{
char index = '1';
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
board[i][j] = index;
index++;
}
}
}
Printing the board
void DrawBoard(char board[HORIZONTAL][VERTICAL])
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%c", board[i][j]);
if (j != 2)
printf("|");
}
if (i != 2)
printf("\n---------");
printf("\n");
}
}
Determining the position of X & Os
int PositionCalculation(char board[3][3], int selection, char input)
{
int column = selection % 3;
int row = selection / 3;
if (column == 0)
{
column += 3;
row -= 1;
}
if (board[row][column - 1] == 'o' || board[row][column - 1] == 'x')
return -1;
board[row][column - 1] = input;
return 0;
}
Win condition checks
bool HorizontalCheck(char board[HORIZONTAL][VERTICAL])
{
for (int i = 0; i < HORIZONTAL; i++)
{
if (board[i][0] == board[i][1] && board[i][1] == board[i][2])
return true;
}
}
bool VerticalCheck(char board[HORIZONTAL][VERTICAL])
{
for (int i = 0; i < VERTICAL; i++)
{
if (board[0][i] == board[1][i] && board[1][i] == board[2][i])
return true;
}
}
bool DiagonalCheck(char board[HORIZONTAL][VERTICAL])
{
if ((board[0][0] == board[1][1] && board[1][1] == board[2][2]) || (board[0][2] == board[1][1] && board[1][1] == board[2][0]))
return true;
}
The main program
#define HORIZONTAL 3
#define VERTICAL 3
void TicTacToe()
{
int selection = 0;
int counter = 0;
int checker = 0;
char board[HORIZONTAL][VERTICAL];
BoardInitializer(board);
DrawBoard(board);
while (counter != 9)
{
if (counter % 2 == 0)
{
printf("\nPlease input where you want to place X: ");
scanf(" %d", &selection);
SCANX:
while (selection < 0 || selection > 10)
{
printf("Invalid input, please try again: ");
scanf(" %d", &selection);
}
printf("\n");
checker = PositionCalculation(board, selection, 'x');
if (checker == -1)
{
selection = -1;
goto SCANX;
}
DrawBoard(board);
counter++;
if (counter > 3)
{
if (HorizontalCheck(board) == true || VerticalCheck(board) == true || DiagonalCheck(board) == true)
goto XWINS;
}
}
else
{
printf("\nPlease input where you want to place O: ");
scanf(" %d", &selection);
SCANO:
while (selection < 0 || selection > 10)
{
printf("Invalid input, please try again: ");
scanf(" %d", &selection);
}
printf("\n");
checker = PositionCalculation(board, selection, 'o');
if (checker == -1)
{
selection = -1;
goto SCANO;
}
DrawBoard(board);
counter++;
if (counter > 3)
{
if (HorizontalCheck(board) == true || VerticalCheck(board) == true || DiagonalCheck(board) == true)
goto OWINS;
}
}
}
printf("Its a draw\n");
goto ENDPROGRAM;
XWINS:
printf("\nX wins!\n");
goto ENDPROGRAM;
OWINS:
printf("\nO wins\n");
goto ENDPROGRAM;
ENDPROGRAM:
return;
}