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