In this lab you will code the game of Tic-Tac-Toe that allows the user to play against the computer. |
#include <string> #include <vector> #include <algorithm> using namespace std; //GLOBAL CONSTANTS const char X = 'X'; const char O = 'O'; const char EMPTY = ' '; const char TIE = 'T'; const char GAME_NOT_OVER = 'N'; //FUNCTION PROTOTYPES void instructions(); void DrawTheBoard(const vector char Result(const vector int userMove(const vector int computerMove(vector int main(){ //CONSTRUCT A VECTOR BOARD AND FILL EACH CELL WITH A BLANK. vector instructions(); //DISPLAY BASIC INSTRUCTIONS //CONSTRUCT THE PLAYERS IN THE GAME char user; char computer; int move; //ASK USER IF THEY WANT TO GO FIRST. ASSIGN X TO THE PLAYER THAT GOES FIRST. cout << "X goes first. Would you like to go first? yY "; char response; cin >> response; if (response == 'y' || response == 'Y') {
computer = O; else {
computer = 'X'; //THE FIRST TURN GOES TO THE X. char whoseTurn = X; DrawTheBoard(board); //PLAY THE GAME UNTIL SOMEONE WINS OR THE PLAYERS TIE. while (Result(board) == GAME_NOT_OVER ){
board[move] = user; else{
board[move] = computer; DrawTheBoard(board); whoseTurn = (whoseTurn ==X ? O:X); //DETERMINE WHO IS THE WINNER char Win = Result(board); if (Win == computer)
void instructions(){
cout << "Make your move by entering a number, 0 - 8, to specify the board position shown below\n\n"; cout << " 0 | 1 | 2"<< endl; cout << " ---------"<< endl; cout << " 3 | 4 | 5"<< endl; cout << " ---------"<< endl; cout << " 6 | 7 | 8\n"<< endl; void DrawTheBoard(const vector
cout << "\n\t" << "---------"; cout << "\n\t" << board[3] << " | " << board[4] << " | " << board[5]; cout << "\n\t" << "---------"; cout << "\n\t" << board[6] << " | " << board[7] << " | " << board[8]; cout << "\n\n"; char Result(const vector } int userMove(const vector
do {
cin >> move; if (board[move] != EMPTY){
move = -1; return move; int computerMove(vector } |