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