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