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