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