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