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