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