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