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