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