Create a class TicTacToe that will enable you to write a complete program to pla
ID: 3643688 • Letter: C
Question
Create a class TicTacToe that will enable you to write a complete program to play the game of tic-tac-toe. The class contains as private data a 3-by-3 two-dimensional array of integers. The constructor should initialize the empty board to all zeros. Create a second class Player that maintains information about each player. Allow for two human players. Wherever the first player moves, place an X in the specified square. Place an O wherever the second player moves. Each move must be to an empty square. After each move, determine whether the game has been won or is a draw.Explanation / Answer
#include #include #include #include using namespace std; enum GameStatus {WIN, CONTINUE, DRAW}; class Player { private: string name_; public: Player() : name_("anonymous") {}; Player(const string & name) : name_(name) {}; void get_name() { cout > name_; } string name() { return name_; } }; class TicTacToe { private: // a char is a short int char board[3][3]; Player * player_1; Player * player_2; Player * current; char cell(int r, int c) { return (board[r][c] == 0 ? '0' : board[r][c]); } public: TicTacToe() { // Initialize all to 0's for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { board[i][j] = 0; } } player_1 = NULL; player_2 = NULL; } string current_player_name() { return current->name(); } void add_player(Player * player) { // if NULL if (!player_1) { player_1 = player; } else if (!player_2) { player_2 = player; } } Player * current_player() { return current; } GameStatus get_status() { // check for a win on diagonals if ( board[0][0] != 0 && board[0][0] == board[1][1] && board[0][0] == board[2][2] ) { return WIN; } else if ( board[2][0] != 0 && board[2][0] == board[1][1] && board[2][0] == board[0][2] ) { return WIN; } // check for win in rows for (int a = 0; a < 3; ++a ) { if ( board[a][0] != 0 && board[a][0] == board[a][1] && board[a][0] == board[a][2] ) { return WIN; } } // check for win in columns for (int a = 0; a < 3; ++a ) { if ( board[0][a] != 0 && board[0][a] == board[1][a] && board[0][a] == board[2][a] ) { return WIN; } } // check for a completed game for ( int r = 0; r < 3; ++r ) { for ( int c = 0; c < 3; ++c ) { if ( board[r][c] == 0 ) { return CONTINUE; // game is not finished } } } return DRAW; // game is a draw } void start_game() { current = player_1; } void print_board() { coutRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.