Question

in c++ : Problem Domain: The classic TicTacToe game alternatively place Xs and Os on a...

in c++ :

Problem Domain:

The classic TicTacToe game alternatively place Xs and Os on a 3x3 grid. The winner is the first player to place 3 consecutive marks in a horizontal, vertical or diagonal row.


Understanding the Problem:

In this assignment, you will:
1) Create a tic tac toe board data structure.
2) Check for game over.
3) Clear the tic tac toe game for each game.
4) Display the tic tac toe board to screen.
5) Simulate playing a game until the board is full.

How to play this version of the game (main.cpp flow)

The program will call the start_game function with argument O or X to indicate first player and will keep track of the next player while players take turns marking the board until the board is full. This version of the game only plays one game.

Class Specifications


TicTacToe class does not have a constructor.
Member Functions and Member(variable) Specifications
+ = public
- = private

Function/Data Member

Functionality of function or data member

+

bool game_over

No parameters
1) return check_board_full function return value

+

void start_game(string first_player)

1) First_player function argument value must be X or O
2) In function set player(private variable) to first_player function argument.
3) Call the clear_board function

+

void mark_board(int position)

1) Mark vector w position -1 equal to player
2) Call set_next_player private function

+

string get_player() const

Return the player value

+

void display_board() const

No parameters
Iterate vector of strings pegs to
Display a tic tac toe board in 3x 3 format

-

void set_next_player()

Set player. If private variable player X player is O else player is X

-

void check_board_full()

No parameters
1) return false if vector of strings pegs has available slot by checking for a “ “(space)in each element. Otherwise return true

-

void clear_board() const

No parameters
1) Set all 9 elements to a “ “ (space)

Class private Data

-

string player

Class member variable

vector of string pegs

Class member variable
1) (initialize to 9 “ “(spaces)

Implementation Files:
1) In file tic_tac_toe.h, write the class interface code.
2) In file tic_tac_toe.cpp, write the class implementation.
3) In file main.cpp, write game flow code to play the tic tac to game.

Running the program from main (write the code in main.cpp)

Main program flow(main.cpp)


1) Prompt the user for first player
2) Start the game
3) In a user-controlled loop prompt the user for a position (int type) and call the mark_board tic tac toe class member function.  

Homework Answers

Answer #1

The classic TicTacToe game alternatively place Xs and Os on a 3x3 grid. The winner is the first player to place 3 consecutive marks in a horizontal, vertical or diagonal row.

COMPILER: USED dev c++

#include <windows.h>
#include <iostream>
#include <string>
 
//--------------------------------------------------------------------------------------------------
using namespace std;
 
//--------------------------------------------------------------------------------------------------
enum players { Computer, Human, Draw, None };
const int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } };
 
//--------------------------------------------------------------------------------------------------
class ttt
{
public:
    ttt() { _p = rand() % 2; reset(); }
 
    void play()
    {
        int res = Draw;
        while( true )
        {
            drawGrid();
            while( true )
            {
                if( _p ) getHumanMove();
                else getComputerMove();
 
                drawGrid();
 
                res = checkVictory();
                if( res != None ) break;
 
                ++_p %= 2;
            }
 
            if( res == Human ) cout << "CONGRATULATIONS HUMAN --- You won!";
            else if( res == Computer ) cout << "NOT SO MUCH A SURPRISE --- I won!";
            else cout << "It's a draw!";
 
            cout << endl << endl;
 
            string r;
            cout << "Play again( Y / N )? "; cin >> r;
            if( r != "Y" && r != "y" ) return;
 
            ++_p %= 2;
            reset();
 
        }
    }
 
private:
    void reset() 
    {
        for( int x = 0; x < 9; x++ )
            _field[x] = None;
    }
 
    void drawGrid()
    {
        system( "cls" );
 
        COORD c = { 0, 2 };
        SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );
 
        cout << " 1 | 2 | 3 " << endl;
        cout << "---+---+---" << endl;
        cout << " 4 | 5 | 6 " << endl;
        cout << "---+---+---" << endl;
        cout << " 7 | 8 | 9 " << endl << endl << endl;
 
        int f = 0;
        for( int y = 0; y < 5; y += 2 )
            for( int x = 1; x < 11; x += 4 )
            {
                if( _field[f] != None )
                {
                    COORD c = { x, 2 + y };
                    SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );
                    string o = _field[f] == Computer ? "X" : "O";
                    cout << o;
                }
                f++;
            }
 
        c.Y = 9;
        SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );
    }
 
    int checkVictory()
    {
        for( int i = 0; i < 8; i++ )
        {
            if( _field[iWin[i][0]] != None &&
                _field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] )
            {
                return _field[iWin[i][0]];
            }
        }
 
        int i = 0;
        for( int f = 0; f < 9; f++ )
        {
            if( _field[f] != None )
                i++;
        }
        if( i == 9 ) return Draw;
 
        return None;
    }
 
    void getHumanMove()
    {
        int m;
        cout << "Enter your move ( 1 - 9 ) ";
        while( true )
        {
            m = 0;
            do
            { cin >> m; }
            while( m < 1 && m > 9 );
 
            if( _field[m - 1] != None )
                cout << "Invalid move. Try again!" << endl;
            else break;
        }
 
        _field[m - 1] = Human;
    }
 
    void getComputerMove()
    {
        int move = 0;
 
        do{ move = rand() % 9; }
        while( _field[move] != None );
 
        for( int i = 0; i < 8; i++ )
        {
            int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2];
 
            if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None )
            {
                move = try3;
                if( _field[try1] == Computer ) break;
            }
 
            if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None ) 
            {                   
                move = try2;
                if( _field[try1] == Computer ) break;
            }
 
            if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None )
            {
                move = try1;
                if( _field[try2] == Computer ) break;
            }
        }
        _field[move] = Computer;
 
    }
 
 
