Labyrinth Structure in C

Question:

Well, I would like to make a game in C "consola" but I have a doubt…. Basically the idea is to have a character that moves through a maze thanks to the user, if the user writes "right" the character moves to the right etc..

I imagine the maze is basically a two-dimensional array, and inside it all zeros and ones are inserted, "1" would be walls and "0" would be free paths… (if there are better ideas please say)

So far I imagine that there is not much difficulty, but I ask, if you want to put an inventory to the character, how do I get an object there in a certain square of the array? if, for example, in the map[2][3] array there is already a 0 "saying it's a free path", how can I insert an object there? like a backpack or something?

Thank you for your willingness to help 🙂

Answer:

Suppose you use a character to represent a position on the grid, where a white space is a free path and X is a wall and other objects are other characters:

const char caminho = ' ';
const char parede  = 'X';
const char mochila = 'm';
const char faca    = 'f';
const char jogador = '+';
const char ouro    = '$';
const char monstro = 'v';
const char chave   = ',';
const char porta   = '#'; 

You can represent the maze like this:

#define LARGURA 10
#define ALTURA 10

const char[LARGURA][ALTURA + 1] labirinto = {
    "XXXXXXXXXX",
    "X # XfX $X",
    "X X   XvXX",
    "X XXXXX  X",
    "X X      X",
    "X X XXXX X",
    "X X Xm X X",
    "X   XX X X",
    "X+X    X,X",
    "XXXXXXXXXX",
};

This + 1 at the end is the string terminator. This format has the advantage that you can draw the maze on the screen by traversing lines and just giving a printf on each line:

int i;
for (i = 0; i < ALTURA; i++) {
    printf("%s", labirinto[i]);
}

Of course, if you have a better way to draw the maze (especially using images, not just text), there is nothing forcing you to use printf , you can use whatever method you see fit. But anyway this is useful at least for debugging.

You probably don't want the static or fixed-size maze. Maybe then dynamic memory allocation is better:

char* labirinto = malloc(sizeof(char) * altura * (largura + 1));
// Gera o labirinto...
// Roda o jogo...
free(labirinto);

This then works as long as you can use a character to represent something. If you have a very large variety of objects, then perhaps the best thing to do is to use arrays of pointers to some sort of structure that describes these objects.

Scroll to Top