-
tic-tac-toe diagonal
Here is the code I have. Hopefully it's self explanatory:
Code:
// Game functions
#include "game.h"
bool check::win(char icon, char board[3][3])
{
if(check::horizontal(icon, board))
return true;
else if(check::vertical(icon, board))
return true;
else if(check::diagonal(icon, board))
return true;
return false;
}
bool check::horizontal(char icon, char board[3][3])
{
int counter = 0;
for(int i = 0; i < 3; i ++)
{
for(int t = 0; t < 3; t ++)
{
if(board[i][t] == icon)
counter ++;
}
if(counter == 3)
return true;
counter = 0;
}
return false;
}
bool check::vertical(char icon, char board[3][3])
{
int counter = 0;
for(int i = 0; i < 3; i ++)
{
for(int t = 0; t < 7; t += 3)
{
if(board[i][t] == icon)
counter ++;
}
if(counter == 3)
return true;
counter = 0;
}
return false;
}
bool check::diagonal(char icon, char board[3][3])
{
int counter = 0;
return false;
}
I'm stumped on how I could use for loops to check for a diagonal win. Any suggestions?
-
bool check::horizontal(char icon, char board[3][3])
{
int counter = 0;
for(int i = 0; i < 3; i ++)
{
if(board[i][i] == icon)
counter ++;
if(counter == 3)
return true;
counter = 0;
}
return false;
}
-
Ahhh, that'll work. Thanks! :D
-
_
Code:
int c = 0;
for (int x = 0; x < width_of_item; ++x) {
if (board[x][x] == icon)
++c;
}
if (c == 3)
/* ... */
If you use the same incrementing value for both x and y then you're moving diagonally in 2 dimensions.
-
Code:
bool check::diagonal(char icon, char board[3][3])
{
if[board[2][2] == icon)
{
if(board[1][1] == icon && board[3][1] == icon || board[1][3] = icon && board[3][1] )
{
return true;
}
else
{
return false;
}
}
return false;
}
i don't have an other idea...
the other ideas don't work correctly because
it doesn't do when you have
[ ] [ ] [x]
[ ] [x ] [ ]
[x ] [ ] [ ]
-
Thanks for the help, guys. I ended up doing this:
Code:
bool check::diagonal(char icon, char board[3][3])
{
int counter = 0;
for(int i = 0; i < 3; i ++)
{
if(board[i][i] == icon)
counter ++;
}
if(counter == 3)
return true;
counter = 0;
int t;
for(i = 0, t = 2; i > 3, t >= 0; i ++, t --)
{
if(board[t][i] == icon)
counter ++;
}
if(counter == 3)
return true;
return false;
}