dfe3475043753cb3c4a2399570403e82af6f9363
[gbajam22] / src / level.c
1 #include "util.h"
2 #include "debug.h"
3 #include "level.h"
4
5 struct level *init_level(const char *descstr)
6 {
7         const char *str, *line;
8         int i, j, ncols = 0, nrows = 0;
9         struct level *lvl;
10         struct cell *cell;
11
12         str = line = descstr;
13
14         while(*str) {
15                 if(*str == '\n') {
16                         if(ncols > 0 && str > line && str - line != ncols) {
17                                 panic(get_pc(), "init_level: inconsistent ncols (%d != %d)\n", str - line, ncols);
18                         }
19                         ncols = str - line;
20                         nrows++;
21                         while(*++str == '\n');
22                         line = str;
23                 } else {
24                         str++;
25                 }
26         }
27
28         if(!ispow2(ncols)) {
29                 panic(get_pc(), "init_level: width is not pow2 (%d)\n", ncols);
30         }
31
32         lvl = malloc_nf(sizeof *lvl);
33         lvl->width = ncols;
34         lvl->xmask = ncols - 1;
35         lvl->height = nrows;
36         lvl->cells = calloc_nf(ncols * nrows, sizeof *lvl->cells);
37         lvl->mobs = 0;
38         lvl->items = 0;
39
40         str = descstr;
41         cell = lvl->cells;
42
43         for(i=0; i<nrows; i++) {
44                 for(j=0; j<ncols; j++) {
45                         cell->x = j;
46                         cell->y = i;
47                         if(*str == '#') {
48                                 cell->type = CELL_SOLID;
49                         } else {
50                                 cell->type = CELL_WALK;
51                         }
52                         cell++;
53                         while(*++str == '\n') str++;
54                 }
55         }
56
57         return lvl;
58 }
59
60 void free_level(struct level *lvl)
61 {
62         void *tmp;
63
64         free(lvl->cells);
65
66         while(lvl->mobs) {
67                 tmp = lvl->mobs;
68                 lvl->mobs = lvl->mobs->next;
69                 free(tmp);
70         }
71         while(lvl->items) {
72                 tmp = lvl->items;
73                 lvl->items = lvl->items->next;
74                 free(tmp);
75         }
76 }