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