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