Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <ctime>
- using namespace std;
- char Board[9];
- void showBoard();
- bool moveIsValid(int m);
- int whoWon();
- int
- main()
- {
- srand(time(NULL));
- string Player_1_Name;
- string Player_2_Name;
- int Whose_Turn = 1;
- int Move;
- int Total_Moves = 0;
- Board[0] = '0';
- Board[1] = '1';
- Board[2] = '2';
- Board[3] = '3';
- Board[4] = '4';
- Board[5] = '5';
- Board[6] = '6';
- Board[7] = '7';
- Board[8] = '8';
- cout << "Player 1: Please enter your name." << endl;
- cin >> Player_1_Name;
- cout << "Player 2: Computer." << endl;
- cin >> Player_2_Name;
- while (whoWon() == 0 && Total_Moves < 9) {
- do {
- if (Whose_Turn == 1) {
- showBoard();
- cout << Player_1_Name << ": It's your turn." << endl;
- cout << "Enter the number of the spot where you'd like to move." << endl;
- cin >> Move;
- } else {
- Move = rand() % 9;
- }
- } while (moveIsValid(Move) != true);
- Total_Moves++;
- switch (Whose_Turn) {
- case (1):
- Board[Move] = 'x';
- Whose_Turn = 2;
- break;
- case (2):
- Board[Move] = 'o';
- Whose_Turn = 1;
- }
- }
- showBoard();
- switch (whoWon()) {
- case 1:
- cout << Player_1_Name << " has won the game!" << endl;
- break;
- case 2:
- cout << Player_2_Name << " has won the game!" << endl;
- break;
- default:
- cout << "It's a tie game!" << endl;
- break;
- }
- system("PAUSE");
- }
- void
- showBoard()
- {
- cout << endl;
- cout << Board[0] << " | " << Board[1] << " | " << Board[2] << endl;
- cout << "--+---+--" << endl;
- cout << Board[3] << " | " << Board[4] << " | " << Board[5] << endl;
- cout << "--+---+--" << endl;
- cout << Board[6] << " | " << Board[7] << " | " << Board[8] << endl;
- cout << endl;
- }
- bool
- moveIsValid(int m)
- {
- return (Board[m] != 'x' && Board[m] != 'o');
- }
- int charToWinner(char ch)
- {
- if (ch == 'x') {
- return 1;
- } else {
- return 2;
- }
- }
- int
- whoWon()
- {
- if (Board[0] == Board[1] && Board[1] == Board[2]) {
- return charToWinner(Board[0]);
- }
- if (Board[3] == Board[4] && Board[4] == Board[5]) {
- return charToWinner(Board[3]);
- }
- if (Board[6] == Board[7] && Board[7] == Board[8]) {
- return charToWinner(Board[6]);
- }
- if (Board[0] == Board[3] && Board[3] == Board[6]) {
- return charToWinner(Board[0]);
- }
- if (Board[1] == Board[4] && Board[4] == Board[7]) {
- return charToWinner(Board[1]);
- }
- if (Board[2] == Board[5] && Board[5] == Board[8]) {
- return charToWinner(Board[2]);
- }
- if (Board[0] == Board[4] && Board[4] == Board[8]) {
- return charToWinner(Board[0]);
- }
- if (Board[2] == Board[4] && Board[4] == Board[6]) {
- return charToWinner(Board[2]);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement