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