I recently made this tic tac toe game and im happy that i finished it. It works like a charm, but now i want to improve on it cause it does have problems. One is when it prompts the user to enter a number, if the user enters anything but a number it acts all crazy. Can you help me figure out why? i thought my default in my switch-case would handle it but it didnt. it probably has to do something with the loop but not sure. Another problem is, when one user enters 3 for example and the board changes it to X, if the other player enters a 3, it then changes it to an O. I want it to use my default in my switch-case when that happens but it doesnt. Please help. Would like to learn whats going on.
cout << "Player " << player << " Choose a number on the board." << endl;
cin >> number;
switch (number)
{
case 1:
array [0][0] = letter_mark;
break;
// ...
default:
cout << "You did not choose a correct number. Try Again." << endl;
--player;
--i;
break;
}
It should test to make sure they entered a valid number. You should also get an error when they select a position that's already been selected, as in it overrides the previous. Also, what is the purpose of --player and --i?
To make sure the user can't override another user, before entering the players X or O on the board, make sure there isn't already a value there. Also, why are you using a 2D array, but using a switch case for values 1 - 9? That makes no sense to me. Keep it simple on yourself.
That makes sense, but you're asking for one value from the user, not two. I made a tic tac toe game a while back, and used a 2D array for it, but my user input was a lot different than yours. What I'd suggest is that you do something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
player = (player % 2) ? 1:2;
char letter_mark = (player == 1) ? 'X' : 'O';
int number;
do {
cout << "Player " << player << " Choose a number on the board." << endl;
cin >> number;
} while (number < 1 || number > 9);
// Checks to make sure it's a valid move...
if (array[number / 3][number % 3] != 'X' && array[number / 3][number % 3] != 'O')
array[number / 3][number % 3] = letter_mark;
else {
// User Selected an invalid spot...
cout << "You did not choose a correct number. Try Again." << endl;
--player;
--i;
}
Ok, your code gave me an idea on how to put my array in the loop using if-else statements instead of switch-case, and it now WORKS!!!! thank you. When using your if statment, it wouldnt put the X or the O in the number i pressed, but everything else worked fine. Here is what I did