Search code examples
carraystetris

Why is my 3d array reversed?


I have a 3d array of ints stored in a struct which represents a tetris block:

typedef struct
{
  int orientations[4][4][4];
  dimension dimensions[4];
  int i;
  int x;
  int y;
}block;

orientations is filled with every possible position for the block and dimension is a struct that provides information for collision checking:

typedef struct 
{
int left, right, bottom;
}dimension;

each orientation and dimension should be linked by the block's i value. For some reason orientations (but not dimensions) seems to be reversed. Does anybody know why this is?

here is how I assign values to dimensions:

block* shape = malloc(sizeof(block));
shape->dimensions[0].left = 0;
shape->dimensions[0].right = 3;
shape->dimensions[0].bottom = 1;
shape->dimensions[1].left = 2;
shape->dimensions[1].right = 2;
shape->dimensions[1].bottom = 3;
shape->dimensions[2].left = 0;
shape->dimensions[2].right = 3;
shape->dimensions[2].bottom = 2;
shape->dimensions[3].left = 1;
shape->dimensions[3].right = 1;
shape->dimensions[3].bottom = 3;

and orientations:

int first[4][4] = {{0,0,0,0}, {2,2,2,2}, {0,0,0,0}, {0,0,0,0}};
int second[4][4] = {{0,0,2,0},{0,0,2,0},{0,0,2,0},{0,0,2,0}};
int third[4][4] = {{0,0,0,0},{0,0,0,0},{2,2,2,2},{0,0,0,0}};
int fourth[4][4] = {{0,2,0,0},{0,2,0,0},{0,2,0,0},{0,2,0,0}};
for (i = 0; i < 4; i++)
{
  for (j = 0; j < 4; j++)
  {
    shape->orientations[0][i][j] = first[i][j];
  }
}
for (i = 0; i < 4; i++)
{
  for (j = 0; j < 4; j++)
  {
    shape->orientations[1][i][j] = second[i][j];
  }
}
for (i = 0; i < 4; i++)
{
  for (j = 0; j < 4; j++)
  {
    shape->orientations[2][i][j] = third[i][j];
  }
}
for (i = 0; i < 4; i++)
{
  for (j = 0; j < 4; j++)
  {
    shape->orientations[3][i][j] = fourth[i][j];
  }
}

here is how I'm accessing the array:

shape->orientations[current->i][i][j]

when I attempt to access shape->orientations[3] it returns the values I set to shape->orientations[0] earlier. Any help would be greatly appreciated, thanks in advance.


Solution

  • The reason is that your array is indexed [orientation][row][column], but you are interpreting it as [orientation][x][y] when you should be interpreting it as [orientation][y][x]. So you are getting a pattern with the x and y swapped, which appears as if it has been rotated to a different orientation (actually it's equivalent to a rotation and a flip).