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