Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- const int D = 3;
- // Function prototypes
- void clearScreen();
- string getCol(string board[D][D], int c);
- string getRow(string board[D][D], int r);
- string getDiag(string board[D][D], int d);
- bool isWinState(string state);
- bool isGameOver(string board[D][D]);
- void printBoard(string board[D][D]);
- void updateBoard(string board[D][D], int pos, string xo);
- // Main function
- int main()
- {
- string board[D][D] = {{"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}};
- int position, turn=0;
- string xo;
- while(!isGameOver(board) && turn < 9)
- {
- clearScreen();
- printBoard (board);
- xo = "x";
- if (turn%2 == 1) xo = "o";
- cout << "Player " << turn%2+1 << "'s turn: ";
- cin >> position;
- position--;
- while(position > 8 || position < 0 || !isdigit(board[position/3][position%3][0]) || cin.fail())
- {
- cout << "Please enter in a valid position: ";
- cin >> position;
- position --;
- }
- board[position/3][position%3] = xo;
- turn ++;
- }
- clearScreen();
- printBoard (board);
- if (turn == 9)
- {
- cout << "A tie!" << endl;
- }
- else
- {
- cout << "Player " << (turn+1)%2 + 1<< " wins!" << endl;
- }
- }
- string getCol(string board[3][3], int c)
- {
- string column = "";
- for(int i=0; i < 3; i++) column = column + board[i][c];
- return column;
- }
- string getRow(string board[3][3], int r)
- {
- string row = "";
- for(int i=0; i < 3; i++) row += board[r][i];
- return row;
- }
- string getDiag(string board[3][3], int d)
- {
- string diagonal = "";
- for(int i=0; i < 3; i++) diagonal += board[i][2*d+(1-2*d)*i];
- return diagonal;
- }
- bool isWinState(string state)
- {
- return state[0]==state[1] && state[1]==state[2] && state[0] != ' ';
- }
- bool isGameOver(string board[3][3])
- {
- for(int i=0; i < 3; i++) if(isWinState(getRow(board, i)) || isWinState(getCol(board,i))) return true;
- for(int i=0; i < 2; i++) if(isWinState(getDiag(board, i))) return true;
- return false;
- }
- void printBoard(string board[D][D])
- {
- for(int i=0; i < 2; i++)
- {
- cout << " " << board[i][0] << " | " << board[i][1] << " | " << board[i][2] << endl;
- cout << "---+---+---" << endl;
- }
- cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << endl;
- }
- void updateBoard(string board[3][3], int pos, string xo)
- {
- board[pos/3][pos%3] = xo;
- }
- void clearScreen()
- {
- cout << string(100, '\n');
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement