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