C-maze structure

3

Well, I would like to make a game in C "console" but I have a question .... Basically the idea is to have a character that goes forward in a labyrinth thanks to the user, if the user type "right" the character moves to the right etc.

I imagine that the labyrinth is basically a two-dimensional array, and inside it is inserted all of zeros and ones, "1" would be walls and "0" 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 in a certain house in the array? if for example in map array [2] [3] there is already a 0 "to say it is free path", how can I insert an object there? type a backpack or anything?

Thank you for your willingness to help:)

    
asked by anonymous 22.11.2014 / 15:42

1 answer

1

Let's suppose you use a character to represent a position on the grid, where a whitespace 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 labyrinth on the screen by traversing lines and only giving printf on each line:

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

Obviously, if you have a better way of drawing the labyrinth (especially using images, not just text), there is nothing that forces you to use printf , you can use whatever method you think best . But anyway this is useful at least for debugging.

You probably will not want the static maze or fixed size. Maybe then dynamic memory allocation is better:

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

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

    
29.11.2014 / 06:49