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
|
#include <iostream>
#include <cstdlib>
using namespace std;
// Global constants
const int ROWS = 3; // Number of rows
const int COLS = 3; // Number of columns
bool win = true; // Holds if game is won
// Function definitions
void showBoard(char [][COLS], int); // showBoard prototype
void p1Select (char [][COLS], int); // player 1 selection prototype
void p2Select (char [][COLS], int); // player 2 selection prototype
bool winOrTie (char [][COLS]); // win or tie selection prototype
int main()
{
char board[ROWS][COLS] = {{42,42,42},
{42,42,42},
{42,42,42}};
while (win == true)
{
showBoard(board, ROWS);
p1Select(board, ROWS);
win = winOrTie(board);
showBoard(board, ROWS);
p2Select(board, ROWS);
win = winOrTie(board);
}
cout << "game over\n";
cout << endl;
system("PAUSE");
return 0;
}
void showBoard(char array[][COLS], int ROWS)
{
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
cout << array[i][j] << " ";
}
cout << endl;
}
}
void p1Select(char array[][COLS], int ROWS)
{
int i, j;
char select = 'X';
cout << "Player 1: Select a row number and column number to place an X: ";
cin >> i >> j;
while (i > ROWS && j > COLS)
{
cout << "Row and column selection must be numbers 1-3 ";
cin >> i >> j;
}
array[i-1][j-1] = select;
}
void p2Select(char array[][COLS], int ROWS)
{
int i, j;
char select = 'O';
cout << "Player 2: Select a row number and column number to place an O: ";
cin >> i >> j;
while (i > ROWS && j > COLS)
{
cout << "Row and column selection must be numbers 1-3 ";
cin >> i >> j;
}
array[i-1][j-1] = select;
}
bool winOrTie(char array[][COLS])
{
char X, O;
if (array[0][0] == 'X' && array[0][1] == 'X' && array[0][2] == 'X')
{
cout << "Player 1 wins\n";
return false;
}
else if (array[0][0] == 'O' && array[0][1] == 'O' && array[0][2] == 'O')
{
cout << "Player 2 wins\n";
return false;
}
}
|