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 100 101 102 103 104
|
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void printBoard();
void checkMark();
void moveInput();
void checkWin();
void getPlayerInput();
char grid[3][3] = {' ',' ',' ',' ',' ',' ',' ',' ',' '};
int playerTurn = 1;
char playerMark;
bool isMoveValid;
bool isGameWon = false;
int main()
{
do
{
printBoard();
checkWin();
checkMark();
getPlayerInput();
system("CLS");
}while (isGameWon != true);
return 0;
}
void printBoard()
{
cout << endl;
cout << " " << setw(2) << grid[0][0] << "|" << setw(2) << grid[0][1] << "|" << setw(2) << grid[0][2] << endl;
cout << " " << "--+--+--"<< endl;
cout << " " << setw(2) << grid[1][0] << "|" << setw(2) << grid[1][1] << "|" << setw(2) << grid[1][2] << endl;
cout << " " << "--+--+--"<< endl;
cout << " " << setw(2) << grid[2][0] << "|" << setw(2) << grid[2][1] << "|" << setw(2) << grid[2][2] << endl;
cout << endl;
}
void checkMark()
{
if (playerTurn == 1)
playerMark = 'X';
else
playerMark = 'O';
}
void getPlayerInput()
{
cout << "Player" << playerTurn << "'s turn (enter x coordinate then press enter, follow b):" << endl;
// Loop until we get a valid move
do
{
int x,y;
bool isMoveValid;
string playerInput;
getline(cin,playerInput);
x = (playerInput.at(0)) - 1);
y = (playerInput.at(2)) - 1);
// Check for a valid move
if (grid[x][y] = ' ')
{
grid[x][y] = playerMark;
isMoveValid = true;
}
else
{
cout << "Invalid input, please use x,y format." << endl;
isMoveValid = false;
}
}while (isMoveValid == false);
}
void checkWin()
{
if (grid[0][0] == grid[0][1] == grid[0][2])
isGameWon = true;
if (grid[0][0] == grid[1][0] == grid[2][0])
isGameWon = true;
if (grid[0][0] == grid[1][1] == grid [2][2])
isGameWon = true;
if (grid[0][1] == grid[1][1] == grid [2][1])
isGameWon = true;
if (grid[0][2] == grid[1][1] == grid [2][0])
isGameWon = true;
if (grid[0][2] == grid[1][2] == grid [2][2])
isGameWon = true;
if (grid[1][0] == grid[1][1] == grid [1][2])
isGameWon = true;
if (grid[2][0] == grid[2][1] == grid [2][2])
isGameWon = true;
else
isGameWon = false;
}
| |