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