Simplify the signature of savefile().
[open-adventure.git] / main.c
1 /*
2  * SPDX-FileCopyrightText: 1977, 2005 by Will Crowther and Don Woods
3  * SPDX-FileCopyrightText: 2017 by Eric S. Raymond
4  * SPDX-License-Identifier: BSD-2-Clause
5  */
6
7 #include <stdlib.h>
8 #include <stdio.h>
9 #include <stdbool.h>
10 #include <getopt.h>
11 #include <signal.h>
12 #include <string.h>
13 #include <ctype.h>
14 #include <unistd.h>
15 #include <editline/readline.h>
16 #include "advent.h"
17 #include "dungeon.h"
18
19 #define DIM(a) (sizeof(a)/sizeof(a[0]))
20
21 #if defined ADVENT_AUTOSAVE
22 static FILE* autosave_fp;
23 void autosave(void)
24 {
25     if (autosave_fp != NULL) {
26         rewind(autosave_fp);
27         savefile(autosave_fp);
28         fflush(autosave_fp);
29     }
30 }
31 #endif
32
33 // LCOV_EXCL_START
34 // exclude from coverage analysis because it requires interactivity to test
35 static void sig_handler(int signo)
36 {
37     if (signo == SIGINT) {
38         if (settings.logfp != NULL)
39             fflush(settings.logfp);
40     }
41
42 #if defined ADVENT_AUTOSAVE
43     if (signo == SIGHUP || signo == SIGTERM)
44         autosave();
45 #endif
46     exit(EXIT_FAILURE);
47 }
48 // LCOV_EXCL_STOP
49
50 char *myreadline(const char *prompt)
51 {
52     /*
53      * This function isn't required for gameplay, readline() straight
54      * up would suffice for that.  It's where we interpret command-line
55      * logfiles for testing purposes.
56      */
57     /* Normal case - no script arguments */
58     if (settings.argc == 0) {
59         char *ln = readline(prompt);
60         if (ln == NULL) {
61             fputs(prompt, stdout);
62         }
63         return ln;
64     }
65
66     char *buf = malloc(LINESIZE + 1);
67     for (;;) {
68         if (settings.scriptfp == NULL || feof(settings.scriptfp)) {
69             if (settings.optind >= settings.argc) {
70                 free(buf);
71                 return NULL;
72             }
73
74             char *next = settings.argv[settings.optind++];
75
76             if (settings.scriptfp != NULL && feof(settings.scriptfp))
77                 fclose(settings.scriptfp);
78             if (strcmp(next, "-") == 0)
79                 settings.scriptfp = stdin; // LCOV_EXCL_LINE
80             else
81                 settings.scriptfp = fopen(next, "r");
82         }
83
84         if (isatty(fileno(settings.scriptfp))) {
85             free(buf); // LCOV_EXCL_LINE
86             return readline(prompt); // LCOV_EXCL_LINE
87         } else {
88             char *ln = fgets(buf, LINESIZE, settings.scriptfp);
89             if (ln != NULL) {
90                 fputs(prompt, stdout);
91                 fputs(ln, stdout);
92                 return ln;
93             }
94         }
95     }
96
97     return NULL;
98 }
99
100 /*  Check if this loc is eligible for any hints.  If been here int
101  *  enough, display.  Ignore "HINTS" < 4 (special stuff, see database
102  *  notes). */
103 static void checkhints(void)
104 {
105     if (conditions[game.loc] >= game.conds) {
106         for (int hint = 0; hint < NHINTS; hint++) {
107             if (game.hinted[hint])
108                 continue;
109             if (!CNDBIT(game.loc, hint + 1 + COND_HBASE))
110                 game.hintlc[hint] = -1;
111             ++game.hintlc[hint];
112             /*  Come here if he's been int enough at required loc(s) for some
113              *  unused hint. */
114             if (game.hintlc[hint] >= hints[hint].turns) {
115                 int i;
116
117                 switch (hint) {
118                 case 0:
119                     /* cave */
120                     if (game.prop[GRATE] == GRATE_CLOSED && !HERE(KEYS))
121                         break;
122                     game.hintlc[hint] = 0;
123                     return;
124                 case 1: /* bird */
125                     if (game.place[BIRD] == game.loc && TOTING(ROD) && game.oldobj == BIRD)
126                         break;
127                     return;
128                 case 2: /* snake */
129                     if (HERE(SNAKE) && !HERE(BIRD))
130                         break;
131                     game.hintlc[hint] = 0;
132                     return;
133                 case 3: /* maze */
134                     if (game.atloc[game.loc] == NO_OBJECT &&
135                         game.atloc[game.oldloc] == NO_OBJECT &&
136                         game.atloc[game.oldlc2] == NO_OBJECT &&
137                         game.holdng > 1)
138                         break;
139                     game.hintlc[hint] = 0;
140                     return;
141                 case 4: /* dark */
142                     if (game.prop[EMERALD] != STATE_NOTFOUND && game.prop[PYRAMID] == STATE_NOTFOUND)
143                         break;
144                     game.hintlc[hint] = 0;
145                     return;
146                 case 5: /* witt */
147                     break;
148                 case 6: /* urn */
149                     if (game.dflag == 0)
150                         break;
151                     game.hintlc[hint] = 0;
152                     return;
153                 case 7: /* woods */
154                     if (game.atloc[game.loc] == NO_OBJECT &&
155                         game.atloc[game.oldloc] == NO_OBJECT &&
156                         game.atloc[game.oldlc2] == NO_OBJECT)
157                         break;
158                     return;
159                 case 8: /* ogre */
160                     i = atdwrf(game.loc);
161                     if (i < 0) {
162                         game.hintlc[hint] = 0;
163                         return;
164                     }
165                     if (HERE(OGRE) && i == 0)
166                         break;
167                     return;
168                 case 9: /* jade */
169                     if (game.tally == 1 && game.prop[JADE] < 0)
170                         break;
171                     game.hintlc[hint] = 0;
172                     return;
173                 default: // LCOV_EXCL_LINE
174                     // Should never happen
175                     BUG(HINT_NUMBER_EXCEEDS_GOTO_LIST); // LCOV_EXCL_LINE
176                 }
177
178                 /* Fall through to hint display */
179                 game.hintlc[hint] = 0;
180                 if (!yes_or_no(hints[hint].question, arbitrary_messages[NO_MESSAGE], arbitrary_messages[OK_MAN]))
181                     return;
182                 rspeak(HINT_COST, hints[hint].penalty, hints[hint].penalty);
183                 game.hinted[hint] = yes_or_no(arbitrary_messages[WANT_HINT], hints[hint].hint, arbitrary_messages[OK_MAN]);
184                 if (game.hinted[hint] && game.limit > WARNTIME)
185                     game.limit += WARNTIME * hints[hint].penalty;
186             }
187         }
188     }
189 }
190
191 static bool spotted_by_pirate(int i)
192 {
193     if (i != PIRATE)
194         return false;
195
196     /*  The pirate's spotted him.  Pirate leaves him alone once we've
197      *  found chest.  K counts if a treasure is here.  If not, and
198      *  tally=1 for an unseen chest, let the pirate be spotted.  Note
199      *  that game.place[CHEST] = LOC_NOWHERE might mean that he's thrown
200      *  it to the troll, but in that case he's seen the chest
201      *  (game.prop[CHEST] == STATE_FOUND). */
202     if (game.loc == game.chloc ||
203         game.prop[CHEST] != STATE_NOTFOUND)
204         return true;
205     int snarfed = 0;
206     bool movechest = false, robplayer = false;
207     for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
208         if (!objects[treasure].is_treasure)
209             continue;
210         /*  Pirate won't take pyramid from plover room or dark
211          *  room (too easy!). */
212         if (treasure == PYRAMID && (game.loc == objects[PYRAMID].plac ||
213                                     game.loc == objects[EMERALD].plac)) {
214             continue;
215         }
216         if (TOTING(treasure) ||
217             HERE(treasure))
218             ++snarfed;
219         if (TOTING(treasure)) {
220             movechest = true;
221             robplayer = true;
222         }
223     }
224     /* Force chest placement before player finds last treasure */
225     if (game.tally == 1 && snarfed == 0 && game.place[CHEST] == LOC_NOWHERE && HERE(LAMP) && game.prop[LAMP] == LAMP_BRIGHT) {
226         rspeak(PIRATE_SPOTTED);
227         movechest = true;
228     }
229     /* Do things in this order (chest move before robbery) so chest is listed
230      * last at the maze location. */
231     if (movechest) {
232         move(CHEST, game.chloc);
233         move(MESSAG, game.chloc2);
234         game.dloc[PIRATE] = game.chloc;
235         game.odloc[PIRATE] = game.chloc;
236         game.dseen[PIRATE] = false;
237     } else {
238         /* You might get a hint of the pirate's presence even if the
239          * chest doesn't move... */
240         if (game.odloc[PIRATE] != game.dloc[PIRATE] && PCT(20))
241             rspeak(PIRATE_RUSTLES);
242     }
243     if (robplayer) {
244         rspeak(PIRATE_POUNCES);
245         for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
246             if (!objects[treasure].is_treasure)
247                 continue;
248             if (!(treasure == PYRAMID && (game.loc == objects[PYRAMID].plac ||
249                                           game.loc == objects[EMERALD].plac))) {
250                 if (AT(treasure) && game.fixed[treasure] == IS_FREE)
251                     carry(treasure, game.loc);
252                 if (TOTING(treasure))
253                     drop(treasure, game.chloc);
254             }
255         }
256     }
257
258     return true;
259 }
260
261 static bool dwarfmove(void)
262 /* Dwarves move.  Return true if player survives, false if he dies. */
263 {
264     int kk, stick, attack;
265     loc_t tk[21];
266
267     /*  Dwarf stuff.  See earlier comments for description of
268      *  variables.  Remember sixth dwarf is pirate and is thus
269      *  very different except for motion rules. */
270
271     /*  First off, don't let the dwarves follow him into a pit or a
272      *  wall.  Activate the whole mess the first time he gets as far
273      *  as the Hall of Mists (what INDEEP() tests).  If game.newloc
274      *  is forbidden to pirate (in particular, if it's beyond the
275      *  troll bridge), bypass dwarf stuff.  That way pirate can't
276      *  steal return toll, and dwarves can't meet the bear.  Also
277      *  means dwarves won't follow him into dead end in maze, but
278      *  c'est la vie.  They'll wait for him outside the dead end. */
279     if (game.loc == LOC_NOWHERE ||
280         FORCED(game.loc) ||
281         CNDBIT(game.newloc, COND_NOARRR))
282         return true;
283
284     /* Dwarf activity level ratchets up */
285     if (game.dflag == 0) {
286         if (INDEEP(game.loc))
287             game.dflag = 1;
288         return true;
289     }
290
291     /*  When we encounter the first dwarf, we kill 0, 1, or 2 of
292      *  the 5 dwarves.  If any of the survivors is at game.loc,
293      *  replace him with the alternate. */
294     if (game.dflag == 1) {
295         if (!INDEEP(game.loc) ||
296             (PCT(95) && (!CNDBIT(game.loc, COND_NOBACK) ||
297                          PCT(85))))
298             return true;
299         game.dflag = 2;
300         for (int i = 1; i <= 2; i++) {
301             int j = 1 + randrange(NDWARVES - 1);
302             if (PCT(50))
303                 game.dloc[j] = 0;
304         }
305
306         /* Alternate initial loc for dwarf, in case one of them
307         *  starts out on top of the adventurer. */
308         for (int i = 1; i <= NDWARVES - 1; i++) {
309             if (game.dloc[i] == game.loc)
310                 game.dloc[i] = DALTLC; //
311             game.odloc[i] = game.dloc[i];
312         }
313         rspeak(DWARF_RAN);
314         drop(AXE, game.loc);
315         return true;
316     }
317
318     /*  Things are in full swing.  Move each dwarf at random,
319      *  except if he's seen us he sticks with us.  Dwarves stay
320      *  deep inside.  If wandering at random, they don't back up
321      *  unless there's no alternative.  If they don't have to
322      *  move, they attack.  And, of course, dead dwarves don't do
323      *  much of anything. */
324     game.dtotal = 0;
325     attack = 0;
326     stick = 0;
327     for (int i = 1; i <= NDWARVES; i++) {
328         if (game.dloc[i] == 0)
329             continue;
330         /*  Fill tk array with all the places this dwarf might go. */
331         unsigned int j = 1;
332         kk = tkey[game.dloc[i]];
333         if (kk != 0)
334             do {
335                 enum desttype_t desttype = travel[kk].desttype;
336                 game.newloc = travel[kk].destval;
337                 /* Have we avoided a dwarf encounter? */
338                 if (desttype != dest_goto)
339                     continue;
340                 else if (!INDEEP(game.newloc))
341                     continue;
342                 else if (game.newloc == game.odloc[i])
343                     continue;
344                 else if (j > 1 && game.newloc == tk[j - 1])
345                     continue;
346                 else if (j >= DIM(tk) - 1)
347                     /* This can't actually happen. */
348                     continue; // LCOV_EXCL_LINE
349                 else if (game.newloc == game.dloc[i])
350                     continue;
351                 else if (FORCED(game.newloc))
352                     continue;
353                 else if (i == PIRATE && CNDBIT(game.newloc, COND_NOARRR))
354                     continue;
355                 else if (travel[kk].nodwarves)
356                     continue;
357                 tk[j++] = game.newloc;
358             } while
359             (!travel[kk++].stop);
360         tk[j] = game.odloc[i];
361         if (j >= 2)
362             --j;
363         j = 1 + randrange(j);
364         game.odloc[i] = game.dloc[i];
365         game.dloc[i] = tk[j];
366         game.dseen[i] = (game.dseen[i] && INDEEP(game.loc)) ||
367                         (game.dloc[i] == game.loc ||
368                          game.odloc[i] == game.loc);
369         if (!game.dseen[i])
370             continue;
371         game.dloc[i] = game.loc;
372         if (spotted_by_pirate(i))
373             continue;
374         /* This threatening little dwarf is in the room with him! */
375         ++game.dtotal;
376         if (game.odloc[i] == game.dloc[i]) {
377             ++attack;
378             if (game.knfloc >= 0)
379                 game.knfloc = game.loc;
380             if (randrange(1000) < 95 * (game.dflag - 2))
381                 ++stick;
382         }
383     }
384
385     /*  Now we know what's happening.  Let's tell the poor sucker about it. */
386     if (game.dtotal == 0)
387         return true;
388     rspeak(game.dtotal == 1 ? DWARF_SINGLE : DWARF_PACK, game.dtotal);
389     if (attack == 0)
390         return true;
391     if (game.dflag == 2)
392         game.dflag = 3;
393     if (attack > 1) {
394         rspeak(THROWN_KNIVES, attack);
395         rspeak(stick > 1 ? MULTIPLE_HITS : (stick == 1 ? ONE_HIT : NONE_HIT), stick);
396     } else {
397         rspeak(KNIFE_THROWN);
398         rspeak(stick ? GETS_YOU : MISSES_YOU);
399     }
400     if (stick == 0)
401         return true;
402     game.oldlc2 = game.loc;
403     return false;
404 }
405
406 /*  "You're dead, Jim."
407  *
408  *  If the current loc is zero, it means the clown got himself killed.
409  *  We'll allow this maxdie times.  NDEATHS is automatically set based
410  *  on the number of snide messages available.  Each death results in
411  *  a message (obituaries[n]) which offers reincarnation; if accepted,
412  *  this results in message obituaries[0], obituaries[2], etc.  The
413  *  last time, if he wants another chance, he gets a snide remark as
414  *  we exit.  When reincarnated, all objects being carried get dropped
415  *  at game.oldlc2 (presumably the last place prior to being killed)
416  *  without change of props.  The loop runs backwards to assure that
417  *  the bird is dropped before the cage.  (This kluge could be changed
418  *  once we're sure all references to bird and cage are done by
419  *  keywords.)  The lamp is a special case (it wouldn't do to leave it
420  *  in the cave). It is turned off and left outside the building (only
421  *  if he was carrying it, of course).  He himself is left inside the
422  *  building (and heaven help him if he tries to xyzzy back into the
423  *  cave without the lamp!).  game.oldloc is zapped so he can't just
424  *  "retreat". */
425 static void croak(void)
426 /*  Okay, he's dead.  Let's get on with it. */
427 {
428     const char* query = obituaries[game.numdie].query;
429     const char* yes_response = obituaries[game.numdie].yes_response;
430
431     ++game.numdie;
432
433     if (game.closng) {
434         /*  He died during closing time.  No resurrection.  Tally up a
435          *  death and exit. */
436         rspeak(DEATH_CLOSING);
437         terminate(endgame);
438     } else if (!yes_or_no(query, yes_response, arbitrary_messages[OK_MAN])
439                || game.numdie == NDEATHS) {
440         /* Player is asked if he wants to try again. If not, or if
441          * he's already used all of his lives, we end the game */
442         terminate(endgame);
443     } else {
444         /* If player wishes to continue, we empty the liquids in the
445          * user's inventory, turn off the lamp, and drop all items
446          * where he died. */
447         game.place[WATER] = game.place[OIL] = LOC_NOWHERE;
448         if (TOTING(LAMP))
449             game.prop[LAMP] = LAMP_DARK;
450         for (int j = 1; j <= NOBJECTS; j++) {
451             int i = NOBJECTS + 1 - j;
452             if (TOTING(i)) {
453                 /* Always leave lamp where it's accessible aboveground */
454                 drop(i, (i == LAMP) ? LOC_START : game.oldlc2);
455             }
456         }
457         game.oldloc = game.loc = game.newloc = LOC_BUILDING;
458     }
459 }
460
461 static void describe_location(void)
462 /* Describe the location to the user */
463 {
464     const char* msg = locations[game.loc].description.small;
465
466     if (MOD(game.abbrev[game.loc], game.abbnum) == 0 || msg == NO_MESSAGE)
467         msg = locations[game.loc].description.big;
468
469     if (!FORCED(game.loc) && DARK(game.loc)) {
470         msg = arbitrary_messages[PITCH_DARK];
471     }
472
473     if (TOTING(BEAR))
474         rspeak(TAME_BEAR);
475
476     speak(msg);
477
478     if (game.loc == LOC_Y2 && PCT(25) && !game.closng)
479         rspeak(SAYS_PLUGH);
480 }
481
482
483 static bool traveleq(int a, int b)
484 /* Are two travel entries equal for purposes of skip after failed condition? */
485 {
486     return (travel[a].condtype == travel[b].condtype)
487            && (travel[a].condarg1 == travel[b].condarg1)
488            && (travel[a].condarg2 == travel[b].condarg2)
489            && (travel[a].desttype == travel[b].desttype)
490            && (travel[a].destval == travel[b].destval);
491 }
492
493 /*  Given the current location in "game.loc", and a motion verb number in
494  *  "motion", put the new location in "game.newloc".  The current loc is saved
495  *  in "game.oldloc" in case he wants to retreat.  The current
496  *  game.oldloc is saved in game.oldlc2, in case he dies.  (if he
497  *  does, game.newloc will be limbo, and game.oldloc will be what killed
498  *  him, so we need game.oldlc2, which is the last place he was
499  *  safe.) */
500 static void playermove(int motion)
501 {
502     int scratchloc, travel_entry = tkey[game.loc];
503     game.newloc = game.loc;
504     if (travel_entry == 0)
505         BUG(LOCATION_HAS_NO_TRAVEL_ENTRIES); // LCOV_EXCL_LINE
506     if (motion == NUL)
507         return;
508     else if (motion == BACK) {
509         /*  Handle "go back".  Look for verb which goes from game.loc to
510          *  game.oldloc, or to game.oldlc2 If game.oldloc has forced-motion.
511          *  te_tmp saves entry -> forced loc -> previous loc. */
512         motion = game.oldloc;
513         if (FORCED(motion))
514             motion = game.oldlc2;
515         game.oldlc2 = game.oldloc;
516         game.oldloc = game.loc;
517         if (CNDBIT(game.loc, COND_NOBACK)) {
518             rspeak(TWIST_TURN);
519             return;
520         }
521         if (motion == game.loc) {
522             rspeak(FORGOT_PATH);
523             return;
524         }
525
526         int te_tmp = 0;
527         for (;;) {
528             enum desttype_t desttype = travel[travel_entry].desttype;
529             scratchloc = travel[travel_entry].destval;
530             if (desttype != dest_goto || scratchloc != motion) {
531                 if (desttype == dest_goto) {
532                     if (FORCED(scratchloc) && travel[tkey[scratchloc]].destval == motion)
533                         te_tmp = travel_entry;
534                 }
535                 if (!travel[travel_entry].stop) {
536                     ++travel_entry;     /* go to next travel entry for this location */
537                     continue;
538                 }
539                 /* we've reached the end of travel entries for game.loc */
540                 travel_entry = te_tmp;
541                 if (travel_entry == 0) {
542                     rspeak(NOT_CONNECTED);
543                     return;
544                 }
545             }
546
547             motion = travel[travel_entry].motion;
548             travel_entry = tkey[game.loc];
549             break; /* fall through to ordinary travel */
550         }
551     } else if (motion == LOOK) {
552         /*  Look.  Can't give more detail.  Pretend it wasn't dark
553          *  (though it may now be dark) so he won't fall into a
554          *  pit while staring into the gloom. */
555         if (game.detail < 3)
556             rspeak(NO_MORE_DETAIL);
557         ++game.detail;
558         game.wzdark = false;
559         game.abbrev[game.loc] = 0;
560         return;
561     } else if (motion == CAVE) {
562         /*  Cave.  Different messages depending on whether above ground. */
563         rspeak((OUTSID(game.loc) && game.loc != LOC_GRATE) ? FOLLOW_STREAM : NEED_DETAIL);
564         return;
565     } else {
566         /* none of the specials */
567         game.oldlc2 = game.oldloc;
568         game.oldloc = game.loc;
569     }
570
571     /* Look for a way to fulfil the motion verb passed in - travel_entry indexes
572      * the beginning of the motion entries for here (game.loc). */
573     for (;;) {
574         if ((travel[travel_entry].motion == HERE) ||
575             travel[travel_entry].motion == motion)
576             break;
577         if (travel[travel_entry].stop) {
578             /*  Couldn't find an entry matching the motion word passed
579              *  in.  Various messages depending on word given. */
580             switch (motion) {
581             case EAST:
582             case WEST:
583             case SOUTH:
584             case NORTH:
585             case NE:
586             case NW:
587             case SW:
588             case SE:
589             case UP:
590             case DOWN:
591                 rspeak(BAD_DIRECTION);
592                 break;
593             case FORWARD:
594             case LEFT:
595             case RIGHT:
596                 rspeak(UNSURE_FACING);
597                 break;
598             case OUTSIDE:
599             case INSIDE:
600                 rspeak(NO_INOUT_HERE);
601                 break;
602             case XYZZY:
603             case PLUGH:
604                 rspeak(NOTHING_HAPPENS);
605                 break;
606             case CRAWL:
607                 rspeak(WHICH_WAY);
608                 break;
609             default:
610                 rspeak(CANT_APPLY);
611             }
612             return;
613         }
614         ++travel_entry;
615     }
616
617     /* (ESR) We've found a destination that goes with the motion verb.
618      * Next we need to check any conditional(s) on this destination, and
619      * possibly on following entries. */
620     do {
621         for (;;) { /* L12 loop */
622             for (;;) {
623                 enum condtype_t condtype = travel[travel_entry].condtype;
624                 int condarg1 = travel[travel_entry].condarg1;
625                 int condarg2 = travel[travel_entry].condarg2;
626                 if (condtype < cond_not) {
627                     /* YAML N and [pct N] conditionals */
628                     if (condtype == cond_goto || condtype == cond_pct) {
629                         if (condarg1 == 0 ||
630                             PCT(condarg1))
631                             break;
632                         /* else fall through */
633                     }
634                     /* YAML [with OBJ] clause */
635                     else if (TOTING(condarg1) ||
636                              (condtype == cond_with && AT(condarg1)))
637                         break;
638                     /* else fall through to check [not OBJ STATE] */
639                 } else if (game.prop[condarg1] != condarg2)
640                     break;
641
642                 /* We arrive here on conditional failure.
643                  * Skip to next non-matching destination */
644                 int te_tmp = travel_entry;
645                 do {
646                     if (travel[te_tmp].stop)
647                         BUG(CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION); // LCOV_EXCL_LINE
648                     ++te_tmp;
649                 } while
650                 (traveleq(travel_entry, te_tmp));
651                 travel_entry = te_tmp;
652             }
653
654             /* Found an eligible rule, now execute it */
655             enum desttype_t desttype = travel[travel_entry].desttype;
656             game.newloc = travel[travel_entry].destval;
657             if (desttype == dest_goto)
658                 return;
659
660             if (desttype == dest_speak) {
661                 /* Execute a speak rule */
662                 rspeak(game.newloc);
663                 game.newloc = game.loc;
664                 return;
665             } else {
666                 switch (game.newloc) {
667                 case 1:
668                     /* Special travel 1.  Plover-alcove passage.  Can carry only
669                      * emerald.  Note: travel table must include "useless"
670                      * entries going through passage, which can never be used
671                      * for actual motion, but can be spotted by "go back". */
672                     game.newloc = (game.loc == LOC_PLOVER)
673                                   ? LOC_ALCOVE
674                                   : LOC_PLOVER;
675                     if (game.holdng > 1 ||
676                         (game.holdng == 1 && !TOTING(EMERALD))) {
677                         game.newloc = game.loc;
678                         rspeak(MUST_DROP);
679                     }
680                     return;
681                 case 2:
682                     /* Special travel 2.  Plover transport.  Drop the
683                      * emerald (only use special travel if toting
684                      * it), so he's forced to use the plover-passage
685                      * to get it out.  Having dropped it, go back and
686                      * pretend he wasn't carrying it after all. */
687                     drop(EMERALD, game.loc);
688                     {
689                         int te_tmp = travel_entry;
690                         do {
691                             if (travel[te_tmp].stop)
692                                 BUG(CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION); // LCOV_EXCL_LINE
693                             ++te_tmp;
694                         } while
695                         (traveleq(travel_entry, te_tmp));
696                         travel_entry = te_tmp;
697                     }
698                     continue; /* goto L12 */
699                 case 3:
700                     /* Special travel 3.  Troll bridge.  Must be done
701                      * only as special motion so that dwarves won't
702                      * wander across and encounter the bear.  (They
703                      * won't follow the player there because that
704                      * region is forbidden to the pirate.)  If
705                      * game.prop[TROLL]=TROLL_PAIDONCE, he's crossed
706                      * since paying, so step out and block him.
707                      * (standard travel entries check for
708                      * game.prop[TROLL]=TROLL_UNPAID.)  Special stuff
709                      * for bear. */
710                     if (game.prop[TROLL] == TROLL_PAIDONCE) {
711                         pspeak(TROLL, look, true, TROLL_PAIDONCE);
712                         game.prop[TROLL] = TROLL_UNPAID;
713                         DESTROY(TROLL2);
714                         move(TROLL2 + NOBJECTS, IS_FREE);
715                         move(TROLL, objects[TROLL].plac);
716                         move(TROLL + NOBJECTS, objects[TROLL].fixd);
717                         juggle(CHASM);
718                         game.newloc = game.loc;
719                         return;
720                     } else {
721                         game.newloc = objects[TROLL].plac + objects[TROLL].fixd - game.loc;
722                         if (game.prop[TROLL] == TROLL_UNPAID)
723                             game.prop[TROLL] = TROLL_PAIDONCE;
724                         if (!TOTING(BEAR))
725                             return;
726                         state_change(CHASM, BRIDGE_WRECKED);
727                         game.prop[TROLL] = TROLL_GONE;
728                         drop(BEAR, game.newloc);
729                         game.fixed[BEAR] = IS_FIXED;
730                         game.prop[BEAR] = BEAR_DEAD;
731                         game.oldlc2 = game.newloc;
732                         croak();
733                         return;
734                     }
735                 default: // LCOV_EXCL_LINE
736                     BUG(SPECIAL_TRAVEL_500_GT_L_GT_300_EXCEEDS_GOTO_LIST); // LCOV_EXCL_LINE
737                 }
738             }
739             break; /* Leave L12 loop */
740         }
741     } while
742     (false);
743 }
744
745 static void lampcheck(void)
746 /* Check game limit and lamp timers */
747 {
748     if (game.prop[LAMP] == LAMP_BRIGHT)
749         --game.limit;
750
751     /*  Another way we can force an end to things is by having the
752      *  lamp give out.  When it gets close, we come here to warn him.
753      *  First following arm checks if the lamp and fresh batteries are
754      *  here, in which case we replace the batteries and continue.
755      *  Second is for other cases of lamp dying.  Even after it goes
756      *  out, he can explore outside for a while if desired. */
757     if (game.limit <= WARNTIME) {
758         if (HERE(BATTERY) && game.prop[BATTERY] == FRESH_BATTERIES && HERE(LAMP)) {
759             rspeak(REPLACE_BATTERIES);
760             game.prop[BATTERY] = DEAD_BATTERIES;
761 #ifdef __unused__
762             /* This code from the original game seems to have been faulty.
763              * No tests ever passed the guard, and with the guard removed
764              * the game hangs when the lamp limit is reached.
765              */
766             if (TOTING(BATTERY))
767                 drop(BATTERY, game.loc);
768 #endif
769             game.limit += BATTERYLIFE;
770             game.lmwarn = false;
771         } else if (!game.lmwarn && HERE(LAMP)) {
772             game.lmwarn = true;
773             if (game.prop[BATTERY] == DEAD_BATTERIES)
774                 rspeak(MISSING_BATTERIES);
775             else if (game.place[BATTERY] == LOC_NOWHERE)
776                 rspeak(LAMP_DIM);
777             else
778                 rspeak(GET_BATTERIES);
779         }
780     }
781     if (game.limit == 0) {
782         game.limit = -1;
783         game.prop[LAMP] = LAMP_DARK;
784         if (HERE(LAMP))
785             rspeak(LAMP_OUT);
786     }
787 }
788
789 static bool closecheck(void)
790 /*  Handle the closing of the cave.  The cave closes "clock1" turns
791  *  after the last treasure has been located (including the pirate's
792  *  chest, which may of course never show up).  Note that the
793  *  treasures need not have been taken yet, just located.  Hence
794  *  clock1 must be large enough to get out of the cave (it only ticks
795  *  while inside the cave).  When it hits zero, we branch to 10000 to
796  *  start closing the cave, and then sit back and wait for him to try
797  *  to get out.  If he doesn't within clock2 turns, we close the cave;
798  *  if he does try, we assume he panics, and give him a few additional
799  *  turns to get frantic before we close.  When clock2 hits zero, we
800  *  transport him into the final puzzle.  Note that the puzzle depends
801  *  upon all sorts of random things.  For instance, there must be no
802  *  water or oil, since there are beanstalks which we don't want to be
803  *  able to water, since the code can't handle it.  Also, we can have
804  *  no keys, since there is a grate (having moved the fixed object!)
805  *  there separating him from all the treasures.  Most of these
806  *  problems arise from the use of negative prop numbers to suppress
807  *  the object descriptions until he's actually moved the objects. */
808 {
809     /* If a turn threshold has been met, apply penalties and tell
810      * the player about it. */
811     for (int i = 0; i < NTHRESHOLDS; ++i) {
812         if (game.turns == turn_thresholds[i].threshold + 1) {
813             game.trnluz += turn_thresholds[i].point_loss;
814             speak(turn_thresholds[i].message);
815         }
816     }
817
818     /*  Don't tick game.clock1 unless well into cave (and not at Y2). */
819     if (game.tally == 0 && INDEEP(game.loc) && game.loc != LOC_Y2)
820         --game.clock1;
821
822     /*  When the first warning comes, we lock the grate, destroy
823      *  the bridge, kill all the dwarves (and the pirate), remove
824      *  the troll and bear (unless dead), and set "closng" to
825      *  true.  Leave the dragon; too much trouble to move it.
826      *  from now until clock2 runs out, he cannot unlock the
827      *  grate, move to any location outside the cave, or create
828      *  the bridge.  Nor can he be resurrected if he dies.  Note
829      *  that the snake is already gone, since he got to the
830      *  treasure accessible only via the hall of the mountain
831      *  king. Also, he's been in giant room (to get eggs), so we
832      *  can refer to it.  Also also, he's gotten the pearl, so we
833      *  know the bivalve is an oyster.  *And*, the dwarves must
834      *  have been activated, since we've found chest. */
835     if (game.clock1 == 0) {
836         game.prop[GRATE] = GRATE_CLOSED;
837         game.prop[FISSURE] = UNBRIDGED;
838         for (int i = 1; i <= NDWARVES; i++) {
839             game.dseen[i] = false;
840             game.dloc[i] = LOC_NOWHERE;
841         }
842         DESTROY(TROLL);
843         move(TROLL + NOBJECTS, IS_FREE);
844         move(TROLL2, objects[TROLL].plac);
845         move(TROLL2 + NOBJECTS, objects[TROLL].fixd);
846         juggle(CHASM);
847         if (game.prop[BEAR] != BEAR_DEAD)
848             DESTROY(BEAR);
849         game.prop[CHAIN] = CHAIN_HEAP;
850         game.fixed[CHAIN] = IS_FREE;
851         game.prop[AXE] = AXE_HERE;
852         game.fixed[AXE] = IS_FREE;
853         rspeak(CAVE_CLOSING);
854         game.clock1 = -1;
855         game.closng = true;
856         return game.closed;
857     } else if (game.clock1 < 0)
858         --game.clock2;
859     if (game.clock2 == 0) {
860         /*  Once he's panicked, and clock2 has run out, we come here
861          *  to set up the storage room.  The room has two locs,
862          *  hardwired as LOC_NE and LOC_SW.  At the ne end, we
863          *  place empty bottles, a nursery of plants, a bed of
864          *  oysters, a pile of lamps, rods with stars, sleeping
865          *  dwarves, and him.  At the sw end we place grate over
866          *  treasures, snake pit, covey of caged birds, more rods, and
867          *  pillows.  A mirror stretches across one wall.  Many of the
868          *  objects come from known locations and/or states (e.g. the
869          *  snake is known to have been destroyed and needn't be
870          *  carried away from its old "place"), making the various
871          *  objects be handled differently.  We also drop all other
872          *  objects he might be carrying (lest he have some which
873          *  could cause trouble, such as the keys).  We describe the
874          *  flash of light and trundle back. */
875         game.prop[BOTTLE] = put(BOTTLE, LOC_NE, EMPTY_BOTTLE);
876         game.prop[PLANT] = put(PLANT, LOC_NE, PLANT_THIRSTY);
877         game.prop[OYSTER] = put(OYSTER, LOC_NE, STATE_FOUND);
878         game.prop[LAMP] = put(LAMP, LOC_NE, LAMP_DARK);
879         game.prop[ROD] = put(ROD, LOC_NE, STATE_FOUND);
880         game.prop[DWARF] = put(DWARF, LOC_NE, 0);
881         game.loc = LOC_NE;
882         game.oldloc = LOC_NE;
883         game.newloc = LOC_NE;
884         /*  Leave the grate with normal (non-negative) property.
885          *  Reuse sign. */
886         put(GRATE, LOC_SW, 0);
887         put(SIGN, LOC_SW, 0);
888         game.prop[SIGN] = ENDGAME_SIGN;
889         game.prop[SNAKE] = put(SNAKE, LOC_SW, SNAKE_CHASED);
890         game.prop[BIRD] = put(BIRD, LOC_SW, BIRD_CAGED);
891         game.prop[CAGE] = put(CAGE, LOC_SW, STATE_FOUND);
892         game.prop[ROD2] = put(ROD2, LOC_SW, STATE_FOUND);
893         game.prop[PILLOW] = put(PILLOW, LOC_SW, STATE_FOUND);
894
895         game.prop[MIRROR] = put(MIRROR, LOC_NE, STATE_FOUND);
896         game.fixed[MIRROR] = LOC_SW;
897
898         for (int i = 1; i <= NOBJECTS; i++) {
899             if (TOTING(i))
900                 DESTROY(i);
901         }
902
903         rspeak(CAVE_CLOSED);
904         game.closed = true;
905         return game.closed;
906     }
907
908     lampcheck();
909     return false;
910 }
911
912 static void listobjects(void)
913 /*  Print out descriptions of objects at this location.  If
914  *  not closing and property value is negative, tally off
915  *  another treasure.  Rug is special case; once seen, its
916  *  game.prop is RUG_DRAGON (dragon on it) till dragon is killed.
917  *  Similarly for chain; game.prop is initially CHAINING_BEAR (locked to
918  *  bear).  These hacks are because game.prop=0 is needed to
919  *  get full score. */
920 {
921     if (!DARK(game.loc)) {
922         ++game.abbrev[game.loc];
923         for (int i = game.atloc[game.loc]; i != 0; i = game.link[i]) {
924             obj_t obj = i;
925             if (obj > NOBJECTS)
926                 obj = obj - NOBJECTS;
927             if (obj == STEPS && TOTING(NUGGET))
928                 continue;
929             if (game.prop[obj] < 0) {
930                 if (game.closed)
931                     continue;
932                 game.prop[obj] = STATE_FOUND;
933                 if (obj == RUG)
934                     game.prop[RUG] = RUG_DRAGON;
935                 if (obj == CHAIN)
936                     game.prop[CHAIN] = CHAINING_BEAR;
937                 if (obj == EGGS)
938                     game.seenbigwords = true;
939                 --game.tally;
940                 /*  Note: There used to be a test here to see whether the
941                  *  player had blown it so badly that he could never ever see
942                  *  the remaining treasures, and if so the lamp was zapped to
943                  *  35 turns.  But the tests were too simple-minded; things
944                  *  like killing the bird before the snake was gone (can never
945                  *  see jewelry), and doing it "right" was hopeless.  E.G.,
946                  *  could cross troll bridge several times, using up all
947                  *  available treasures, breaking vase, using coins to buy
948                  *  batteries, etc., and eventually never be able to get
949                  *  across again.  If bottle were left on far side, could then
950                  *  never get eggs or trident, and the effects propagate.  So
951                  *  the whole thing was flushed.  anyone who makes such a
952                  *  gross blunder isn't likely to find everything else anyway
953                  *  (so goes the rationalisation). */
954             }
955             int kk = game.prop[obj];
956             if (obj == STEPS)
957                 kk = (game.loc == game.fixed[STEPS])
958                      ? STEPS_UP
959                      : STEPS_DOWN;
960             pspeak(obj, look, true, kk);
961         }
962     }
963 }
964
965 static bool preprocess_command(command_t *command)
966 /* Pre-processes a command input to see if we need to tease out a few specific cases:
967  * - "enter water" or "enter stream":
968  *   weird specific case that gets the user wet, and then kicks us back to get another command
969  * - <object> <verb>:
970  *   Irregular form of input, but should be allowed. We switch back to <verb> <object> form for
971  *   further processing.
972  * - "grate":
973  *   If in location with grate, we move to that grate. If we're in a number of other places,
974  *   we move to the entrance.
975  * - "water plant", "oil plant", "water door", "oil door":
976  *   Change to "pour water" or "pour oil" based on context
977  * - "cage bird":
978  *   If bird is present, we change to "carry bird"
979  *
980  * Returns true if pre-processing is complete, and we're ready to move to the primary command
981  * processing, false otherwise. */
982 {
983     if (command->word[0].type == MOTION && command->word[0].id == ENTER
984         && (command->word[1].id == STREAM || command->word[1].id == WATER)) {
985         if (LIQLOC(game.loc) == WATER)
986             rspeak(FEET_WET);
987         else
988             rspeak(WHERE_QUERY);
989     } else {
990         if (command->word[0].type == OBJECT) {
991             /* From OV to VO form */
992             if (command->word[1].type == ACTION) {
993                 command_word_t stage = command->word[0];
994                 command->word[0] = command->word[1];
995                 command->word[1] = stage;
996             }
997
998             if (command->word[0].id == GRATE) {
999                 command->word[0].type = MOTION;
1000                 if (game.loc == LOC_START ||
1001                     game.loc == LOC_VALLEY ||
1002                     game.loc == LOC_SLIT) {
1003                     command->word[0].id = DEPRESSION;
1004                 }
1005                 if (game.loc == LOC_COBBLE ||
1006                     game.loc == LOC_DEBRIS ||
1007                     game.loc == LOC_AWKWARD ||
1008                     game.loc == LOC_BIRDCHAMBER ||
1009                     game.loc == LOC_PITTOP) {
1010                     command->word[0].id = ENTRANCE;
1011                 }
1012             }
1013             if ((command->word[0].id == WATER || command->word[0].id == OIL) &&
1014                 (command->word[1].id == PLANT || command->word[1].id == DOOR)) {
1015                 if (AT(command->word[1].id)) {
1016                     command->word[1] = command->word[0];
1017                     command->word[0].id = POUR;
1018                     command->word[0].type = ACTION;
1019                     strncpy(command->word[0].raw, "pour", LINESIZE - 1);
1020                 }
1021             }
1022             if (command->word[0].id == CAGE && command->word[1].id == BIRD && HERE(CAGE) && HERE(BIRD)) {
1023                 command->word[0].id = CARRY;
1024                 command->word[0].type = ACTION;
1025             }
1026         }
1027
1028         /* If no word type is given for the first word, we assume it's a motion. */
1029         if (command->word[0].type == NO_WORD_TYPE)
1030             command->word[0].type = MOTION;
1031
1032         command->state = PREPROCESSED;
1033         return true;
1034     }
1035     return false;
1036 }
1037
1038 static bool do_move(void)
1039 /* Actually execute the move to the new location and dwarf movement */
1040 {
1041     /*  Can't leave cave once it's closing (except by main office). */
1042     if (OUTSID(game.newloc) && game.newloc != 0 && game.closng) {
1043         rspeak(EXIT_CLOSED);
1044         game.newloc = game.loc;
1045         if (!game.panic)
1046             game.clock2 = PANICTIME;
1047         game.panic = true;
1048     }
1049
1050     /*  See if a dwarf has seen him and has come from where he
1051      *  wants to go.  If so, the dwarf's blocking his way.  If
1052      *  coming from place forbidden to pirate (dwarves rooted in
1053      *  place) let him get out (and attacked). */
1054     if (game.newloc != game.loc && !FORCED(game.loc) && !CNDBIT(game.loc, COND_NOARRR)) {
1055         for (size_t i = 1; i <= NDWARVES - 1; i++) {
1056             if (game.odloc[i] == game.newloc && game.dseen[i]) {
1057                 game.newloc = game.loc;
1058                 rspeak(DWARF_BLOCK);
1059                 break;
1060             }
1061         }
1062     }
1063     game.loc = game.newloc;
1064
1065     if (!dwarfmove())
1066         croak();
1067
1068     if (game.loc == LOC_NOWHERE)
1069         croak();
1070
1071     /* The easiest way to get killed is to fall into a pit in
1072      * pitch darkness. */
1073     if (!FORCED(game.loc) && DARK(game.loc) && game.wzdark && PCT(PIT_KILL_PROB)) {
1074         rspeak(PIT_FALL);
1075         game.oldlc2 = game.loc;
1076         croak();
1077         return false;
1078     }
1079
1080     return true;
1081 }
1082
1083 static bool do_command(void)
1084 /* Get and execute a command */
1085 {
1086     static command_t command;
1087     clear_command(&command);
1088
1089     /* Describe the current location and (maybe) get next command. */
1090     while (command.state != EXECUTED) {
1091         describe_location();
1092
1093         if (FORCED(game.loc)) {
1094             playermove(HERE);
1095             return true;
1096         }
1097
1098         listobjects();
1099
1100         /* Command not yet given; keep getting commands from user
1101          * until valid command is both given and executed. */
1102         clear_command(&command);
1103         while (command.state <= GIVEN) {
1104
1105             if (game.closed) {
1106                 /*  If closing time, check for any objects being toted with
1107                  *  game.prop < 0 and stash them.  This way objects won't be
1108                  *  described until they've been picked up and put down
1109                  *  separate from their respective piles. */
1110                 if (game.prop[OYSTER] < 0 && TOTING(OYSTER))
1111                     pspeak(OYSTER, look, true, 1);
1112                 for (size_t i = 1; i <= NOBJECTS; i++) {
1113                     if (TOTING(i) && game.prop[i] < 0)
1114                         game.prop[i] = STASHED(i);
1115                 }
1116             }
1117
1118             /* Check to see if the room is dark. If the knife is here,
1119              * and it's dark, the knife permanently disappears */
1120             game.wzdark = DARK(game.loc);
1121             if (game.knfloc != LOC_NOWHERE && game.knfloc != game.loc)
1122                 game.knfloc = LOC_NOWHERE;
1123
1124             /* Check some for hints, get input from user, increment
1125              * turn, and pre-process commands. Keep going until
1126              * pre-processing is done. */
1127             while ( command.state < PREPROCESSED ) {
1128                 checkhints();
1129
1130                 /* Get command input from user */
1131                 if (!get_command_input(&command))
1132                     return false;
1133
1134                 /* Every input, check "foobar" flag. If zero, nothing's going
1135                  * on. If pos, make neg. If neg, he skipped a word, so make it
1136                  * zero.
1137                  */
1138                 game.foobar = (game.foobar > WORD_EMPTY) ? -game.foobar : WORD_EMPTY;
1139
1140                 ++game.turns;
1141                 preprocess_command(&command);
1142             }
1143
1144             /* check if game is closed, and exit if it is */
1145             if (closecheck() )
1146                 return true;
1147
1148             /* loop until all words in command are processed */
1149             while (command.state == PREPROCESSED ) {
1150                 command.state = PROCESSING;
1151
1152                 if (command.word[0].id == WORD_NOT_FOUND) {
1153                     /* Gee, I don't understand. */
1154                     sspeak(DONT_KNOW, command.word[0].raw);
1155                     clear_command(&command);
1156                     continue;
1157                 }
1158
1159                 /* Give user hints of shortcuts */
1160                 if (strncasecmp(command.word[0].raw, "west", sizeof("west")) == 0) {
1161                     if (++game.iwest == 10)
1162                         rspeak(W_IS_WEST);
1163                 }
1164                 if (strncasecmp(command.word[0].raw, "go", sizeof("go")) == 0 && command.word[1].id != WORD_EMPTY) {
1165                     if (++game.igo == 10)
1166                         rspeak(GO_UNNEEDED);
1167                 }
1168
1169                 switch (command.word[0].type) {
1170                 case MOTION:
1171                     playermove(command.word[0].id);
1172                     command.state = EXECUTED;
1173                     continue;
1174                 case OBJECT:
1175                     command.part = unknown;
1176                     command.obj = command.word[0].id;
1177                     break;
1178                 case ACTION:
1179                     if (command.word[1].type == NUMERIC)
1180                         command.part = transitive;
1181                     else
1182                         command.part = intransitive;
1183                     command.verb = command.word[0].id;
1184                     break;
1185                 case NUMERIC:
1186                     if (!settings.oldstyle) {
1187                         sspeak(DONT_KNOW, command.word[0].raw);
1188                         clear_command(&command);
1189                         continue;
1190                     }
1191                     break;// LCOV_EXCL_LINE
1192                 default: // LCOV_EXCL_LINE
1193                 case NO_WORD_TYPE: // LCOV_EXCL_LINE
1194                     BUG(VOCABULARY_TYPE_N_OVER_1000_NOT_BETWEEN_0_AND_3); // LCOV_EXCL_LINE
1195                 }
1196
1197                 switch (action(command)) {
1198                 case GO_TERMINATE:
1199                     command.state = EXECUTED;
1200                     break;
1201                 case GO_MOVE:
1202                     playermove(NUL);
1203                     command.state = EXECUTED;
1204                     break;
1205                 case GO_WORD2:
1206 #ifdef GDEBUG
1207                     printf("Word shift\n");
1208 #endif /* GDEBUG */
1209                     /* Get second word for analysis. */
1210                     command.word[0] = command.word[1];
1211                     command.word[1] = empty_command_word;
1212                     command.state = PREPROCESSED;
1213                     break;
1214                 case GO_UNKNOWN:
1215                     /*  Random intransitive verbs come here.  Clear obj just in case
1216                      *  (see attack()). */
1217                     command.word[0].raw[0] = toupper(command.word[0].raw[0]);
1218                     sspeak(DO_WHAT, command.word[0].raw);
1219                     command.obj = NO_OBJECT;
1220
1221                     /* object cleared; we need to go back to the preprocessing step */
1222                     command.state = GIVEN;
1223                     break;
1224                 case GO_CHECKHINT: // FIXME: re-name to be more contextual; this was previously a label
1225                     command.state = GIVEN;
1226                     break;
1227                 case GO_DWARFWAKE:
1228                     /*  Oh dear, he's disturbed the dwarves. */
1229                     rspeak(DWARVES_AWAKEN);
1230                     terminate(endgame);
1231                 case GO_CLEAROBJ: // FIXME: re-name to be more contextual; this was previously a label
1232                     clear_command(&command);
1233                     break;
1234                 case GO_TOP: // FIXME: re-name to be more contextual; this was previously a label
1235                     break;
1236                 default: // LCOV_EXCL_LINE
1237                     BUG(ACTION_RETURNED_PHASE_CODE_BEYOND_END_OF_SWITCH); // LCOV_EXCL_LINE
1238                 }
1239             } /* while command has not been fully processed */
1240         } /* while command is not yet given */
1241     } /* while command is not executed */
1242
1243     /* command completely executed; we return true. */
1244     return true;
1245 }
1246
1247 /*
1248  * MAIN PROGRAM
1249  *
1250  *  Adventure (rev 2: 20 treasures)
1251  *  History: Original idea & 5-treasure version (adventures) by Willie Crowther
1252  *           15-treasure version (adventure) by Don Woods, April-June 1977
1253  *           20-treasure version (rev 2) by Don Woods, August 1978
1254  *              Errata fixed: 78/12/25
1255  *           Revived 2017 as Open Adventure.
1256  */
1257
1258 int main(int argc, char *argv[])
1259 {
1260     int ch;
1261
1262     /*  Options. */
1263
1264 #if defined ADVENT_AUTOSAVE
1265     const char* opts = "dl:oa:";
1266     const char* usage = "Usage: %s [-l logfilename] [-o] [-a filename] [script...]\n";
1267     FILE *rfp = NULL;
1268     const char* autosave_filename = NULL;
1269 #elif !defined ADVENT_NOSAVE
1270     const char* opts = "dl:or:";
1271     const char* usage = "Usage: %s [-l logfilename] [-o] [-r restorefilename] [script...]\n";
1272     FILE *rfp = NULL;
1273 #else
1274     const char* opts = "dl:o";
1275     const char* usage = "Usage: %s [-l logfilename] [-o] [script...]\n";
1276 #endif
1277     while ((ch = getopt(argc, argv, opts)) != EOF) {
1278         switch (ch) {
1279         case 'd': // LCOV_EXCL_LINE
1280             settings.debug +=1; // LCOV_EXCL_LINE
1281             break; // LCOV_EXCL_LINE
1282         case 'l':
1283             settings.logfp = fopen(optarg, "w");
1284             if (settings.logfp == NULL)
1285                 fprintf(stderr,
1286                         "advent: can't open logfile %s for write\n",
1287                         optarg);
1288             signal(SIGINT, sig_handler);
1289             break;
1290         case 'o':
1291             settings.oldstyle = true;
1292             settings.prompt = false;
1293             break;
1294 #ifdef ADVENT_AUTOSAVE
1295         case 'a':
1296             rfp = fopen(optarg, READ_MODE);
1297             autosave_filename = optarg;
1298             signal(SIGHUP, sig_handler);
1299             signal(SIGTERM, sig_handler);
1300             break;
1301 #elif !defined ADVENT_NOSAVE
1302         case 'r':
1303             rfp = fopen(optarg, "r");
1304             if (rfp == NULL)
1305                 fprintf(stderr,
1306                         "advent: can't open save file %s for read\n",
1307                         optarg);
1308             break;
1309 #endif
1310         default:
1311             fprintf(stderr,
1312                     usage, argv[0]);
1313             fprintf(stderr,
1314                     "        -l create a log file of your game named as specified'\n");
1315             fprintf(stderr,
1316                     "        -o 'oldstyle' (no prompt, no command editing, displays 'Initialising...')\n");
1317 #if defined ADVENT_AUTOSAVE
1318             fprintf(stderr,
1319                     "        -a automatic save/restore from specified saved game file\n");
1320 #elif !defined ADVENT_NOSAVE
1321             fprintf(stderr,
1322                     "        -r restore from specified saved game file\n");
1323 #endif
1324             exit(EXIT_FAILURE);
1325             break;
1326         }
1327     }
1328
1329     /* copy invocation line part after switches */
1330     settings.argc = argc - optind;
1331     settings.argv = argv + optind;
1332     settings.optind = 0;
1333
1334     /*  Initialize game variables */
1335     int seedval = initialise();
1336
1337 #if !defined ADVENT_NOSAVE
1338     if (!rfp) {
1339         game.novice = yes_or_no(arbitrary_messages[WELCOME_YOU], arbitrary_messages[CAVE_NEARBY], arbitrary_messages[NO_MESSAGE]);
1340         if (game.novice)
1341             game.limit = NOVICELIMIT;
1342     } else {
1343         restore(rfp);
1344 #if defined ADVENT_AUTOSAVE
1345         score(scoregame);
1346 #endif
1347     }
1348 #if defined ADVENT_AUTOSAVE
1349     if (autosave_filename != NULL) {
1350         if ((autosave_fp = fopen(autosave_filename, WRITE_MODE)) == NULL) {
1351             perror(autosave_filename);
1352             return EXIT_FAILURE;
1353         }
1354         autosave();
1355     }
1356 #endif
1357 #else
1358     game.novice = yes_or_no(arbitrary_messages[WELCOME_YOU], arbitrary_messages[CAVE_NEARBY], arbitrary_messages[NO_MESSAGE]);
1359     if (game.novice)
1360         game.limit = NOVICELIMIT;
1361 #endif
1362
1363     if (settings.logfp)
1364         fprintf(settings.logfp, "seed %d\n", seedval);
1365
1366     /* interpret commands until EOF or interrupt */
1367     for (;;) {
1368         // if we're supposed to move, move
1369         if (!do_move())
1370             continue;
1371
1372         // get command
1373         if (!do_command())
1374             break;
1375     }
1376     /* show score and exit */
1377     terminate(quitgame);
1378 }
1379
1380 /* end */