Take a deep breath. You're actually very close to having this right.
Line 76 is wrong. Due to order of operations, the compiler interprets this as:
else if ((board[0] =='X') or ('O' && board[1] =='X') or ('O' && board[2] =='X') or ...
Since 'O' is not zero, it's always interpretted as true, so it can be somplified to:
else if ((board[0] =='X') or ( board[1] =='X') or (board[2] =='X') or ...
What you really want to know is if any of the squares are '.':
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
bool
isTie()
{
if (XsWin())
return false;
else if (OsWin())
return false;
else {
for (int i=0; i<9; ++i) {
if (board[i] == '.') return false;
}
return true;
}
}
|
For the main program, you have to get a move, check for a winner, and check for a tie. Then get the next move and do the same:
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
|
int
main()
{
while (true) {
// Print the board
cout << "Xs til Death" << endl;
printBoard();
// Get X's move
cout << "Play your Position 1-9: ";
int userChoice;
do {
cin >> userChoice;
userChoice--;
} while (!isValidChoice(userChoice));
board[userChoice] = 'X';
// Print the board
printBoard();
if (XsWin()) {
cout << "X wins!\n";
break;
} else if (isTie()) {
cout << "Tie game\n";
break;
}
// Get O's move
cout << "Play your Position 1-9: ";
int user2Choice;
do {
cin >> user2Choice;
user2Choice--;
} while (!isValidChoice(user2Choice));
board[user2Choice] = 'O';
// Print the board
printBoard();
if (OsWin()) {
cout << "O wins!\n";
break;
} else if (isTie()) {
cout << "Tie game\n";
break;
}
}
}
|
This code works but it's inefficient. There's lots of duplication. Get the program working, save the file and then consider this:
It would be better to keep a variable that represents the current player and then have each pass through the loop do one player's move:
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
|
int
main()
{
char player = 'X';
while (true) {
// Print the board
printBoard();
// Get move
cout << player << "'s move Position 1-9: ";
int userChoice;
do {
cin >> userChoice;
userChoice--;
} while (!isValidChoice(userChoice));
board[userChoice] = player;
if (Wins(player)) {
cout << player << " wins!\n";
break;
} else if (isTie()) {
cout << "Tie game.\n";
break;
}
// switch players
if (player == 'X') {
player = 'O';
} else {
player = 'X';
}
}
// Show the final board
printBoard();
}
|
Can you change the rest of the code so it works with this main()?