Hello hayabusaruler,
There is no reason to rewrite the "havewinner" function just use it correctly.
As an example and using
Ganado's suggestion:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int havewinner()
{
for (int i = 0; i < 3; i++)
{
if (grid[i][0] == "X" && grid[i][1] == "X" && grid[i][2] == "X")
{
return 1;
}
else if (grid[i][0] == "0" && grid[i][1] == "0" && grid[i][2] == "0")
{
return 2;
}
}
return 0; // <--- At the end of the function when there is no winner.
| |
Remove the else statements. This way if nothing returns a 1 or 2 the last thing the function will so is return (0) zero to show there is no winner.
You have a 2D array of strings. Unusual, but it works. Here the for loop has the correct value for "i" to access the rows of the array, but accessing the individual elements of the string are off by one. The string elements are numbered 0, 1, 2 and when you get to the last check of "[i][3]" the (3) is ouside of or past the end of the string.
Then in "play" you would use:
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
|
void play()
{
bool winner{}, cont{ true };
int row1 = 0, col1 = 0, row2 = 0, col2 = 0;
//int total = 0; // <--- No longer needed.
while (cont) // <--- Can not use "continue" because it is a key word.
{
cout << "Player 1 turn" << endl;
cout << "Input row:";
cin >> row1; // <--- User types 1, 2 or 3.
//row1--; // <--- An alternative to subtracting (1) later.
cout << "Input col:";
cin >> col1; // <--- User types 1, 2 or 3.
grid[row1 - 1][col1 - 1] = "X"; // <--- Subtracts 1 from user input to access the correct element of the array.
//grid[row1][col1] = "X"; // <--- If you use line 13
//total++; // <--- No longer needed.
output();
//std::cout << " " << total << '\n'; // <--- Used for testing. Comment or remove when finished.
winner = havewinner();
if (winner) // <--- (0) means false and any number greater than (0) is considered true.
{
cout << "Winner is player " << winner << ".\n";
cont = false;
continue; // <--- Jumps to the while condition. Bypasses every down to the closing } of the while loop.
}
| |
The same concept would have to be repeated for player 2.
The last if/else if in "havewinner" checks for a win from top left to bottom right. That is 1 of 2 diagonals. You need to copy that and reverse the check from top right to bottom left.
That should get you a working program. After that there are ways to improve and shorten the code, but first I would get it working the way that you want.
Before you have to ask in the
bool winner{}, cont{ true };
. The {}s are called the uniform initializer and are available from the 2011 standards on. Empty they set "char"s to "\0", the int types to (0) zero and "double"s to "0.0". As the "cont" shows you can put something inside the {}s to give it a value other than (0) zero.
Andy