0
I am creating a game for my college work and need to read a txt file to build a level (phase) of the game. The txt example can be accessed here: https://pastebin.com/f778Ucxa. The dash represents an empty space, J the player’s starting position, P the door position, E the enemy positions and the other letters represent chests. In my game, a struct
for each of these elements. There is only one player and one port, but the number of enemies and chests varies from level to level.
I’m encountering several difficulties when implementing the function ler_level()
. My reading loop is this:
while (fread(&leitura, 1, 1, arquivo)) {
switch (leitura) {
case '-': break;
case 'J':
pont_player->posx = byte % 80;
pont_player->posy = byte / 80;
break;
case 'P':
pont_porta->posx = byte % 80;
pont_porta->posy = byte / 80;
break;
case 'E': break; // inimigo, ainda não sei o que colocar aqui
default: break; // baús, idem
}
byte++;
}
I need to build the structs
so that they’re global and, as far as I know, the only way to do that is with malloc()
. So I intend to create a pointer array, the first two being for the player and the port, which are the only constants here:
void ** ponteiros;
ponteiros = malloc(sizeof (void *) * 2);
struct Jogador *pont_player = malloc( sizeof (struct Jogador));
ponteiros[0] = pont_player;
struct Porta *pont_porta = malloc( sizeof (struct Porta));
ponteiros[1] = pont_porta;
I think there is no problem so far, but from now on I do not know what else to do. I need to build an indefinite number of structs
to enemies and chests, so that outside the function I can differentiate the pointers of enemies from those of chests. I thought about using matrices, but I have no idea how a matrix of indefinite pointer sizes works. What about the size of the array ponteiros
, do not know if I can say that it is four or have to consider the possible new arrays of pointers (of enemies and chests) as larger elements, and therefore allocate extra memory to them.
By the way, outside of the function I was planning to "clone" the structs this way:
struct Jogador player = *ponteiros[0] // ou seja lá como eu iria fazer para guardar o ponteiro fora da ler_level()
I don’t know if this is the most "correct" way to do this, because I imagine that you waste memory by collecting the data. Here are the structs I mentioned, in case you need to read their definition: https://pastebin.com/HmWDGYes.