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