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