int _p;
int _field[9];
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
    srand( GetTickCount() );
 
    ttt tic;
    tic.play();
 
    return 0;
}

OUTPUT:

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Write a program that allows two players to play a game of tic-tac-toe. Use a twodimensional...
Write a program that allows two players to play a game of tic-tac-toe. Use a twodimensional char array with three rows and three columns as the game board. Each element in the array should be initialized with an asterisk (*). The program should run a loop that: • Displays the contents of the board array. • Allows player 1 to select a location on the board for an X. The program should ask the user to enter the row and...
C++ See the provided specification files. Complete the implementation for each as a separate file. void...
C++ See the provided specification files. Complete the implementation for each as a separate file. void seen(std::string); If there is already a Word object in the Words list, then the number of occurrences for this word is incremented. If there is no Word object for this word already, create a new word object with occurrence =1, and insert this object into the list of Word objects. std::string getNextWord(); Returns the next word of the list and sets the currentItem pointer...
IntNode class I am providing the IntNode class you are required to use. Place this class...
IntNode class I am providing the IntNode class you are required to use. Place this class definition within the IntList.h file exactly as is. Make sure you place it above the definition of your IntList class. Notice that you will not code an implementation file for the IntNode class. The IntNode constructor has been defined inline (within the class declaration). Do not write any other functions for the IntNode class. Use as is. struct IntNode { int data; IntNode *next;...
Getting the following errors: Error 1 error C2436: '{ctor}' : member function or nested class in...
Getting the following errors: Error 1 error C2436: '{ctor}' : member function or nested class in constructor initializer list on line 565 Error 2 error C2436: '{ctor}' : member function or nested class in constructor initializer list on line 761 I need this code to COMPILE and RUN, but I cannot get rid of this error. Please Help!! #include #include #include #include using namespace std; enum contactGroupType {// used in extPersonType FAMILY, FRIEND, BUSINESS, UNFILLED }; class addressType { private:...
In this assignment, you’ll make an inventory system for a store’s items, including produce and books....
In this assignment, you’ll make an inventory system for a store’s items, including produce and books. The starter program is an inventory system for only produce. 1. Include the price of an item by adding to the Item class the protected data member int priceInDollars that stores the price in dollars of an individual item. Write a public function SetPrice with a single int parameter prcInDllrs and returns nothing. SetPrice assigns the value of prcInDllrs to priceInDollars. Modify the AddItemToInventory...
In main.cpp, write a templated function more which takes in two variables of the same type...
In main.cpp, write a templated function more which takes in two variables of the same type and returns whichever variable is greater than (>) the other. You can and may need to add something to the food class in order for more to be able to be called properly. //food.h #ifndef _FOOD_H #define _FOOD_H #include <iostream> #include <string> using namespace std; class Food { private: string name; int quantity; public: Food(); void setName(string newName); void setQuantity(int newQuantity); string getName(); int...
Create a stadium class. The class header file content (.h file) can go in this question,...
Create a stadium class. The class header file content (.h file) can go in this question, the class implementation (.cpp file) can go in the following question, and the main.cpp content can go in the third question. static data members: starting seat number next seat number data members: stadium name name of home team current opponent seats sold (vector of seat numbers) member functions: custom constructor - take input of stadium name default constructor get next seat number (static) change...
Implement and demonstrate a disk-based buffer pool class based on the LRU buffer pool replacement strategy....
Implement and demonstrate a disk-based buffer pool class based on the LRU buffer pool replacement strategy. Disk blocks are numbered consecutively from the beginning of the file with the first block numbered as 0. Assume that blocks are 4096 bytes in size. Use the supplied C++ files to implement your LRU Buffer Pool based on the instructions below. • Implement a BufferBlock class using the supplied BufferBlockADT.h o Your Buffer Block must inherit BufferBlockADT or you will not get credit...
In C++ Employee Class Write a class named Employee (see definition below), create an array of...
In C++ Employee Class Write a class named Employee (see definition below), create an array of Employee objects, and process the array using three functions. In main create an array of 100 Employee objects using the default constructor. The program will repeatedly execute four menu items selected by the user, in main: 1) in a function, store in the array of Employee objects the user-entered data shown below (but program to allow an unknown number of objects to be stored,...
write a c++ program A class called car (as shown in the class diagram) contains: o...
write a c++ program A class called car (as shown in the class diagram) contains: o Four private variables: carId (int), carType (String), carSpeed (int) and numOfCars (int). numOfCars is a static counter that should be  Incremented whenever a new Car object is created.  Decremented whenever a Car object is destructed. o Two constructors (parametrized and copy constructor) and one destructor. o Getters and setters for the Car type, ID, and speed. And static getter function for numOfCars....