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