1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
//This program is made to play a two player game of Tic Tac Toe.
//This program does not keep score or stats.
#include <iostream>
using namespace std;
// Global variables
const int ROW = 3;
const int COL = 3;
//Function Prototypes
void displayBoard(char[][COL], int, int);
void gameBoard(char[][COL], int, int);
bool gameEnd(char[][COL], int, int);
int main()
{
char board[ROW][COL];
int row, col;
char player = 'X';
gameBoard(board, ROW, COL);
displayBoard(board, ROW, COL);
cout << "Let's play Tic Tac Toe!\n";
cout << "Player one will be X's and player two will be O's.\n";
do {
cout << "Player " << player << endl;
do {
cout << "Enter row: ";
cin >> row;
cout << "Enter column: ";
cin >> col;
} while (board[row][col] != ' ');
board[row][col] = player;
displayBoard(board, ROW, COL);
if (player == 'X')
player = 'O';
else
player = 'X';
} while (!gameEnd(board, ROW, COL));
cout << "Game over!" << endl;
}
void gameBoard(char space[][COL], int rowsize, int colsize)
{
for (int row = 0; row < rowsize; row++)
for (int col = 0; col < colsize; col++)
space[row][col] = '*';
}
void displayBoard(char space[][COL], int rowsize, int colsize)
{
for (int row = 0; row < rowsize; row++)
{
cout << row;
for (int col = 0; col < colsize; col++)
cout << "\t" << space[row][col];
cout << endl;
}
for (int col = 0; col < colsize; col++)
cout << "\t" << col;
cout << endl;
}
bool gameEnd(char space[][COL], int rowsize, int colsize)
{
int notUsed = 0;
int Xs;
int Os;
// This section is to check for a tie.
for (int row = 0; row < rowsize; row++)
for (int col = 0; col < colsize; col++)
if (space[row][col] == ' ') notUsed++;
if (notUsed == 0)
return true;
// This section is to check each row for winning line.
for (int row = 0; row < rowsize; row++)
{
Xs = 0;
Os = 0;
for (int col = 0; col < colsize; col++)
{
if (space[row][col] == 'X')
Xs++;
else if (space[row][col] == 'O')
Os++;
}
if (Xs == colsize || Os == colsize)
return true;
}
// This section is to check each column for winning line.
for (int col = 0; col < colsize; col++)
{
Xs = 0;
Os = 0;
for (int row = 0; row < rowsize; row++)
{
if (space[row][col] == 'X')
Xs++;
else if (space[row][col] == 'O')
Os++;
}
if (Xs == colsize || Os == colsize)
return true;
}
return false;
}
|