-
2D diagonal counter
Hi,
My program has a 2-dimensional grid. Basically it's a grid of 19x19 and bunch of '0's. I want to be able to count diagonally when I insert 'x's that are diagonal... such as...
0000x
000x0
00x00
0x000
x0000
I was able to figure out the horizontal counters and vertical counters, but I seem to be having trouble making a loop of counter for diagonal 5-in-a-row of 'x's.
Thanks.
-
Can you explain the problem better? Depending on the row and column direction, to insert the 'x's, you could do something like:
Code:
if (i+4 < 19 && j-4 < 19)
{
grid[i][j] = 'x';
grid[i+1][j-1] = 'x';
grid[i+2][j-2] = 'x';
grid[i+3][j-3] = 'x';
grid[i+4][j-4] = 'x';
}
else
{
//Outside grid
}
And there might be four different directions the diagonal could take.
-
Sorry that I wasn't clear....
Okay basically, I'm making the game gomoku(five-in-a-row). So basically, it's a game where the player tries to get his pieces "5-in-a-row" in order to win. Kind of like connect four.
I was able to make conditions for horizontal and vertical, but for both diagonals, I was having a hard time actually trying to make a condition.
Hopefully that cleared things up a bit.
-
something like
Code:
no_of_rows;
no_of_column;
int_tmp = no_of_column;
for(i=1; i<=no_of_row;i++)
{
if(g[i][int_tmp] == 'x')
{ .....Execution....}
int_tmp--;
if(int_tmp==1)
break;
}
I dont..but may be helpful
-
Ok, so you're trying to check for 5-in-a-row diagonally in any direction? I would probably do something like the following:
Code:
int y, x, win;
win = 0;
for (y=0; y<19; y++)
{
for (x=0; x<19; x++)
{
if (grid[y][x] == 'x')
{
ydir = -1;
xdir = -1;
if (five_in_a_row(grid, y, x, ydir, xdir))
{
win = 1;
break;
}
ydir = -1;
xdir = 1;
if (five_in_a_row(grid, y, x, ydir, xdir))
{
win = 1;
break;
}
ydir = 1;
xdir = -1;
if (five_in_a_row(grid, y, x, ydir, xdir))
{
win = 1;
break;
}
ydir = 1;
xdir = 1;
if (five_in_a_row(grid, y, x, ydir, xdir))
{
win = 1;
break;
}
}
}
}
if (win == 1)
{
printf("You win!\n");
}
.
.
/* Function five_in_a_row */
int five_in_a_row(char grid[19][19], int y, int x, int ydir, int xdir)
{
int count;
for (count=0, count<4; count++)
{
y += ydir;
x += xdir;
if (y>=0 && y<19 && x>=0 && x<19 && grid[y][x] == 'x')
{
continue;
}
else
{
return 0;
}
}
return 1;
}
You could also use function five_in_a_row() to check for wins horizontally and vertically by setting xdir or ydir to 0. And you could make an array of xdir and ydir to cover all the directions, thereby making the code shorter. There's probably many different ways to do this. This is just one idea.