I've got this sample code below. I understand cells is being made in a 1 dimensional manner, since the compiler stores 2d arrays in memory row-by-row in 1d. What I don't understand/can't visualize is how to access elements or change positions.
I know
board->cells[i (20 * (10 - 1))] = FLAG_WALL;
is used to set flags for the bottom most row. From the format it looks to be using a formula but I am unsure of what it is. The formula also seems to change for the right and left edges. (board->cells[i * 20 20 - 1] = FLAG_WALL;
)Looking at the line
board->cells[20 * 2 2] = FLAG_SNAKE;
it seems cell[42] is where the snake flag is spawned. What would the arithmetic look like to shift its position by 1 cell up, down, right, left? When imagining cell[42] as a part of a 1d array in memory I can't figure out the arithmetic nor the resulting cell number after a shift such as 'up'.
board_init_status_t initialize_default_board(board_t* board) {
board->width = 20;
board->height = 10;
board->cells = calloc(20 * 10, sizeof(int));
// Set edge cells!
// Top and bottom edges:
for (int i = 0; i < 20; i) {
board->cells[i] = FLAG_WALL;
board->cells[i (20 * (10 - 1))] = FLAG_WALL;
}
// Left and right edges:
for (int i = 0; i < 10; i) {
board->cells[i * 20] = FLAG_WALL;
board->cells[i * 20 20 - 1] = FLAG_WALL;
}
// Add snake
board->cells[20 * 2 2] = FLAG_SNAKE;
return INIT_SUCCESS;
}
CodePudding user response:
Think of the 1d array as a 2d one, the beginning of the last row would be at the position
width * (height - 1)
and the last cell of the last row atwidth * height
almost the same logic goes for the sides.board->cells[20 * 2 2] = FLAG_SNAKE;
means it goes at the 2nd row in position 2. Or in (x;y) coordinates (2, 2). It's pure math. If you want to move in a 1d array like in a 2d one just multiply the length of one line by the index of the row you want to go (let's call ity
) and then addx
to reach thex
cell.
board_init_status_t initialize_default_board(board_t* board) {
board->width = 20;
board->height = 10;
board->cells = calloc(20 * 10, sizeof(int));
// Set edge cells!
// Top and bottom edges:
for (int i = 0; i < 20; i) {
board->cells[i] = FLAG_WALL; // [0, 19] (top row)
board->cells[i (20 * (10 - 1))] = FLAG_WALL; // [180, 199] (bottom row)
}
// Left and right edges:
for (int i = 0; i < 10; i) {
board->cells[i * 20] = FLAG_WALL; // (left row)
board->cells[i * 20 20 - 1] = FLAG_WALL; // (right row)
}
// Add snake
board->cells[20 * 2 2] = FLAG_SNAKE;
return INIT_SUCCESS;
}