home · contact · privacy
Refactored finding of random passable position into its own function.
[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 "actors.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 struct yx_uint16 find_passable_pos (struct Map * map) {
74 // Return a random passable position on map.
75   struct yx_uint16 pos;
76   for (pos.y = pos.x = 0; 0 == is_passable(map, pos);) {
77       pos.y = rrand(0, 0) % map->size.y;
78       pos.x = rrand(0, 0) % map->size.x; }
79   return pos; }
80
81 void map_scroll (struct Map * map, char dir) {
82 // Scroll map into direction dir if possible by changing the offset.
83   if      (NORTH == dir && map->offset.y > 0) map->offset.y--;
84   else if (SOUTH == dir)                      map->offset.y++;
85   else if (WEST  == dir && map->offset.x > 0) map->offset.x--;
86   else if (EAST  == dir)                      map->offset.x++; }
87
88 void turn_over (struct World * world, char action) {
89 // Record action in game record file, increment turn and move enemy.
90   if (1 == world->interactive) {
91     FILE * file = fopen("record", "a");
92     fputc(action, file);
93     fclose(file); }
94   world->turn++;
95   rrand(1, world->seed * world->turn);
96   struct Monster * monster;
97   for (monster = world->monster; monster != 0; monster = monster->next)
98     move_monster(world, monster); }
99
100 void save_game(struct World * world) {
101 // Save game data to game file.
102   FILE * file = fopen("savefile", "w");
103   write_uint32_bigendian(world->seed, file);
104   write_uint32_bigendian(world->turn, file);
105   write_uint16_bigendian(world->player->pos.y + 1, file);
106   write_uint16_bigendian(world->player->pos.x + 1, file);
107   struct Monster * monster;
108   for (monster = world->monster; monster != 0; monster = monster->next) {
109     write_uint16_bigendian(monster->pos.y + 1, file);
110     write_uint16_bigendian(monster->pos.x + 1, file); }
111   write_uint16_bigendian(0, file);
112   struct Item * item;
113   for (item = world->item; item != 0; item = item->next) {
114     write_uint16_bigendian(item->pos.y + 1, file);
115     write_uint16_bigendian(item->pos.x + 1, file); }
116   write_uint16_bigendian(0, file);
117   fclose(file); }
118
119 void toggle_window (struct WinMeta * win_meta, struct Win * win) {
120 // Toggle display of window win.
121   if (0 != win->frame.curses_win)
122     suspend_win(win_meta, win);
123   else
124     append_win(win_meta, win); }
125
126 void scroll_pad (struct WinMeta * win_meta, char dir) {
127 // Try to scroll pad left or right.
128   if      ('+' == dir)
129     reset_pad_offset(win_meta, win_meta->pad_offset + 1);
130   else if ('-' == dir)
131     reset_pad_offset(win_meta, win_meta->pad_offset - 1); }
132
133 void growshrink_active_window (struct WinMeta * win_meta, char change) {
134 // Grow or shrink active window horizontally or vertically by one cell size.
135   if (0 != win_meta->active) {
136     struct yx_uint16 size = win_meta->active->frame.size;
137     if      (change == '-') size.y--;
138     else if (change == '+') size.y++;
139     else if (change == '_') size.x--;
140     else if (change == '*') size.x++;
141     resize_active_win (win_meta, size); } }
142
143 unsigned char meta_keys(int key, struct World * world, struct WinMeta * win_meta, struct Win * win_keys,
144                         struct Win * win_map, struct Win * win_info, struct Win * win_log) {
145 // Call some meta program / window management actions dependent on key. Return 1 to signal quitting.
146   if (key == get_action_key(world->keybindings, "quit"))
147     return 1;
148   else if (key == get_action_key(world->keybindings, "scroll pad right"))
149     scroll_pad (win_meta, '+');
150   else if (key == get_action_key(world->keybindings, "scroll pad left"))
151     scroll_pad (win_meta, '-');
152   else if (key == get_action_key(world->keybindings, "toggle keys window"))
153     toggle_window(win_meta, win_keys);
154   else if (key == get_action_key(world->keybindings, "toggle map window"))
155     toggle_window(win_meta, win_map);
156   else if (key == get_action_key(world->keybindings, "toggle info window"))
157     toggle_window(win_meta, win_info);
158   else if (key == get_action_key(world->keybindings, "toggle log window"))
159     toggle_window(win_meta, win_log);
160   else if (key == get_action_key(world->keybindings, "cycle forwards"))
161     cycle_active_win(win_meta, 'n');
162   else if (key == get_action_key(world->keybindings, "cycle backwards"))
163     cycle_active_win(win_meta, 'p');
164   else if (key == get_action_key(world->keybindings, "shift forwards"))
165     shift_active_win(win_meta, 'f');
166   else if (key == get_action_key(world->keybindings, "shift backwards"))
167     shift_active_win(win_meta, 'b');
168   else if (key == get_action_key(world->keybindings, "grow horizontally"))
169     growshrink_active_window(win_meta, '*');
170   else if (key == get_action_key(world->keybindings, "shrink horizontally"))
171     growshrink_active_window(win_meta, '_');
172   else if (key == get_action_key(world->keybindings, "grow vertically"))
173     growshrink_active_window(win_meta, '+');
174   else if (key == get_action_key(world->keybindings, "shrink vertically"))
175     growshrink_active_window(win_meta, '-');
176   else if (key == get_action_key(world->keybindings, "save keys"))
177     save_keybindings(world);
178   else if (key == get_action_key(world->keybindings, "keys nav up"))
179     keyswin_move_selection (world, 'u');
180   else if (key == get_action_key(world->keybindings, "keys nav down"))
181     keyswin_move_selection (world, 'd');
182   else if (key == get_action_key(world->keybindings, "keys mod"))
183     keyswin_mod_key (world, win_meta);
184   else if (key == get_action_key(world->keybindings, "map up"))
185     map_scroll (world->map, NORTH);
186   else if (key == get_action_key(world->keybindings, "map down"))
187     map_scroll (world->map, SOUTH);
188   else if (key == get_action_key(world->keybindings, "map right"))
189     map_scroll (world->map, EAST);
190   else if (key == get_action_key(world->keybindings, "map left"))
191     map_scroll (world->map, WEST);
192   return 0; }
193
194 int main (int argc, char *argv[]) {
195   struct World world;
196
197   // Read in startup options (i.e. replay option and replay start turn).
198   int opt;
199   uint32_t start_turn;
200   world.interactive = 1;
201   while ((opt = getopt(argc, argv, "s::")) != -1) {
202     switch (opt) {
203       case 's':
204         world.interactive = 0;
205         start_turn = 0;
206         if (optarg)
207           start_turn = atoi(optarg);
208         break;
209       default:
210         exit(EXIT_FAILURE); } }
211
212   // Initialize log, player, monsters and items.
213   world.log = calloc(1, sizeof(char));
214   update_log (&world, " ");
215   struct Player player;
216   world.player = &player;
217   struct Monster * monster;
218   struct Item * item;
219   uint16_t test;
220   char start;
221
222   // For interactive mode, try to load world state from savefile.
223   FILE * file;
224   if (1 == world.interactive && 0 == access("savefile", F_OK)) {
225     file = fopen("savefile", "r");
226     world.seed = read_uint32_bigendian(file);
227     world.turn = read_uint32_bigendian(file);
228     player.pos.y = read_uint16_bigendian(file) - 1;
229     player.pos.x = read_uint16_bigendian(file) - 1;
230     start = 1;
231     world.monster = 0;
232     while (1) {
233       test = read_uint16_bigendian(file);
234       if (0 == test)
235         break;
236       if (start) {
237         monster = malloc(sizeof(struct Monster));
238         world.monster = monster;
239         start = 0; }
240       else {
241         monster->next = malloc(sizeof(struct Monster));
242         monster = monster->next; }
243       monster->name = 'M';
244       monster->pos.y = test - 1;
245       monster->pos.x = read_uint16_bigendian(file) - 1; }
246     if (!start)
247       monster->next = 0;
248     start = 1;
249     world.item = 0;
250     while (1) {
251       test = read_uint16_bigendian(file);
252       if (0 == test)
253         break;
254       if (start) {
255         item = malloc(sizeof(struct Item));
256         world.item = item;
257         start = 0; }
258       else {
259         item->next = malloc(sizeof(struct Item));
260         item = item->next; }
261       item->name = '#';
262       item->pos.y = test - 1;
263       item->pos.x = read_uint16_bigendian(file) - 1; }
264     if (!start)
265       item->next = 0;
266     fclose(file); }
267
268   // For non-interactive mode, try to load world state from record file.
269   else {
270     world.turn = 1;
271     if (0 == world.interactive) {
272       file = fopen("record", "r");
273       world.seed = read_uint32_bigendian(file); }
274
275     // For interactive-mode in newly started world, generate a start seed from the current time.
276     else {
277       file = fopen("record", "w");
278       world.seed = time(NULL);
279       write_uint32_bigendian(world.seed, file);
280       fclose(file); } }
281
282   // Generate map from seed and, if newly generated world, start positions of actors.
283   rrand(1, world.seed);
284   struct Map map = init_map();
285   world.map = &map;
286   if (1 == world.turn) {
287     player.pos = find_passable_pos(&map);
288     unsigned char n_monsters = rrand(0, 0) % 16;
289     unsigned char n_items    = rrand(0, 0) % 48;
290     unsigned char i;
291     start = 1;
292     world.monster = 0;
293     for (i = 0; i < n_monsters; i++) {
294       if (start) {
295         monster = malloc(sizeof(struct Monster));
296         world.monster = monster;
297         start = 0; }
298       else {
299         monster->next = malloc(sizeof(struct Monster));
300         monster = monster->next; }
301       monster->pos = find_passable_pos(&map);
302       monster->name = 'M'; }
303     if (!start)
304       monster->next = 0;
305     start = 1;
306     world.item = 0;
307     for (i = 0; i < n_items; i++) {
308       if (start) {
309         item = malloc(sizeof(struct Item));
310         world.item = item;
311         start = 0; }
312       else {
313         item->next = malloc(sizeof(struct Item));
314         item = item->next; }
315       item->pos = find_passable_pos(&map);
316       item->name = '#'; }
317     if (!start)
318       item->next = 0; }
319
320   // Initialize window system and windows.
321   WINDOW * screen = initscr();
322   noecho();
323   curs_set(0);
324   keypad(screen, TRUE);
325   raw();
326   init_keybindings(&world);
327   struct WinMeta win_meta = init_win_meta(screen);
328   struct Win win_keys = init_win(&win_meta, "Keys", &world, draw_keys_win);
329   struct Win win_map = init_win(&win_meta, "Map", &world, draw_map_win);
330   struct Win win_info = init_win(&win_meta, "Info", &world, draw_info_win);
331   struct Win win_log = init_win(&win_meta, "Log", &world, draw_log_win);
332   win_keys.frame.size.x = 29;
333   win_map.frame.size.x = win_meta.pad.size.x - win_keys.frame.size.x - win_log.frame.size.x - 2;
334   win_info.frame.size.y = 1;
335   win_log.frame.size.y = win_meta.pad.size.y - 3;
336   toggle_window(&win_meta, &win_keys);
337   toggle_window(&win_meta, &win_map);
338   toggle_window(&win_meta, &win_info);
339   toggle_window(&win_meta, &win_log);
340
341   // Replay mode.
342   int key;
343   unsigned char quit_called = 0;
344   if (0 == world.interactive) {
345     unsigned char still_reading_file = 1;
346     int action;
347     while (1) {
348       if (start_turn == world.turn)
349         start_turn = 0;
350       if (0 == start_turn) {
351         draw_all_wins (&win_meta);
352         key = getch(); }
353       if (1 == still_reading_file &&
354           (world.turn < start_turn || key == get_action_key(world.keybindings, "wait / next turn")) ) {
355         action = getc(file);
356         if (EOF == action) {
357           start_turn = 0;
358           still_reading_file = 0; }
359         else if (0 == action)
360           player_wait (&world);
361         else if (NORTH == action)
362           move_player(&world, NORTH);
363         else if (EAST  == action)
364           move_player(&world, EAST);
365         else if (SOUTH == action)
366           move_player(&world, SOUTH);
367         else if (WEST == action)
368           move_player(&world, WEST); }
369       else
370         quit_called = meta_keys(key, &world, &win_meta, &win_keys, &win_map, &win_info, &win_log);
371         if (1 == quit_called)
372           break; } }
373
374   // Interactive mode.
375   else {
376     uint32_t last_turn = 0;
377     while (1) {
378       if (last_turn != world.turn) {
379         save_game(&world);
380         last_turn = world.turn; }
381       draw_all_wins (&win_meta);
382       key = getch();
383       if      (key == get_action_key(world.keybindings, "player up"))
384         move_player(&world, NORTH);
385       else if (key == get_action_key(world.keybindings, "player right"))
386         move_player(&world, EAST);
387       else if (key == get_action_key(world.keybindings, "player down"))
388         move_player(&world, SOUTH);
389       else if (key == get_action_key(world.keybindings, "player left"))
390         move_player(&world, WEST);
391       else if (key == get_action_key(world.keybindings, "wait / next turn"))
392         player_wait (&world);
393       else
394         quit_called = meta_keys(key, &world, &win_meta, &win_keys, &win_map, &win_info, &win_log);
395         if (1 == quit_called)
396           break; } }
397
398   // Clean up and exit.
399   free(map.cells);
400   for (key = 0; key <= world.keyswindata->max; key++)
401     free(world.keybindings[key].name);
402   free(world.keybindings);
403   free(world.keyswindata);
404   free(world.log);
405   endwin();
406   return 0; }