home · contact · privacy
Fixed bug that corrupted record files.
[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, &world.score)
110             || read_uint16_bigendian(file, &player.pos.y)
111             || read_uint16_bigendian(file, &player.pos.x)
112             || read_uint8(file, &player.hitpoints)
113             || read_map_objects(&world, &world.monster, file)
114             || read_map_objects(&world, &world.item,    file))
115         {
116             exit_err(1, &world, err_r);
117         }
118         exit_err(fclose(file), &world, err_c);
119         player.pos.y--;
120         player.pos.x--;
121     }
122
123     /* For non-interactive mode, try to load world state from record file. */
124     else
125     {
126         err_o = "Trouble loading record file (fopen() in main()) / "
127                 "opening file 'record' for reading.";
128         err_r = "Trouble loading record file (read_uint32_bigendian() in "
129                 "main()) / reading from opened file 'record'.";
130         world.turn = 1;
131         if (0 == world.interactive)
132         {
133             file = fopen(recordfile, "r");
134             exit_err(NULL == file, &world, err_o);
135             exit_err(read_uint32_bigendian(file, &world.seed), &world, err_r);
136         }
137
138         /* For interactive-mode in newly started world, generate a start seed
139          * from the current time.
140          */
141         else
142         {
143             world.seed = time(NULL);
144             world.score = 0;
145
146             err_o        = "Trouble recording new seed (fopen() in main()) / "
147                            "opening 'record_tmp' file for writing.";
148             char * err_w = "Trouble recording new seed "
149                            "(write_uint32_bigendian() in main()) / writing to "
150                            "opened file 'record_tmp'.";
151             err_c        = "Trouble recording new seed (fclose() in main()) / "
152                            "closing opened file 'record_tmp'.";
153             char * err_m = "Trouble recording new seed (rename() in main()) : "
154                            "renaming file 'record_tmp' to 'record'.";
155             file = fopen(recordfile_tmp, "w");
156             exit_err(0 == file, &world, err_o);
157             exit_err(write_uint32_bigendian(world.seed, file), &world, err_w);
158             exit_err(fclose(file), &world, err_c);
159             exit_err(rename(recordfile_tmp, recordfile), &world, err_m);
160         }
161     }
162
163
164     /* Generate map from seed and, if newly generated world, start positions of
165      * actors.
166      */
167     rrand_seed(world.seed);
168     struct Map map = init_map();
169     world.map = &map;
170     set_cleanup_flag(CLEANUP_MAP);
171     if (1 == world.turn)
172     {
173         player.pos = find_passable_pos(world.map);
174         void * foo;
175         foo = build_map_objects(&world, &world.monster, 1, 1 + rrand() % 27);
176         foo = build_map_objects(&world, foo, 2, 1 + rrand() % 9);
177         build_map_objects(&world, foo, 3, 1 + rrand() % 3);
178         foo = build_map_objects(&world, &world.item, 4, 1 + rrand() % 3);
179         build_map_objects(&world, foo, 5, 1 + rrand() % 3);
180     }
181
182     /* Initialize window system and windows. */
183     WINDOW * screen = initscr();
184     set_cleanup_flag(CLEANUP_NCURSES);
185     noecho();
186     curs_set(0);
187     keypad(screen, TRUE);
188     raw();
189     init_keybindings(&world);
190     set_cleanup_flag(CLEANUP_KEYBINDINGS);
191     struct WinMeta win_meta;
192     char * err_winmem = "Trouble with init_win() or draw_all_wins() in main().";
193     exit_err(init_win_meta(screen, &win_meta), &world, err_winmem);
194     struct Win win_keys = init_win(&win_meta, "Keys",
195                                    0, 29, &world, draw_keys_win);
196     struct Win win_info = init_win(&win_meta, "Info",
197                                    3, 20, &world, draw_info_win);
198     uint16_t height_logwin = win_meta.padframe.size.y
199                              - (2 + win_info.frame.size.y);
200     struct Win win_log = init_win(&win_meta, "Log",
201                                   height_logwin, 20, &world, draw_log_win);
202     uint16_t width_mapwin = win_meta.padframe.size.x - win_keys.frame.size.x
203                              - win_log.frame.size.x - 2;
204     struct Win win_map = init_win(&win_meta, "Map",
205                                   0, width_mapwin, &world, draw_map_win);
206     toggle_window(&win_meta, &win_keys);
207     toggle_window(&win_meta, &win_map);
208     toggle_window(&win_meta, &win_info);
209     toggle_window(&win_meta, &win_log);
210
211     /* Replay mode. */
212     int key;
213     uint8_t quit_called = 0;
214     uint8_t await_actions = 1;
215     if (0 == world.interactive)
216     {
217         int action;
218         while (1)
219         {
220             if (start_turn == world.turn)
221             {
222                 start_turn = 0;
223             }
224             if (0 == start_turn)
225             {
226                 exit_err(draw_all_wins(&win_meta), &world, err_winmem);
227                 key = getch();
228             }
229             if (1 == await_actions
230                 && (world.turn < start_turn
231                     || key == get_action_key(world.keybindings,
232                                              "wait / next turn")) )
233             {
234                 action = getc(file);
235                 if (EOF == action)
236                 {
237                     start_turn = 0;
238                     await_actions = 0;
239                 }
240                 else if (0 == action)
241                 {
242                     player_wait (&world);
243                 }
244                 else if (NORTH == action)
245                 {
246                     move_player(&world, NORTH);
247                 }
248                 else if (EAST  == action)
249                 {
250                     move_player(&world, EAST);
251                 }
252                 else if (SOUTH == action)
253                 {
254                     move_player(&world, SOUTH);
255                 }
256                 else if (WEST == action)
257                 {
258                     move_player(&world, WEST);
259                 }
260             }
261             else
262             {
263                 quit_called = meta_keys(key, &world, &win_meta, &win_keys,
264                                              &win_map, &win_info, &win_log);
265                 if (1 == quit_called)
266                 {
267                     err_c = "Trouble closing 'record' file (fclose() in "
268                             "main()).";
269                     exit_err(fclose(file), &world, err_c);
270                     exit_game(&world);
271                 }
272             }
273         }
274     }
275
276     /* Interactive mode. */
277     else
278     {
279         uint32_t last_turn = 0;
280         while (1)
281         {
282             if (last_turn != world.turn)
283             {
284                 save_game(&world);
285                 last_turn = world.turn;
286             }
287             if (1 == await_actions && 0 == player.hitpoints)
288             {
289                 await_actions = 0;
290             }
291             draw_all_wins (&win_meta);
292             key = getch();
293             if      (1 == await_actions
294                      && key == get_action_key(world.keybindings,
295                                               "player up"))
296             {
297                 move_player(&world, NORTH);
298             }
299             else if (1 == await_actions
300                      && key == get_action_key(world.keybindings,
301                                               "player right"))
302             {
303                 move_player(&world, EAST);
304             }
305             else if (1 == await_actions
306                      && key == get_action_key(world.keybindings,
307                                               "player down"))
308             {
309                 move_player(&world, SOUTH);
310             }
311             else if (1 == await_actions
312                      && key == get_action_key(world.keybindings,
313                                               "player left"))
314             {
315                 move_player(&world, WEST);
316             }
317             else if (1 == await_actions
318                      && key == get_action_key(world.keybindings,
319                                               "wait / next turn"))
320             {
321                 player_wait (&world);
322             }
323             else
324             {
325                 quit_called = meta_keys(key, &world, &win_meta, &win_keys,
326                                              &win_map, &win_info, &win_log);
327                 if (1 == quit_called)
328                 {
329                     exit_game(&world);
330                 }
331             }
332         }
333     }
334 }