Help with simplifying int main ( ) for Tic Tac Toe Program


I'm currently taking a beginner C++ course and finished a lab assignment a couple weeks ago (so it has already be turned in and graded). My professor asked that in the future the int main () section be minimized as much as possible to only function calls. I'm having some difficulty figuring out how I could have made it simpler.

Is there a way for me to take everything within the while loop and put it into its own function. What would the parameters for that function?

(This is just the int main () and does not include the code for the functions, let me know if you'd like me to provide the rest of my code)


int main()
{

char board[rows_columns][rows_columns]; //Initialize Board
char a,b; // To hold X and O Markers
int x,y; // Algebraic notation variables for position on the board
a='X';
b='O';
bool play = true;
initializeBoard(board);
displayBoard(board);

while(true) //Cycles through turns and "breaks" from loop if Winner is found
{
getInput(board,a,x,y);
markBoard(board, x,y,a);
displayBoard(board);

if (check_Game_Winner(board))
break;

getInput(board,b,x,y);
markBoard(board, x,y,b);
displayBoard(board);

if (check_Game_Winner(board))
break;
}

return 0;
Last edited on
Your main() could consist of
1
2
3
{
   playGame();
}
Is there a way for me to take everything within the while loop and put it into its own function. What would the parameters for that function?

Yes, you just need to pass everything that the function needs as arguments. This gets easier if you encapsulate all the variables that make up the state of the game in a single object. That way you only need to pass that object as argument.

Whether or not it makes sense to put everything inside the loop inside a single function is a different question. You already use a lot of functions. If you want to put it inside a function then you should think about what the code does and come up with a name to describe it. If you cannot come up with a name, or you end up having to use a lot of "and" to combine widely different actions (e.g. doXandY()), then it might be a sign that they don't belong together in the same function.

At the moment you have essentially the same code repeated twice. Once for each player. You might want to think about ways to avoid having to repeat the same code for each player. Whether or not you use additional functions for this is up to you.
Last edited on
Perhaps something like (not tried):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bool process(char board[rows_columns][rows_columns], char p, int x, int y) {
	displayBoard(board);
	getInput(board, p, x, y);
	markBoard(board, x, y, p);
	return check_Game_Winner(board);
}


int main() {
	constexpr char plays[] {"XO"};
	char board[rows_columns][rows_columns] {};
	int x {}, y {};

	initializeBoard(board);

	for (bool p {}; !process(board, plays[p], x, y); p = !p);
}

Topic archived. No new replies allowed.