home · contact · privacy
7caef902be0f9dad534f8d1c758f5af149d28a37
[plomrogue] / src / main.c
1 /* main.c */
2
3 #include "main.h"
4 #include <stdlib.h> /* for atoi(), exit(), EXIT_FAILURE, calloc() */
5 #include <stdio.h> /* for FILE typedef, F_OK, rename() */
6 #include <ncurses.h> /* for initscr(), noecho(), curs_set(), keypad(), raw() */
7 #include <time.h> /* for time() */
8 #include <unistd.h> /* for unlink(), getopt(), optarg */
9 #include <stdint.h> /* for uint8_t */
10 #include <errno.h> /* for errno */
11 #include "windows.h" /* for structs WinMeta, Win, init_win(), init_win_meta(),
12                       * draw_all_wins()
13                       */
14 #include "draw_wins.h" /* for draw_keys_win(), draw_map_win(), draw_info_win(),
15                         * draw_log_win()
16                         */
17 #include "keybindings.h" /* for initkeybindings(), get_action_key() */
18 #include "readwrite.h" /* for [read/write]_uint[8/16/32][_bigendian]() */
19 #include "map_objects.h" /* for structs Monster, Item, Player,
20                           * init_map_object_defs(), read_map_objects(),
21                           * build_map_objects()
22                           */
23 #include "map_object_actions.h" /* for player_wait(), move_player() */
24 #include "map.h" /* for struct Map, init_map() */
25 #include "misc.h" /* for update_log(), toggle_window(), find_passable_pos(),
26                    * meta_keys(), save_game()
27                    */
28 #include "yx_uint16.h" /* for dir enum */
29 #include "rrand.h" /* for rrand(), rrand_seed() */
30 #include "rexit.h" /* for exit_game() */
31
32 int main(int argc, char *argv[])
33 {
34     struct World world;
35     char * recordfile = "record";
36     char * savefile = "savefile";
37     char * err_x = "A file 'record' exists, but no 'savefile'. If everything "
38                    "was in order, both or none would exist. I won't start "
39                    "until this is corrected.";
40     if (!access(recordfile, F_OK) && access(savefile, F_OK))
41     {
42         errno = 0;
43         exit_err(1, &world, err_x);
44     }
45     err_x        = "A 'savefile' exists, but no file 'record'. If everything "
46                    "was in order, both or none would exist. I won't start "
47                    "until this is corrected.";
48
49     if (!access(savefile, F_OK) && access(recordfile, F_OK))
50     {
51         errno = 0;
52         exit_err(1, &world, err_x);
53     }
54     char * recordfile_tmp = "record_tmp";
55     char * savefile_tmp   = "savefile_tmp";
56     err_x        = "A file 'recordfile_tmp' exists, probably from a corrupted "
57                    "previous record saving process. To avoid game record "
58                    "corruption, I won't start until it is removed or renamed.";
59     exit_err(!access(recordfile_tmp, F_OK), &world, err_x);
60     err_x        = "A file 'savefile_tmp' exists, probably from a corrupted "
61                    "previous game saving process. To avoid savegame "
62                    "corruption, I won't start until it is removed or renamed.";
63     exit_err(!access(savefile_tmp,   F_OK), &world, err_x);
64
65     /* Read in startup options (i.e. replay option and replay start turn). */
66     int opt;
67     uint32_t start_turn;
68     world.interactive = 1;
69     while ((opt = getopt(argc, argv, "s::")) != -1)
70     {
71         switch (opt)
72         {
73             case 's':
74                 world.interactive = 0;
75                 start_turn = 0;
76                 if (optarg)
77                     start_turn = atoi(optarg);
78                  break;
79             default:
80                 exit(EXIT_FAILURE);
81         }
82     }
83
84     /* Initialize log, player, monster/item definitions and monsters/items. */
85     world.log = calloc(1, sizeof(char));
86     set_cleanup_flag(CLEANUP_LOG);
87     update_log (&world, " ");
88     struct Player player;
89     player.hitpoints = 5;
90     world.player = &player;
91     world.monster = 0;
92     world.item = 0;
93     init_map_object_defs(&world, "defs");
94
95     /* For interactive mode, try to load world state from savefile. */
96     char * err_o = "Trouble loading game (fopen() in main()) / "
97                    "opening 'savefile' for reading.";
98     char * err_r = "Trouble loading game (in main()) / "
99                    "reading from opened 'savefile'.";
100     char * err_c = "Trouble loading game (fclose() in main()) / "
101                    "closing opened 'savefile'.";
102     FILE * file;
103     if (1 == world.interactive && 0 == access(savefile, F_OK))
104     {
105         file = fopen(savefile, "r");
106         exit_err(0 == file, &world, err_o);
107         if (   read_uint32_bigendian(file, &world.seed)
108             || read_uint32_bigendian(file, &world.turn)
109             || read_uint16_bigendian(file, &player.pos.y)
110             || read_uint16_bigendian(file, &player.pos.x)
111             || read_uint8(file, &player.hitpoints)
112             || read_map_objects(&world, &world.monster, file)
113             || read_map_objects(&world, &world.item,    file))
114         {
115             exit_err(1, &world, err_r);
116         }
117         exit_err(fclose(file), &world, err_c);
118         player.pos.y--;
119         player.pos.x--;
120     }
121
122     /* For non-interactive mode, try to load world state from record file. */
123     else
124     {
125         err_o = "Trouble loading record file (fopen() in main()) / "
126                 "opening file 'record' for reading.";
127         err_r = "Trouble loading record file (read_uint32_bigendian() in "
128                 "main()) / reading from opened file 'record'.";
129         world.turn = 1;
130         if (0 == world.interactive)
131         {
132             file = fopen(recordfile, "r");
133             exit_err(0 == file, &world, err_o);
134             exit_err(read_uint32_bigendian(file, &world.seed), &world, err_r);
135         }
136
137         /* For interactive-mode in newly started world, generate a start seed
138          * from the current time.
139          */
140         else
141         {
142             world.seed = time(NULL);
143
144             err_o        = "Trouble recording new seed (fopen() in main()) / "
145                            "opening 'record_tmp' file for writing.";
146             char * err_w = "Trouble recording new seed "
147                            "(write_uint32_bigendian() in main()) / writing to "
148                            "opened file 'record_tmp'.";
149             err_c        = "Trouble recording new seed (fclose() in main()) / "
150                            "closing opened file 'record_tmp'.";
151             char * err_m = "Trouble recording new seed (rename() in main()) : "
152                            "renaming file 'record_tmp' to 'record'.";
153             file = fopen(recordfile_tmp, "w");
154             exit_err(0 == file, &world, err_o);
155             exit_err(write_uint32_bigendian(world.seed, file), &world, err_w);
156             exit_err(fclose(file), &world, err_c);
157             exit_err(rename(recordfile_tmp, recordfile), &world, err_m);
158         }
159     }
160
161
162     /* Generate map from seed and, if newly generated world, start positions of
163      * actors.
164      */
165     rrand_seed(world.seed);
166     struct Map map = init_map();
167     world.map = &map;
168     set_cleanup_flag(CLEANUP_MAP);
169     if (1 == world.turn)
170     {
171         player.pos = find_passable_pos(world.map);
172         void * foo;
173         foo = build_map_objects(&world, &world.monster, 1, 1 + rrand() % 27);
174         foo = build_map_objects(&world, foo, 2, 1 + rrand() % 9);
175         build_map_objects(&world, foo, 3, 1 + rrand() % 3);
176         foo = build_map_objects(&world, &world.item, 4, 1 + rrand() % 3);
177         build_map_objects(&world, foo, 5, 1 + rrand() % 3);
178     }
179
180     /* Initialize window system and windows. */
181     WINDOW * screen = initscr();
182     set_cleanup_flag(CLEANUP_NCURSES);
183     noecho();
184     curs_set(0);
185     keypad(screen, TRUE);
186     raw();
187     init_keybindings(&world);
188     set_cleanup_flag(CLEANUP_KEYBINDINGS);
189     struct WinMeta win_meta;
190     char * err_winmem = "Trouble with init_win() or draw_all_wins() in main().";
191     exit_err(init_win_meta(screen, &win_meta), &world, err_winmem);
192     struct Win win_keys = init_win(&win_meta, "Keys",
193                                    0, 29, &world, draw_keys_win);
194     struct Win win_info = init_win(&win_meta, "Info",
195                                    2, 20, &world, draw_info_win);
196     uint16_t height_logwin = win_meta.padframe.size.y
197                              - (2 + win_info.frame.size.y);
198     struct Win win_log = init_win(&win_meta, "Log",
199                                   height_logwin, 20, &world, draw_log_win);
200     uint16_t width_mapwin = win_meta.padframe.size.x - win_keys.frame.size.x
201                              - win_log.frame.size.x - 2;
202     struct Win win_map = init_win(&win_meta, "Map",
203                                   0, width_mapwin, &world, draw_map_win);
204     toggle_window(&win_meta, &win_keys);
205     toggle_window(&win_meta, &win_map);
206     toggle_window(&win_meta, &win_info);
207     toggle_window(&win_meta, &win_log);
208
209     /* Replay mode. */
210     int key;
211     uint8_t quit_called = 0;
212     uint8_t await_actions = 1;
213     if (0 == world.interactive)
214     {
215         int action;
216         while (1)
217         {
218             if (start_turn == world.turn)
219             {
220                 start_turn = 0;
221             }
222             if (0 == start_turn)
223             {
224                 exit_err(draw_all_wins(&win_meta), &world, err_winmem);
225                 key = getch();
226             }
227             if (1 == await_actions
228                 && (world.turn < start_turn
229                     || key == get_action_key(world.keybindings,
230                                              "wait / next turn")) )
231             {
232                 action = getc(file);
233                 if (EOF == action)
234                 {
235                     start_turn = 0;
236                     await_actions = 0;
237                 }
238                 else if (0 == action)
239                 {
240                     player_wait (&world);
241                 }
242                 else if (NORTH == action)
243                 {
244                     move_player(&world, NORTH);
245                 }
246                 else if (EAST  == action)
247                 {
248                     move_player(&world, EAST);
249                 }
250                 else if (SOUTH == action)
251                 {
252                     move_player(&world, SOUTH);
253                 }
254                 else if (WEST == action)
255                 {
256                     move_player(&world, WEST);
257                 }
258             }
259             else
260             {
261                 quit_called = meta_keys(key, &world, &win_meta, &win_keys,
262                                              &win_map, &win_info, &win_log);
263                 if (1 == quit_called)
264                 {
265                     err_c = "Trouble closing 'record' file (fclose() in "
266                             "main()).";
267                     exit_err(fclose(file), &world, err_c);
268                     exit_game(&world);
269                 }
270             }
271         }
272     }
273
274     /* Interactive mode. */
275     else
276     {
277         uint32_t last_turn = 0;
278         while (1)
279         {
280             if (last_turn != world.turn)
281             {
282                 save_game(&world);
283                 last_turn = world.turn;
284             }
285             if (1 == await_actions && 0 == player.hitpoints)
286             {
287                 await_actions = 0;
288             }
289             draw_all_wins (&win_meta);
290             key = getch();
291             if      (1 == await_actions
292                      && key == get_action_key(world.keybindings,
293                                               "player up"))
294             {
295                 move_player(&world, NORTH);
296             }
297             else if (1 == await_actions
298                      && key == get_action_key(world.keybindings,
299                                               "player right"))
300             {
301                 move_player(&world, EAST);
302             }
303             else if (1 == await_actions
304                      && key == get_action_key(world.keybindings,
305                                               "player down"))
306             {
307                 move_player(&world, SOUTH);
308             }
309             else if (1 == await_actions
310                      && key == get_action_key(world.keybindings,
311                                               "player left"))
312             {
313                 move_player(&world, WEST);
314             }
315             else if (1 == await_actions
316                      && key == get_action_key(world.keybindings,
317                                               "wait / next turn"))
318             {
319                 player_wait (&world);
320             }
321             else
322             {
323                 quit_called = meta_keys(key, &world, &win_meta, &win_keys,
324                                              &win_map, &win_info, &win_log);
325                 if (1 == quit_called)
326                 {
327                     exit_game(&world);
328                 }
329             }
330         }
331     }
332 }