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