C++ Write a class called Board that represents a tic-tac-toe board. It should ha
ID: 3730283 • Letter: C
Question
C++
Write a class called Board that represents a tic-tac-toe board. It should have a 3x3 array of chars ('x', 'o', or a space, where a space would represent an empty square) as a data member, which will store the locations of the players' moves. It should have a default constructor that initializes the 3x3 array to being empty (each element set to a space character). It should have a method called makeMove that takes two ints and a char (either 'x' or 'o') as parameters, representing the x and y coordinates of the move (see the example below) and which player's turn it is. If that location is unoccupied, makeMove should record the move and return true. If that location is already occupied, makeMove should just return false. There should be a method called gameState that takes no parameters and returns one of the four following values: X_WON, O_WON, DRAW, or UNFINISHED - use an enum for this, not strings (the enum definition should go in Board.hpp, before the class, not inside it). [Optional: write a method called print, which just prints out the current board to the screen - this is not required, but will very likely be useful for debugging.]
Write a class called T3Reader that uses the Board class to re-run a game of TicTacToe from moves that it reads from a text file. This class will have a field for a Board object and a field to keep track of which player's turn it is. It should have a constructor that takes a char parameter that specifies whether 'x' or 'o' should have the first move. It should have a method called readGameFile that takes a string parameter that gives the name of the game file. The readGameFile method should keep looping, reading a move from the file, and sending it to the board (with makeMove). The readGameFile method should return false if any of the moves is for a square that was already occupied, or if there are still additional moves in the file after the game has finished. Otherwise it should return true. Make sure you close the input file in every case.
Here's an example of the format for the text file:
and so on. Which coordinate is the row and which is the column doesn't matter as long as you're consistent.
The files must be named: Board.cpp, Board.hpp, T3Reader.cpp, T3Reader.hpp.
Explanation / Answer
Solution:
code:
//main1.cpp
#include "Board.hpp"
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
void printGameState(State gameState);
int main()
{
// Initialize a new board
Board::Board myBoard;
// Print the board to make sure it's empty
myBoard.printBoard();
// Print the game state
printGameState(myBoard.gameState());
// Make a move
myBoard.makeMove(0, 0, 'x');
// Print the board and game state again
myBoard.printBoard();
printGameState(myBoard.gameState());
return 0;
}
void printGameState(State gameState)
{
switch (gameState)
{
case 0:
cout << "Game State: X_WON" << endl;
break;
case 1:
cout << "Game State: O_WON" << endl;
break;
case 2:
cout << "Game State: DRAW" << endl;
break;
case 3:
cout << "Game State: UNFINISHED" << endl;
break;
}
}
----------------------------------------------------------------------------------------------------------------
//main2.cpp
#include "T3Reader.hpp"
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main()
{
// Initialize a new reader object, and print the output
cout << T3Reader::T3Reader newGame ("input.txt") << endl;
return 0;
}
-------------------------------------------------------------------------------------------------------------------
//T3Reader.cpp
#include "T3Reader.hpp"
#include <iostream>
#include <fstream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
T3Reader::T3Reader(char firstTurn)
{
nextTurn = firstTurn;
}
bool T3Reader::readGameFile(string fileName)
{
// Initialize variables to store the coords and results for each move
int xCoord, yCoord;
bool moveResult;
// Open the input file
std::ifstream inFile(fileName);
// Loop until the end of the file
while (inFile >> xCoord >> yCoord)
{
// If the game is finished, return false
if (gameBoard.gameState() != 3)
{
// Make sure to close the file!
inFile.close();
return false;
}
moveResult = gameBoard.makeMove(xCoord, yCoord, nextTurn);
// Return false if the move failed
if (moveResult == false)
{
// Make sure to close the file!
inFile.close();
return false;
}
// Toggle the next player
if (nextTurn == 'x')
{
nextTurn = 'o';
}
else
{
nextTurn = 'x';
}
}
inFile.close();
return true;
}
------------------------------------------------------------------------------------------------
//T3Reader.hpp
#include "Board.hpp"
#include <string>
#ifndef T3READER_HPP
#define T3READER_HPP
class T3Reader
{
private:
// Board object for the game
Board::Board gameBoard;
// Which player goes next
char nextTurn;
public:
// Default constructor takes a char to determine which player goes first
T3Reader(char firstTurn);
// readGameFile reads the file containing a list of moves and calls Board::makeMove to make successive moves
bool readGameFile(std::string fileName);
};
#endif
---------------------------------------------------------------------------------------------
//Board.cpp
#include "Board.hpp"
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
Board::Board()
{
// Set each cell of the gameBoard array to empty
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
gameBoard[i][j] = 'o';
}
}
}
bool Board::makeMove(int xCoord, int yCoord, char gamePiece)
{
// Reminder: Array[row][col]
// If the space is already taken
if (gameBoard[yCoord][xCoord] != '=')
{
// Illegal move
return false;
}
// Otherwise, record the move
gameBoard[yCoord][xCoord] = gamePiece;
// And return true
return true;
}
State Board::gameState()
{
// usedSpaces counts the number of non-empty spaces
int usedSpaces = 0;
// Run through each space on the board
for (int y = 0; y < 3; y++)
{
for (int x = 0; x < 3; x++)
{
// Count the non-empty spaces
if (gameBoard[y][x] != '=')
{
usedSpaces++;
}
// Check for an 'o' win
if (gameBoard[y][x] == 'o')
{
// Check adjacents vertically
if (gameBoard[y+1][x] == 'o' && gameBoard[y-1][x] == 'o')
{
return O_WON;
}
// Check adjacents horizontally
else if (gameBoard[y][x+1] == 'o' && gameBoard[y][x-1] == 'o')
{
return O_WON;
}
// Check adjacents on the diagonals
else if (gameBoard[y+1][x-1] == 'o' && gameBoard[y-1][x+1] == 'o')
{
return O_WON;
}
else if (gameBoard[y+1][x+1] == 'o' && gameBoard[y-1][x-1] == 'o')
{
return O_WON;
}
}
// Check for an 'x' win
if (gameBoard[y][x] == 'x')
{
// Check adjacents vertically
if (gameBoard[y+1][x] == 'x' && gameBoard[y-1][x] == 'x')
{
return X_WON;
}
// Check adjacents horizontally
else if (gameBoard[y][x+1] == 'x' && gameBoard[y][x-1] == 'x')
{
return X_WON;
}
// Check adjacents on the diagonals
else if (gameBoard[y+1][x-1] == 'x' && gameBoard[y-1][x+1] == 'x')
{
return X_WON;
}
else if (gameBoard[y+1][x+1] == 'x' && gameBoard[y-1][x-1] == 'x')
{
return X_WON;
}
}
}
}
// While there is no winner
// If all the spaces are full, it's a draw
if (usedSpaces == 9)
{
return DRAW;
}
return UNFINISHED;
}
// printBoard is an accessor for debugging
void Board::printBoard()
{
// Reminder: Array[y][x]
// Print the array upside-down, so it makes sense graphically
for (int y = 2; y >= 0; y--)
{
cout << "| ";
for (int x = 0; x < 3; x++)
{
cout << gameBoard[y][x] << " | ";
}
cout << endl;
}
}
---------------------------------------------------------------------------------------------
//Board.hpp
#include <string>
using std::string;
#ifndef BOARD_HPP
#define BOARD_HPP
// Enumerated data type for the game state. Describes which player, if any, has won the game, or if the game ended in a draw.
enum State {X_WON, O_WON, DRAW, UNFINISHED};
// Board class
class Board
{
private:
char gameBoard[3][3];
public:
// The default constructor sets all board spaces to an empty (space) character
Board();
// makeMove takes int coordinates and a char representing a game piece and changes the corresponding space on the board
bool makeMove(int xCoord, int yCoord, char gamePiece);
// gameState determines the state of the game--if either player has won, if the game is a draw, or if the game is still in progress
State gameState();
// printBoard is for debugging
void printBoard();
};
#endif
I hope this helps if you find any problem. Please comment below. Don't forget to give a thumbs up if you liked it. :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.