home · contact · privacy
Restructured chained objects on map via new ChainMapObject struct, allowing for great...
[plomrogue] / src / roguelike.c
1 #include "roguelike.h"
2 #include <stdlib.h>
3 #include <stdint.h>
4 #include <ncurses.h>
5 #include <string.h>
6 #include <time.h>
7 #include <unistd.h>
8 #include "windows.h"
9 #include "draw_wins.h"
10 #include "keybindings.h"
11 #include "readwrite.h"
12 #include "objects_on_map.h"
13
14 uint16_t rrand(char use_seed, uint32_t new_seed) {
15 // Pseudo-random number generator (LGC algorithm). Use instead of rand() to ensure portable predictability.
16   static uint32_t seed;
17   if (0 != use_seed)
18     seed = new_seed;
19   seed = ((seed * 1103515245) + 12345) % 2147483648;   // Values as recommended by POSIX.1-2001 (see rand(3)).
20   return (seed / 65536); }                         // Ignore least significant 16 bits (they are less random).
21
22 void update_log (struct World * world, char * text) {
23 // Update log by appending text, or by appending a "." if text is the same as the last one.
24   static char * last_msg;
25   if (0 == last_msg)
26     last_msg = calloc(1, sizeof(char));
27   char * new_text;
28   uint16_t len_old = strlen(world->log);
29   if (0 == strcmp(last_msg, text)) {
30     uint16_t len_whole = len_old + 1;
31     new_text = calloc(len_whole + 1, sizeof(char));
32     memcpy(new_text, world->log, len_old);
33     memcpy(new_text + len_old, ".", 1); }
34   else {
35     uint16_t len_new = strlen(text);
36     uint16_t len_whole = len_old + len_new + 1;
37     new_text = calloc(len_whole, sizeof(char));
38     memcpy(new_text, world->log, len_old);
39     memcpy(new_text + len_old, text, len_new);
40     last_msg = calloc(len_new + 1, sizeof(char));
41     memcpy(last_msg, text, len_new); }
42   free(world->log);
43   world->log = new_text; }
44
45 struct Map init_map () {
46 // Initialize map with some experimental start values.
47   struct Map map;
48   map.size.x = 64;
49   map.size.y = 64;
50   map.offset.x = 0;
51   map.offset.y = 0;
52   uint32_t size = map.size.x * map.size.y;
53   map.cells = malloc(size);
54   uint16_t y, x;
55   for (y = 0; y < map.size.y; y++)
56     for (x = 0; x < map.size.x; x++)
57       map.cells[(y * map.size.x) + x] = '~';
58   map.cells[size / 2 + (map.size.x / 2)] = '.';
59   uint32_t repeats, root, curpos;
60   for (root = 0; root * root * root < size; root++);
61   for (repeats = 0; repeats < size * root; repeats++) {
62     y = rrand(0, 0) % map.size.y;
63     x = rrand(0, 0) % map.size.x;
64     curpos = y * map.size.x + x;
65     if ('~' == map.cells[curpos] &&
66         (   (curpos >= map.size.x && '.' == map.cells[curpos - map.size.x])
67          || (curpos < map.size.x * (map.size.y-1) && '.' == map.cells[curpos + map.size.x])
68          || (curpos > 0 && curpos % map.size.x != 0 && '.' == map.cells[curpos-1])
69          || (curpos < (map.size.x * map.size.y) && (curpos+1) % map.size.x != 0 && '.' == map.cells[curpos+1])))
70       map.cells[y * map.size.x + x] = '.'; }
71   return map; }
72
73 void map_scroll (struct Map * map, char dir) {
74 // Scroll map into direction dir if possible by changing the offset.
75   if      (NORTH == dir && map->offset.y > 0) map->offset.y--;
76   else if (SOUTH == dir)                      map->offset.y++;
77   else if (WEST  == dir && map->offset.x > 0) map->offset.x--;
78   else if (EAST  == dir)                      map->offset.x++; }
79
80 void turn_over (struct World * world, char action) {
81 // Record action in game record file, increment turn and move enemy.
82   if (1 == world->interactive) {
83     FILE * file = fopen("record", "a");
84     fputc(action, file);
85     fclose(file); }
86   world->turn++;
87   rrand(1, world->seed * world->turn);
88   struct Monster * monster;
89   for (monster = world->monster; monster != 0; monster = monster->cmo.next)
90     move_monster(world, monster); }
91
92 void save_game(struct World * world) {
93 // Save game data to game file.
94   FILE * file = fopen("savefile", "w");
95   write_uint32_bigendian(world->seed, file);
96   write_uint32_bigendian(world->turn, file);
97   write_uint16_bigendian(world->player->pos.y + 1, file);
98   write_uint16_bigendian(world->player->pos.x + 1, file);
99   write_map_objects (world->monster, file, write_map_objects_monsterdata);
100   write_map_objects (world->item, file, readwrite_map_objects_dummy);
101   fclose(file); }
102
103 void toggle_window (struct WinMeta * win_meta, struct Win * win) {
104 // Toggle display of window win.
105   if (0 != win->frame.curses_win)
106     suspend_win(win_meta, win);
107   else
108     append_win(win_meta, win); }
109
110 void scroll_pad (struct WinMeta * win_meta, char dir) {
111 // Try to scroll pad left or right.
112   if      ('+' == dir)
113     reset_pad_offset(win_meta, win_meta->pad_offset + 1);
114   else if ('-' == dir)
115     reset_pad_offset(win_meta, win_meta->pad_offset - 1); }
116
117 void growshrink_active_window (struct WinMeta * win_meta, char change) {
118 // Grow or shrink active window horizontally or vertically by one cell size.
119   if (0 != win_meta->active) {
120     struct yx_uint16 size = win_meta->active->frame.size;
121     if      (change == '-') size.y--;
122     else if (change == '+') size.y++;
123     else if (change == '_') size.x--;
124     else if (change == '*') size.x++;
125     resize_active_win (win_meta, size); } }
126
127 unsigned char meta_keys(int key, struct World * world, struct WinMeta * win_meta, struct Win * win_keys,
128                         struct Win * win_map, struct Win * win_info, struct Win * win_log) {
129 // Call some meta program / window management actions dependent on key. Return 1 to signal quitting.
130   if (key == get_action_key(world->keybindings, "quit"))
131     return 1;
132   else if (key == get_action_key(world->keybindings, "scroll pad right"))
133     scroll_pad (win_meta, '+');
134   else if (key == get_action_key(world->keybindings, "scroll pad left"))
135     scroll_pad (win_meta, '-');
136   else if (key == get_action_key(world->keybindings, "toggle keys window"))
137     toggle_window(win_meta, win_keys);
138   else if (key == get_action_key(world->keybindings, "toggle map window"))
139     toggle_window(win_meta, win_map);
140   else if (key == get_action_key(world->keybindings, "toggle info window"))
141     toggle_window(win_meta, win_info);
142   else if (key == get_action_key(world->keybindings, "toggle log window"))
143     toggle_window(win_meta, win_log);
144   else if (key == get_action_key(world->keybindings, "cycle forwards"))
145     cycle_active_win(win_meta, 'n');
146   else if (key == get_action_key(world->keybindings, "cycle backwards"))
147     cycle_active_win(win_meta, 'p');
148   else if (key == get_action_key(world->keybindings, "shift forwards"))
149     shift_active_win(win_meta, 'f');
150   else if (key == get_action_key(world->keybindings, "shift backwards"))
151     shift_active_win(win_meta, 'b');
152   else if (key == get_action_key(world->keybindings, "grow horizontally"))
153     growshrink_active_window(win_meta, '*');
154   else if (key == get_action_key(world->keybindings, "shrink horizontally"))
155     growshrink_active_window(win_meta, '_');
156   else if (key == get_action_key(world->keybindings, "grow vertically"))
157     growshrink_active_window(win_meta, '+');
158   else if (key == get_action_key(world->keybindings, "shrink vertically"))
159     growshrink_active_window(win_meta, '-');
160   else if (key == get_action_key(world->keybindings, "save keys"))
161     save_keybindings(world);
162   else if (key == get_action_key(world->keybindings, "keys nav up"))
163     keyswin_move_selection (world, 'u');
164   else if (key == get_action_key(world->keybindings, "keys nav down"))
165     keyswin_move_selection (world, 'd');
166   else if (key == get_action_key(world->keybindings, "keys mod"))
167     keyswin_mod_key (world, win_meta);
168   else if (key == get_action_key(world->keybindings, "map up"))
169     map_scroll (world->map, NORTH);
170   else if (key == get_action_key(world->keybindings, "map down"))
171     map_scroll (world->map, SOUTH);
172   else if (key == get_action_key(world->keybindings, "map right"))
173     map_scroll (world->map, EAST);
174   else if (key == get_action_key(world->keybindings, "map left"))
175     map_scroll (world->map, WEST);
176   return 0; }
177
178 void write_map_objects_monsterdata (void * start, FILE * file) {
179 // Write to file data specific tto map objects of type monster.
180   struct Monster * monster = (struct Monster *) start;
181   fputc(monster->hitpoints, file); }
182
183 void readwrite_map_objects_dummy (void * dummy, FILE * file) {
184 // Dummy function for calls of (write|read)_map_objects on map objects without specific attributes.
185   ; }
186
187 void write_map_objects (void * start, FILE * file, void (* f) (void *, FILE *) ) {
188 // Write into file the map object chain starting at start, use f() for object-type specific data.
189   struct ChainMapObject * cmo;
190   for (cmo = start; cmo != 0; cmo = cmo->next) {
191     write_uint16_bigendian(cmo->pos.y + 1, file);
192     write_uint16_bigendian(cmo->pos.x + 1, file);
193     fputc(cmo->name, file);
194     f (cmo, file); }
195   write_uint16_bigendian(0, file); }
196
197 void read_map_objects_monsterdata (void * start, FILE * file) {
198 // Read from file data speciifc to map objects of type monster.
199   struct Monster * monster = (struct Monster *) start;
200   monster->hitpoints = fgetc(file); }
201
202 void read_map_objects (void * start, FILE * file, size_t size, void (* f) (void *, FILE *) ) {
203 // Read from file chain of map objects starting at start, use f() for object-type specific data.
204   int * q = start;
205   * q = 0;
206   struct ChainMapObject * cmo;
207   struct ChainMapObject * * z = start;
208   uint16_t test;
209   char still_at_start = 1;
210   while (1) {
211     test = read_uint16_bigendian(file);
212     if (0 == test)
213       break;
214     if (still_at_start) {
215       cmo = malloc(size);
216       * z = cmo;
217       still_at_start = 0; }
218     else {
219       cmo->next = malloc(size);
220       cmo = cmo->next; }
221     cmo->pos.y = test - 1;
222     cmo->pos.x = read_uint16_bigendian(file) - 1;
223     cmo->name = fgetc(file);
224     f (cmo, file); }
225   if (!still_at_start)
226     cmo->next = 0; }
227
228 void build_map_objects_monsterdata (void * start) {
229 // Build data specific to map objects of type monster.
230   struct Monster * monster = (struct Monster *) start;
231   monster->cmo.name = 'A' + (rrand(0, 0) % 8);
232   monster->hitpoints = 5; }
233
234 void build_map_objects_itemdata (void * start) {
235 // Build data speciifc to map objects of type data.
236   struct Item * item = (struct Item *) start;
237   item->cmo.name = '#' + (rrand(0, 0) % 4); }
238
239 void build_map_objects (void * start, unsigned char n, size_t size, void (* f) (void *), struct Map * map) {
240 // Build chain of n map objects starting at start, use f() for object-specific data.
241   int * q = start;
242   * q = 0;
243   unsigned char i;
244   struct ChainMapObject * cmo;
245   struct ChainMapObject * * z = start;
246   char still_at_start = 1;
247   for (i = 0; i < n; i++) {
248     if (still_at_start) {
249       cmo = malloc(size);
250       * z = cmo;
251       still_at_start = 0; }
252     else {
253       cmo->next = malloc(size);
254       cmo = cmo->next; }
255     cmo->pos = find_passable_pos(map);
256     f(cmo); }
257   if (!still_at_start)
258     cmo->next = 0; }
259
260 int main (int argc, char *argv[]) {
261   struct World world;
262
263   // Read in startup options (i.e. replay option and replay start turn).
264   int opt;
265   uint32_t start_turn;
266   world.interactive = 1;
267   while ((opt = getopt(argc, argv, "s::")) != -1) {
268     switch (opt) {
269       case 's':
270         world.interactive = 0;
271         start_turn = 0;
272         if (optarg)
273           start_turn = atoi(optarg);
274         break;
275       default:
276         exit(EXIT_FAILURE); } }
277
278   // Initialize log, player, monsters and items.
279   world.log = calloc(1, sizeof(char));
280   update_log (&world, " ");
281   struct Player player;
282   world.player = &player;
283
284   // For interactive mode, try to load world state from savefile.
285   FILE * file;
286   if (1 == world.interactive && 0 == access("savefile", F_OK)) {
287     file = fopen("savefile", "r");
288     world.seed = read_uint32_bigendian(file);
289     world.turn = read_uint32_bigendian(file);
290     player.pos.y = read_uint16_bigendian(file) - 1;
291     player.pos.x = read_uint16_bigendian(file) - 1;
292     read_map_objects (&world.monster, file, sizeof(struct Monster), read_map_objects_monsterdata);
293     read_map_objects (&world.item,    file, sizeof(struct Item),    readwrite_map_objects_dummy);
294     fclose(file); }
295
296   // For non-interactive mode, try to load world state from record file.
297   else {
298     world.turn = 1;
299     if (0 == world.interactive) {
300       file = fopen("record", "r");
301       world.seed = read_uint32_bigendian(file); }
302
303     // For interactive-mode in newly started world, generate a start seed from the current time.
304     else {
305       file = fopen("record", "w");
306       world.seed = time(NULL);
307       write_uint32_bigendian(world.seed, file);
308       fclose(file); } }
309
310   // Generate map from seed and, if newly generated world, start positions of actors.
311   rrand(1, world.seed);
312   struct Map map = init_map();
313   world.map = &map;
314   if (1 == world.turn) {
315     player.pos = find_passable_pos(&map);
316     unsigned char n_monsters = rrand(0, 0) % 16;
317     unsigned char n_items    = rrand(0, 0) % 48;
318     build_map_objects (&world.monster, n_monsters, sizeof(struct Monster), build_map_objects_monsterdata, &map);
319     build_map_objects (&world.item,    n_items,    sizeof(struct Item),    build_map_objects_itemdata,    &map); }
320
321   // Initialize window system and windows.
322   WINDOW * screen = initscr();
323   noecho();
324   curs_set(0);
325   keypad(screen, TRUE);
326   raw();
327   init_keybindings(&world);
328   struct WinMeta win_meta = init_win_meta(screen);
329   struct Win win_keys = init_win(&win_meta, "Keys", &world, draw_keys_win);
330   struct Win win_map = init_win(&win_meta, "Map", &world, draw_map_win);
331   struct Win win_info = init_win(&win_meta, "Info", &world, draw_info_win);
332   struct Win win_log = init_win(&win_meta, "Log", &world, draw_log_win);
333   win_keys.frame.size.x = 29;
334   win_map.frame.size.x = win_meta.pad.size.x - win_keys.frame.size.x - win_log.frame.size.x - 2;
335   win_info.frame.size.y = 1;
336   win_log.frame.size.y = win_meta.pad.size.y - 3;
337   toggle_window(&win_meta, &win_keys);
338   toggle_window(&win_meta, &win_map);
339   toggle_window(&win_meta, &win_info);
340   toggle_window(&win_meta, &win_log);
341
342   // Replay mode.
343   int key;
344   unsigned char quit_called = 0;
345   if (0 == world.interactive) {
346     unsigned char still_reading_file = 1;
347     int action;
348     while (1) {
349       if (start_turn == world.turn)
350         start_turn = 0;
351       if (0 == start_turn) {
352         draw_all_wins (&win_meta);
353         key = getch(); }
354       if (1 == still_reading_file &&
355           (world.turn < start_turn || key == get_action_key(world.keybindings, "wait / next turn")) ) {
356         action = getc(file);
357         if (EOF == action) {
358           start_turn = 0;
359           still_reading_file = 0; }
360         else if (0 == action)
361           player_wait (&world);
362         else if (NORTH == action)
363           move_player(&world, NORTH);
364         else if (EAST  == action)
365           move_player(&world, EAST);
366         else if (SOUTH == action)
367           move_player(&world, SOUTH);
368         else if (WEST == action)
369           move_player(&world, WEST); }
370       else
371         quit_called = meta_keys(key, &world, &win_meta, &win_keys, &win_map, &win_info, &win_log);
372         if (1 == quit_called)
373           break; } }
374
375   // Interactive mode.
376   else {
377     uint32_t last_turn = 0;
378     while (1) {
379       if (last_turn != world.turn) {
380         save_game(&world);
381         last_turn = world.turn; }
382       draw_all_wins (&win_meta);
383       key = getch();
384       if      (key == get_action_key(world.keybindings, "player up"))
385         move_player(&world, NORTH);
386       else if (key == get_action_key(world.keybindings, "player right"))
387         move_player(&world, EAST);
388       else if (key == get_action_key(world.keybindings, "player down"))
389         move_player(&world, SOUTH);
390       else if (key == get_action_key(world.keybindings, "player left"))
391         move_player(&world, WEST);
392       else if (key == get_action_key(world.keybindings, "wait / next turn"))
393         player_wait (&world);
394       else
395         quit_called = meta_keys(key, &world, &win_meta, &win_keys, &win_map, &win_info, &win_log);
396         if (1 == quit_called)
397           break; } }
398
399   // Clean up and exit.
400   free(map.cells);
401   for (key = 0; key <= world.keyswindata->max; key++)
402     free(world.keybindings[key].name);
403   free(world.keybindings);
404   free(world.keyswindata);
405   free(world.log);
406   endwin();
407   return 0; }