Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- char board[3][3] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'} }; //stores the values on the board.
- char turn = 'X'; //determines whether it is "X"'s turn or "O"'s turn.
- int choice; //used for user input.
- int fullCheck = 0; //checks how many spaces are filled on the board. When this value is equal to 9, the board is full, so the program announces a tie and terminates the program.
- bool isOver = false; //a boolean for whether the game is over or not. Once this value is true, the program terminates.
- void switchTurn()
- {
- if (turn == 'X')
- {
- turn = 'O';
- }
- else
- {
- turn = 'X';
- }
- }
- void drawBoard()
- {
- for (int horizontal = 0; horizontal < 3; ++horizontal)
- {
- cout << "|";
- for (int vertical = 0; vertical < 3; ++vertical)
- {
- cout << board[horizontal][vertical] << "|";
- }
- if (horizontal < 2)
- {
- cout << "\n|-+-+-|\n";
- }
- }
- }
- void translateChoice()
- {
- int rowPick = 0;
- int columnPick = 0;
- choice -= 1;
- while (choice > 2)
- {
- rowPick += 1;
- choice -= 3;
- }
- columnPick = choice;
- if (board[rowPick][columnPick] != 'X' && board[rowPick][columnPick] != 'O' && rowPick <= 2)
- {
- board[rowPick][columnPick] = turn;
- switchTurn();
- fullCheck += 1;
- }
- else
- {
- cout << "Sorry, that square is taken. Try again";
- }
- }
- void winProcedure()
- {
- switchTurn();
- drawBoard();
- cout << "\n\nyou win, " << turn << "!!\n\n";
- isOver = true;
- }
- void winCheck()
- {
- if ((board[0][0] == board[1][1] && board[1][1] == board[2][2]) || (board[2][0] == board[1][1] && board[1][1] == board[0][2]))
- {
- winProcedure();
- }
- for (int i = 0; i < 3; ++i)
- {
- if ((board[i][0] == board[i][1] && board[i][1] == board[i][2]) || (board[0][i] == board[1][i] && board[1][i] == board[2][i]))
- {
- winProcedure();
- }
- }
- }
- int main()
- {
- cout << "Welcome to Tic Tac Toe!\n\n";
- while (isOver == false)
- {
- drawBoard();
- cout << "\n\nPick your square, " << turn << "\n\nChoice: ";
- cin >> choice;
- system("CLS");
- translateChoice();
- cout << "\n\n";
- winCheck();
- if (fullCheck == 9 && isOver == false)
- {
- cout << "It's a tie!\n\n";
- isOver = true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement