I have defined these 2 structs:
#define MAP_SIZE 5
typedef struct battle_cell {
int status_a;
int status_b;
int ship_a;
int ship_b;
} battle_cell;
struct battlemap {
battle_cell cell[MAP_SIZE][MAP_SIZE];
int progress_a;
int progress_b;
};
After the initalization of the map and all the other variables with zeros:
for (i = 0; i < MAP_SIZE; i++) {
for (j = 0; j < MAP_SIZE; j++) {
map->cell[i][j].status_a = 0;
map->cell[i][j].status_b = 0;
map->cell[i][j].ship_a = 0;
map->cell[i][j].ship_b = 0;
}
}
map->progress_a = 0;
map->progress_b = 0;
There is a point that I have to check the ship_a and ship_b values that live in each cell, something like that (the logic is a bit more complex than this iteration):
for (i = posXB; i < posXB + SHIP_SIZE; i++) {
map->cell[posYB][i].ship_b = 1;
}
I need to do exactly the same for the ship_a variable. So, I have to duplicate quite a big chunk of code because I am not able to find a way to get the field within the struct dynamically. For example, I could define a function:
void cell_iteration (battlemap *map, int pos, int pos_y, int ship_size, /* field_parameter/pointer */) {
int i;
for (i = pos; i < pos + ship_size; i++) {
map->cell[pos_y][i].ship_b = 1; // use the field_parameter/pointer instead of ship_b
}
}
Is there an elegant way to do something like that?
UPDATE
Just a clarification. The structs can definitely be simplified, but this is not my question. I 've just tried to create an example :)