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