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