home · contact · privacy
Moved pseudo-random generator into its own library, simplified its interface and...
[plomrogue] / src / map.c
1 #include "map.h"
2 #include <stdlib.h>      /* for malloc() */
3 #include <stdint.h>      /* for uint16_t, uint32_t */
4 #include "misc.h"        /* for center_offset() */
5 #include "map_objects.h" /* for Player struct */
6 #include "yx_uint16.h"   /* for yx_uint16 and dir enums */
7 #include "rrand.h"       /* for rrand() */
8
9
10
11 struct Map init_map ()
12 {
13     struct Map map;
14     map.size.x = 64;
15     map.size.y = 64;
16     map.offset.x = 0;
17     map.offset.y = 0;
18     uint32_t size = map.size.x * map.size.y;
19     map.cells = malloc(size);
20     uint16_t y, x;
21     for (y = 0; y < map.size.y; y++)
22     {
23         for (x = 0; x < map.size.x; x++)
24         {
25             map.cells[(y * map.size.x) + x] = '~';
26         }
27     }
28     map.cells[size / 2 + (map.size.x / 2)] = '.';
29     uint32_t curpos;
30     while (1)
31     {
32         y = rrand() % map.size.y;
33         x = rrand() % map.size.x;
34         curpos = y * map.size.x + x;
35         if ('~' == map.cells[curpos]
36             && ((curpos >= map.size.x && '.' == map.cells[curpos - map.size.x])
37                 || (curpos < map.size.x * (map.size.y-1)
38                      && '.' == map.cells[curpos + map.size.x])
39                 || (curpos > 0 && curpos % map.size.x != 0
40                     && '.' == map.cells[curpos-1])
41                 || (curpos < (map.size.x * map.size.y)
42                     && (curpos+1) % map.size.x != 0
43                     && '.' == map.cells[curpos+1])))
44         {
45             if (y == 0 || y == map.size.y - 1 || x == 0 || x == map.size.x - 1)
46             {
47                 break;
48             }
49             map.cells[y * map.size.x + x] = '.';
50         }
51     }
52     return map;
53 }
54
55
56
57 void map_scroll (struct Map * map, enum dir d, struct yx_uint16 win_size)
58 {
59     if      (NORTH == d && map->offset.y > 0)
60     {
61         map->offset.y--;
62     }
63     else if (WEST  == d && map->offset.x > 0)
64     {
65         map->offset.x--;
66     }
67     else if (SOUTH == d && map->offset.y + win_size.y < map->size.y)
68     {
69         map->offset.y++;
70     }
71     else if (EAST  == d && map->offset.x + win_size.x < map->size.x)
72     {
73         map->offset.x++;
74     }
75 }
76
77
78
79 void map_center_player(struct Map * map, struct Player * player,
80                        struct yx_uint16 win_size)
81 {
82     map->offset.y = center_offset (player->pos.y, map->size.y, win_size.y);
83     map->offset.x = center_offset (player->pos.x, map->size.x, win_size.x);
84 }