home · contact · privacy
Added command to focus map on player.
[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 "objects_on_map.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 curpos;
60   while (1) {
61     y = rrand(0, 0) % map.size.y;
62     x = rrand(0, 0) % map.size.x;
63     curpos = y * map.size.x + x;
64     if ('~' == map.cells[curpos] &&
65         (   (curpos >= map.size.x && '.' == map.cells[curpos - map.size.x])
66          || (curpos < map.size.x * (map.size.y-1) && '.' == map.cells[curpos + map.size.x])
67          || (curpos > 0 && curpos % map.size.x != 0 && '.' == map.cells[curpos-1])
68          || (curpos < (map.size.x * map.size.y) && (curpos+1) % map.size.x != 0 && '.' == map.cells[curpos+1]))) {
69       if (y == 0 || y == map.size.y - 1 || x == 0 || x == map.size.x - 1)
70         break;
71       map.cells[y * map.size.x + x] = '.'; } }
72   return map; }
73
74 void map_scroll (struct Map * map, char dir, struct yx_uint16 win_size) {
75 // Scroll map into direction dir if possible by changing the offset.
76   if      (NORTH == dir && map->offset.y > 0)
77     map->offset.y--;
78   else if (WEST  == dir && map->offset.x > 0)
79     map->offset.x--;
80   else if (SOUTH == dir && map->offset.y + win_size.y < map->size.y)
81     map->offset.y++;
82   else if (EAST  == dir && map->offset.x + win_size.x < map->size.x)
83     map->offset.x++; }
84
85 void map_center_player (struct Map * map, struct Player * player, struct yx_uint16 win_size) {
86 // Center map on player.
87   if (player->pos.y < win_size.y / 2)                      map->offset.y = 0;
88   else if (player->pos.y < map->size.y - (win_size.y / 2)) map->offset.y = player->pos.y - (win_size.y / 2);
89   else                                                     map->offset.y = map->size.y - win_size.y;
90   if (player->pos.x < win_size.x / 2)                      map->offset.x = 0;
91   else if (player->pos.x < map->size.x - (win_size.x / 2)) map->offset.x = player->pos.x - (win_size.x / 2);
92   else                                                     map->offset.x = map->size.x - win_size.x; }
93
94 void turn_over (struct World * world, char action) {
95 // Record action in game record file, increment turn and move enemy.
96   if (1 == world->interactive) {
97     FILE * file = fopen("record", "a");
98     fputc(action, file);
99     fclose(file); }
100   world->turn++;
101   rrand(1, world->seed * world->turn);
102   struct Monster * monster;
103   for (monster = world->monster; monster != 0; monster = monster->cmo.next)
104     move_monster(world, monster); }
105
106 void save_game(struct World * world) {
107 // Save game data to game file.
108   FILE * file = fopen("savefile", "w");
109   write_uint32_bigendian(world->seed, file);
110   write_uint32_bigendian(world->turn, file);
111   write_uint16_bigendian(world->player->pos.y + 1, file);
112   write_uint16_bigendian(world->player->pos.x + 1, file);
113   write_map_objects (world->monster, file, write_map_objects_monsterdata);
114   write_map_objects (world->item, file, readwrite_map_objects_dummy);
115   fclose(file); }
116
117 void toggle_window (struct WinMeta * win_meta, struct Win * win) {
118 // Toggle display of window win.
119   if (0 != win->frame.curses_win)
120     suspend_win(win_meta, win);
121   else
122     append_win(win_meta, win); }
123
124 void scroll_pad (struct WinMeta * win_meta, char dir) {
125 // Try to scroll pad left or right.
126   if      ('+' == dir)
127     reset_pad_offset(win_meta, win_meta->pad_offset + 1);
128   else if ('-' == dir)
129     reset_pad_offset(win_meta, win_meta->pad_offset - 1); }
130
131 void growshrink_active_window (struct WinMeta * win_meta, char change) {
132 // Grow or shrink active window horizontally or vertically by one cell size.
133   if (0 != win_meta->active) {
134     struct yx_uint16 size = win_meta->active->frame.size;
135     if      (change == '-') size.y--;
136     else if (change == '+') size.y++;
137     else if (change == '_') size.x--;
138     else if (change == '*') size.x++;
139     resize_active_win (win_meta, size); } }
140
141 unsigned char meta_keys(int key, struct World * world, struct WinMeta * win_meta, struct Win * win_keys,
142                         struct Win * win_map, struct Win * win_info, struct Win * win_log) {
143 // Call some meta program / window management actions dependent on key. Return 1 to signal quitting.
144   if (key == get_action_key(world->keybindings, "quit"))
145     return 1;
146   else if (key == get_action_key(world->keybindings, "scroll pad right"))
147     scroll_pad (win_meta, '+');
148   else if (key == get_action_key(world->keybindings, "scroll pad left"))
149     scroll_pad (win_meta, '-');
150   else if (key == get_action_key(world->keybindings, "toggle keys window"))
151     toggle_window(win_meta, win_keys);
152   else if (key == get_action_key(world->keybindings, "toggle map window"))
153     toggle_window(win_meta, win_map);
154   else if (key == get_action_key(world->keybindings, "toggle info window"))
155     toggle_window(win_meta, win_info);
156   else if (key == get_action_key(world->keybindings, "toggle log window"))
157     toggle_window(win_meta, win_log);
158   else if (key == get_action_key(world->keybindings, "cycle forwards"))
159     cycle_active_win(win_meta, 'n');
160   else if (key == get_action_key(world->keybindings, "cycle backwards"))
161     cycle_active_win(win_meta, 'p');
162   else if (key == get_action_key(world->keybindings, "shift forwards"))
163     shift_active_win(win_meta, 'f');
164   else if (key == get_action_key(world->keybindings, "shift backwards"))
165     shift_active_win(win_meta, 'b');
166   else if (key == get_action_key(world->keybindings, "grow horizontally"))
167     growshrink_active_window(win_meta, '*');
168   else if (key == get_action_key(world->keybindings, "shrink horizontally"))
169     growshrink_active_window(win_meta, '_');
170   else if (key == get_action_key(world->keybindings, "grow vertically"))
171     growshrink_active_window(win_meta, '+');
172   else if (key == get_action_key(world->keybindings, "shrink vertically"))
173     growshrink_active_window(win_meta, '-');
174   else if (key == get_action_key(world->keybindings, "save keys"))
175     save_keybindings(world);
176   else if (key == get_action_key(world->keybindings, "keys nav up"))
177     keyswin_move_selection (world, 'u');
178   else if (key == get_action_key(world->keybindings, "keys nav down"))
179     keyswin_move_selection (world, 'd');
180   else if (key == get_action_key(world->keybindings, "keys mod"))
181     keyswin_mod_key (world, win_meta);
182   else if (key == get_action_key(world->keybindings, "map up"))
183     map_scroll (world->map, NORTH, win_map->frame.size);
184   else if (key == get_action_key(world->keybindings, "map down"))
185     map_scroll (world->map, SOUTH, win_map->frame.size);
186   else if (key == get_action_key(world->keybindings, "map right"))
187     map_scroll (world->map, EAST, win_map->frame.size);
188   else if (key == get_action_key(world->keybindings, "map left"))
189     map_scroll (world->map, WEST, win_map->frame.size);
190   else if (key == get_action_key(world->keybindings, "map center player"))
191     map_center_player (world->map, world->player, win_map->frame.size);
192   return 0; }
193
194 int main (int argc, char *argv[]) {
195   struct World world;
196
197   // Read in startup options (i.e. replay option and replay start turn).
198   int opt;
199   uint32_t start_turn;
200   world.interactive = 1;
201   while ((opt = getopt(argc, argv, "s::")) != -1) {
202     switch (opt) {
203       case 's':
204         world.interactive = 0;
205         start_turn = 0;
206         if (optarg)
207           start_turn = atoi(optarg);
208         break;
209       default:
210         exit(EXIT_FAILURE); } }
211
212   // Initialize log, player, monsters and items.
213   world.log = calloc(1, sizeof(char));
214   update_log (&world, " ");
215   struct Player player;
216   player.hitpoints = 5;
217   world.player = &player;
218   world.monster = 0;
219   world.item = 0;
220
221   // For interactive mode, try to load world state from savefile.
222   FILE * file;
223   if (1 == world.interactive && 0 == access("savefile", F_OK)) {
224     file = fopen("savefile", "r");
225     world.seed = read_uint32_bigendian(file);
226     world.turn = read_uint32_bigendian(file);
227     player.pos.y = read_uint16_bigendian(file) - 1;
228     player.pos.x = read_uint16_bigendian(file) - 1;
229     read_map_objects (&world.monster, file, sizeof(struct Monster), read_map_objects_monsterdata);
230     read_map_objects (&world.item,    file, sizeof(struct Item),    readwrite_map_objects_dummy);
231     fclose(file); }
232
233   // For non-interactive mode, try to load world state from record file.
234   else {
235     world.turn = 1;
236     if (0 == world.interactive) {
237       file = fopen("record", "r");
238       world.seed = read_uint32_bigendian(file); }
239
240     // For interactive-mode in newly started world, generate a start seed from the current time.
241     else {
242       file = fopen("record", "w");
243       world.seed = time(NULL);
244       write_uint32_bigendian(world.seed, file);
245       fclose(file); } }
246
247   // Generate map from seed and, if newly generated world, start positions of actors.
248   rrand(1, world.seed);
249   struct Map map = init_map();
250   world.map = &map;
251   if (1 == world.turn) {
252     player.pos = find_passable_pos(&map);
253     unsigned char n_monsters = rrand(0, 0) % 16;
254     unsigned char n_items    = rrand(0, 0) % 48;
255     build_map_objects (&world.monster, n_monsters, sizeof(struct Monster), build_map_objects_monsterdata, &map);
256     build_map_objects (&world.item,    n_items,    sizeof(struct Item),    build_map_objects_itemdata,    &map); }
257
258   // Initialize window system and windows.
259   WINDOW * screen = initscr();
260   noecho();
261   curs_set(0);
262   keypad(screen, TRUE);
263   raw();
264   init_keybindings(&world);
265   struct WinMeta win_meta = init_win_meta(screen);
266   struct Win win_keys = init_win(&win_meta, "Keys", &world, draw_keys_win);
267   struct Win win_map = init_win(&win_meta, "Map", &world, draw_map_win);
268   struct Win win_info = init_win(&win_meta, "Info", &world, draw_info_win);
269   struct Win win_log = init_win(&win_meta, "Log", &world, draw_log_win);
270   win_keys.frame.size.x = 29;
271   win_map.frame.size.x = win_meta.pad.size.x - win_keys.frame.size.x - win_log.frame.size.x - 2;
272   win_info.frame.size.y = 2;
273   win_log.frame.size.y = win_meta.pad.size.y - (2 + win_info.frame.size.y);
274   toggle_window(&win_meta, &win_keys);
275   toggle_window(&win_meta, &win_map);
276   toggle_window(&win_meta, &win_info);
277   toggle_window(&win_meta, &win_log);
278
279   // Replay mode.
280   int key;
281   unsigned char quit_called = 0;
282   unsigned char await_actions = 1;
283   if (0 == world.interactive) {
284     int action;
285     while (1) {
286       if (start_turn == world.turn)
287         start_turn = 0;
288       if (0 == start_turn) {
289         draw_all_wins (&win_meta);
290         key = getch(); }
291       if (1 == await_actions &&
292           (world.turn < start_turn || key == get_action_key(world.keybindings, "wait / next turn")) ) {
293         action = getc(file);
294         if (EOF == action) {
295           start_turn = 0;
296           await_actions = 0; }
297         else if (0 == action)
298           player_wait (&world);
299         else if (NORTH == action)
300           move_player(&world, NORTH);
301         else if (EAST  == action)
302           move_player(&world, EAST);
303         else if (SOUTH == action)
304           move_player(&world, SOUTH);
305         else if (WEST == action)
306           move_player(&world, WEST); }
307       else
308         quit_called = meta_keys(key, &world, &win_meta, &win_keys, &win_map, &win_info, &win_log);
309         if (1 == quit_called)
310           break; } }
311
312   // Interactive mode.
313   else {
314     uint32_t last_turn = 0;
315     while (1) {
316       if (last_turn != world.turn) {
317         save_game(&world);
318         last_turn = world.turn; }
319       if (1 == await_actions && 0 == player.hitpoints)
320         await_actions = 0;
321       draw_all_wins (&win_meta);
322       key = getch();
323       if      (1 == await_actions && key == get_action_key(world.keybindings, "player up"))
324         move_player(&world, NORTH);
325       else if (1 == await_actions && key == get_action_key(world.keybindings, "player right"))
326         move_player(&world, EAST);
327       else if (1 == await_actions && key == get_action_key(world.keybindings, "player down"))
328         move_player(&world, SOUTH);
329       else if (1 == await_actions && key == get_action_key(world.keybindings, "player left"))
330         move_player(&world, WEST);
331       else if (1 == await_actions && key == get_action_key(world.keybindings, "wait / next turn"))
332         player_wait (&world);
333       else
334         quit_called = meta_keys(key, &world, &win_meta, &win_keys, &win_map, &win_info, &win_log);
335         if (1 == quit_called)
336           break; } }
337
338   // Clean up and exit.
339   free(map.cells);
340   for (key = 0; key <= world.keyswindata->max; key++)
341     free(world.keybindings[key].name);
342   free(world.keybindings);
343   free(world.keyswindata);
344   free(world.log);
345   endwin();
346   return 0; }