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