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