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