Deal with more agressive gcov 7.1; Reindent
[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: // LCOV_EXCL_LINE
227                     BUG(HINT_NUMBER_EXCEEDS_GOTO_LIST); // LCOV_EXCL_LINE
228                 }
229
230                 /* Fall through to hint display */
231                 game.hintlc[hint] = 0;
232                 if (!yes(hints[hint].question, arbitrary_messages[NO_MESSAGE], arbitrary_messages[OK_MAN]))
233                     return;
234                 rspeak(HINT_COST, hints[hint].penalty, hints[hint].penalty);
235                 game.hinted[hint] = yes(arbitrary_messages[WANT_HINT], hints[hint].hint, arbitrary_messages[OK_MAN]);
236                 if (game.hinted[hint] && game.limit > WARNTIME)
237                     game.limit += WARNTIME * hints[hint].penalty;
238             }
239         }
240     }
241 }
242
243 static bool spotted_by_pirate(int i)
244 {
245     if (i != PIRATE)
246         return false;
247
248     /*  The pirate's spotted him.  Pirate leaves him alone once we've
249      *  found chest.  K counts if a treasure is here.  If not, and
250      *  tally=1 for an unseen chest, let the pirate be spotted.  Note
251      *  that game.place[CHEST] = LOC_NOWHERE might mean that he's thrown
252      *  it to the troll, but in that case he's seen the chest
253      *  (game.prop[CHEST] == STATE_FOUND). */
254     if (game.loc == game.chloc ||
255         game.prop[CHEST] != STATE_NOTFOUND)
256         return true;
257     int snarfed = 0;
258     bool movechest = false, robplayer = false;
259     for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
260         if (!objects[treasure].is_treasure)
261             continue;
262         /*  Pirate won't take pyramid from plover room or dark
263          *  room (too easy!). */
264         if (treasure == PYRAMID && (game.loc == objects[PYRAMID].plac ||
265                                     game.loc == objects[EMERALD].plac)) {
266             continue;
267         }
268         if (TOTING(treasure) ||
269             HERE(treasure))
270             ++snarfed;
271         if (TOTING(treasure)) {
272             movechest = true;
273             robplayer = true;
274         }
275     }
276     /* Force chest placement before player finds last treasure */
277     if (game.tally == 1 && snarfed == 0 && game.place[CHEST] == LOC_NOWHERE && HERE(LAMP) && game.prop[LAMP] == LAMP_BRIGHT) {
278         rspeak(PIRATE_SPOTTED);
279         movechest = true;
280     }
281     /* Do things in this order (chest move before robbery) so chest is listed
282      * last at the maze location. */
283     if (movechest) {
284         move(CHEST, game.chloc);
285         move(MESSAG, game.chloc2);
286         game.dloc[PIRATE] = game.chloc;
287         game.odloc[PIRATE] = game.chloc;
288         game.dseen[PIRATE] = false;
289     } else {
290         /* You might get a hint of the pirate's presence even if the
291          * chest doesn't move... */
292         if (game.odloc[PIRATE] != game.dloc[PIRATE] && PCT(20))
293             rspeak(PIRATE_RUSTLES);
294     }
295     if (robplayer) {
296         rspeak(PIRATE_POUNCES);
297         for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
298             if (!objects[treasure].is_treasure)
299                 continue;
300             if (!(treasure == PYRAMID && (game.loc == objects[PYRAMID].plac ||
301                                           game.loc == objects[EMERALD].plac))) {
302                 if (AT(treasure) && game.fixed[treasure] == IS_FREE)
303                     carry(treasure, game.loc);
304                 if (TOTING(treasure))
305                     drop(treasure, game.chloc);
306             }
307         }
308     }
309
310     return true;
311 }
312
313 static bool dwarfmove(void)
314 /* Dwarves move.  Return true if player survives, false if he dies. */
315 {
316     int kk, stick, attack;
317     long tk[21];
318
319     /*  Dwarf stuff.  See earlier comments for description of
320      *  variables.  Remember sixth dwarf is pirate and is thus
321      *  very different except for motion rules. */
322
323     /*  First off, don't let the dwarves follow him into a pit or a
324      *  wall.  Activate the whole mess the first time he gets as far
325      *  as the Hall of Mists (what INDEEP() tests).  If game.newloc
326      *  is forbidden to pirate (in particular, if it's beyond the
327      *  troll bridge), bypass dwarf stuff.  That way pirate can't
328      *  steal return toll, and dwarves can't meet the bear.  Also
329      *  means dwarves won't follow him into dead end in maze, but
330      *  c'est la vie.  They'll wait for him outside the dead 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 game.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                     /* This can't actually happen. */
400                     continue; // LCOV_EXCL_LINE
401                 else if (game.newloc == game.dloc[i])
402                     continue;
403                 else if (FORCED(game.newloc))
404                     continue;
405                 else if (i == PIRATE && CNDBIT(game.newloc, COND_NOARRR))
406                     continue;
407                 else if (travel[kk].nodwarves)
408                     continue;
409                 tk[j++] = game.newloc;
410             } while
411             (!travel[kk++].stop);
412         tk[j] = game.odloc[i];
413         if (j >= 2)
414             --j;
415         j = 1 + randrange(j);
416         game.odloc[i] = game.dloc[i];
417         game.dloc[i] = tk[j];
418         game.dseen[i] = (game.dseen[i] && INDEEP(game.loc)) ||
419                         (game.dloc[i] == game.loc ||
420                          game.odloc[i] == game.loc);
421         if (!game.dseen[i])
422             continue;
423         game.dloc[i] = game.loc;
424         if (spotted_by_pirate(i))
425             continue;
426         /* This threatening little dwarf is in the room with him! */
427         ++game.dtotal;
428         if (game.odloc[i] == game.dloc[i]) {
429             ++attack;
430             if (game.knfloc >= 0)
431                 game.knfloc = game.loc;
432             if (randrange(1000) < 95 * (game.dflag - 2))
433                 ++stick;
434         }
435     }
436
437     /*  Now we know what's happening.  Let's tell the poor sucker about it. */
438     if (game.dtotal == 0)
439         return true;
440     rspeak(game.dtotal == 1 ? DWARF_SINGLE : DWARF_PACK, game.dtotal);
441     if (attack == 0)
442         return true;
443     if (game.dflag == 2)
444         game.dflag = 3;
445     if (attack > 1) {
446         rspeak(THROWN_KNIVES, attack);
447         rspeak(stick > 1 ? MULTIPLE_HITS : (stick == 1 ? ONE_HIT : NONE_HIT), stick);
448     } else {
449         rspeak(KNIFE_THROWN);
450         rspeak(stick ? GETS_YOU : MISSES_YOU);
451     }
452     if (stick == 0)
453         return true;
454     game.oldlc2 = game.loc;
455     return false;
456 }
457
458 /*  "You're dead, Jim."
459  *
460  *  If the current loc is zero, it means the clown got himself killed.
461  *  We'll allow this maxdie times.  NDEATHS is automatically set based
462  *  on the number of snide messages available.  Each death results in
463  *  a message (obituaries[n]) which offers reincarnation; if accepted,
464  *  this results in message obituaries[0], obituaries[2], etc.  The
465  *  last time, if he wants another chance, he gets a snide remark as
466  *  we exit.  When reincarnated, all objects being carried get dropped
467  *  at game.oldlc2 (presumably the last place prior to being killed)
468  *  without change of props.  The loop runs backwards to assure that
469  *  the bird is dropped before the cage.  (This kluge could be changed
470  *  once we're sure all references to bird and cage are done by
471  *  keywords.)  The lamp is a special case (it wouldn't do to leave it
472  *  in the cave). It is turned off and left outside the building (only
473  *  if he was carrying it, of course).  He himself is left inside the
474  *  building (and heaven help him if he tries to xyzzy back into the
475  *  cave without the lamp!).  game.oldloc is zapped so he can't just
476  *  "retreat". */
477
478 static void croak(void)
479 /*  Okay, he's dead.  Let's get on with it. */
480 {
481     const char* query = obituaries[game.numdie].query;
482     const char* yes_response = obituaries[game.numdie].yes_response;
483     ++game.numdie;
484     if (game.closng) {
485         /*  He died during closing time.  No resurrection.  Tally up a
486          *  death and exit. */
487         rspeak(DEATH_CLOSING);
488         terminate(endgame);
489     } else if ( !yes(query, yes_response, arbitrary_messages[OK_MAN])
490                 || game.numdie == NDEATHS)
491         terminate(endgame);
492     else {
493         game.place[WATER] = game.place[OIL] = LOC_NOWHERE;
494         if (TOTING(LAMP))
495             game.prop[LAMP] = LAMP_DARK;
496         for (int j = 1; j <= NOBJECTS; j++) {
497             int i = NOBJECTS + 1 - j;
498             if (TOTING(i)) {
499                 /* Always leave lamp where it's accessible aboveground */
500                 drop(i, (i == LAMP) ? LOC_START : game.oldlc2);
501             }
502         }
503         game.oldloc = game.loc = game.newloc = LOC_BUILDING;
504     }
505 }
506
507 static bool traveleq(long a, long b)
508 /* Are two travel entries equal for purposes of skip after failed condition? */
509 {
510     return (travel[a].condtype == travel[b].condtype)
511            && (travel[a].condarg1 == travel[b].condarg1)
512            && (travel[a].condarg2 == travel[b].condarg2)
513            && (travel[a].desttype == travel[b].desttype)
514            && (travel[a].destval == travel[b].destval);
515 }
516
517 /*  Given the current location in "game.loc", and a motion verb number in
518  *  "motion", put the new location in "game.newloc".  The current loc is saved
519  *  in "game.oldloc" in case he wants to retreat.  The current
520  *  game.oldloc is saved in game.oldlc2, in case he dies.  (if he
521  *  does, game.newloc will be limbo, and game.oldloc will be what killed
522  *  him, so we need game.oldlc2, which is the last place he was
523  *  safe.) */
524
525 static void playermove( int motion)
526 {
527     int scratchloc, travel_entry = tkey[game.loc];
528     game.newloc = game.loc;
529     if (travel_entry == 0)
530         BUG(LOCATION_HAS_NO_TRAVEL_ENTRIES); // LCOV_EXCL_LINE
531     if (motion == NUL)
532         return;
533     else if (motion == BACK) {
534         /*  Handle "go back".  Look for verb which goes from game.loc to
535          *  game.oldloc, or to game.oldlc2 If game.oldloc has forced-motion.
536          *  te_tmp saves entry -> forced loc -> previous loc. */
537         motion = game.oldloc;
538         if (FORCED(motion))
539             motion = game.oldlc2;
540         game.oldlc2 = game.oldloc;
541         game.oldloc = game.loc;
542         if (CNDBIT(game.loc, COND_NOBACK)) {
543             rspeak(TWIST_TURN);
544             return;
545         }
546         if (motion == game.loc) {
547             rspeak(FORGOT_PATH);
548             return;
549         }
550
551         int te_tmp = 0;
552         for (;;) {
553             enum desttype_t desttype = travel[travel_entry].desttype;
554             scratchloc = travel[travel_entry].destval;
555             if (desttype != dest_goto || scratchloc != motion) {
556                 if (desttype == dest_goto) {
557                     if (FORCED(scratchloc) && travel[tkey[scratchloc]].destval == motion)
558                         te_tmp = travel_entry;
559                 }
560                 if (!travel[travel_entry].stop) {
561                     ++travel_entry;     /* go to next travel entry for this location */
562                     continue;
563                 }
564                 /* we've reached the end of travel entries for game.loc */
565                 travel_entry = te_tmp;
566                 if (travel_entry == 0) {
567                     rspeak(NOT_CONNECTED);
568                     return;
569                 }
570             }
571
572             motion = travel[travel_entry].motion;
573             travel_entry = tkey[game.loc];
574             break; /* fall through to ordinary travel */
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     do {
646         for (;;) { /* L12 loop */
647             for (;;) {
648                 enum condtype_t condtype = travel[travel_entry].condtype;
649                 long condarg1 = travel[travel_entry].condarg1;
650                 long condarg2 = travel[travel_entry].condarg2;
651                 if (condtype < cond_not) {
652                     /* YAML N and [pct N] conditionals */
653                     if (condtype == cond_goto || condtype == cond_pct) {
654                         if (condarg1 == 0 ||
655                             PCT(condarg1))
656                             break;
657                         /* else fall through */
658                     }
659                     /* YAML [with OBJ] clause */
660                     else if (TOTING(condarg1) ||
661                              (condtype == cond_with && AT(condarg1)))
662                         break;
663                     /* else fall through to check [not OBJ STATE] */
664                 } else if (game.prop[condarg1] != condarg2)
665                     break;
666
667                 /* We arrive here on conditional failure.
668                  * Skip to next non-matching destination */
669                 long te_tmp = travel_entry;
670                 do {
671                     if (travel[te_tmp].stop)
672                         BUG(CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION); // LCOV_EXCL_LINE
673                     ++te_tmp;
674                 } while
675                 (traveleq(travel_entry, te_tmp));
676                 travel_entry = te_tmp;
677             }
678
679             /* Found an eligible rule, now execute it */
680             enum desttype_t desttype = travel[travel_entry].desttype;
681             game.newloc = travel[travel_entry].destval;
682             if (desttype == dest_goto)
683                 return;
684
685             if (desttype == dest_speak) {
686                 /* Execute a speak rule */
687                 rspeak(game.newloc);
688                 game.newloc = game.loc;
689                 return;
690             } else {
691                 switch (game.newloc) {
692                 case 1:
693                     /* Special travel 1.  Plover-alcove passage.  Can carry only
694                      * emerald.  Note: travel table must include "useless"
695                      * entries going through passage, which can never be used
696                      * for actual motion, but can be spotted by "go back". */
697                     game.newloc = (game.loc == LOC_PLOVER)
698                                   ? LOC_ALCOVE
699                                   : LOC_PLOVER;
700                     if (game.holdng > 1 ||
701                         (game.holdng == 1 && !TOTING(EMERALD))) {
702                         game.newloc = game.loc;
703                         rspeak(MUST_DROP);
704                     }
705                     return;
706                 case 2:
707                     /* Special travel 2.  Plover transport.  Drop the
708                      * emerald (only use special travel if toting
709                      * it), so he's forced to use the plover-passage
710                      * to get it out.  Having dropped it, go back and
711                      * pretend he wasn't carrying it after all. */
712                     drop(EMERALD, game.loc);
713                     int te_tmp = travel_entry;
714                     do {
715                         if (travel[te_tmp].stop)
716                             BUG(CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION); // LCOV_EXCL_LINE
717                         ++te_tmp;
718                     } while
719                     (traveleq(travel_entry, te_tmp));
720                     travel_entry = te_tmp;
721                     continue; /* goto L12 */
722                 case 3:
723                     /* Special travel 3.  Troll bridge.  Must be done
724                      * only as special motion so that dwarves won't
725                      * wander across and encounter the bear.  (They
726                      * won't follow the player there because that
727                      * region is forbidden to the pirate.)  If
728                      * game.prop[TROLL]=TROLL_PAIDONCE, he's crossed
729                      * since paying, so step out and block him.
730                      * (standard travel entries check for
731                      * game.prop[TROLL]=TROLL_UNPAID.)  Special stuff
732                      * 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: // LCOV_EXCL_LINE
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     /* If a turn threshold has been met, apply penalties and tell
789      * the player about it. */
790     for (int i = 0; i < NTHRESHOLDS; ++i) {
791         if (game.turns == turn_thresholds[i].threshold + 1) {
792             game.trnluz += turn_thresholds[i].point_loss;
793             speak(turn_thresholds[i].message);
794         }
795     }
796
797     /*  Don't tick game.clock1 unless well into cave (and not at Y2). */
798     if (game.tally == 0 && INDEEP(game.loc) && game.loc != LOC_Y2)
799         --game.clock1;
800
801     /*  When the first warning comes, we lock the grate, destroy
802      *  the bridge, kill all the dwarves (and the pirate), remove
803      *  the troll and bear (unless dead), and set "closng" to
804      *  true.  Leave the dragon; too much trouble to move it.
805      *  from now until clock2 runs out, he cannot unlock the
806      *  grate, move to any location outside the cave, or create
807      *  the bridge.  Nor can he be resurrected if he dies.  Note
808      *  that the snake is already gone, since he got to the
809      *  treasure accessible only via the hall of the mountain
810      *  king. Also, he's been in giant room (to get eggs), so we
811      *  can refer to it.  Also also, he's gotten the pearl, so we
812      *  know the bivalve is an oyster.  *And*, the dwarves must
813      *  have been activated, since we've found chest. */
814     if (game.clock1 == 0) {
815         game.prop[GRATE] = GRATE_CLOSED;
816         game.prop[FISSURE] = UNBRIDGED;
817         for (int i = 1; i <= NDWARVES; i++) {
818             game.dseen[i] = false;
819             game.dloc[i] = LOC_NOWHERE;
820         }
821         move(TROLL, LOC_NOWHERE);
822         move(TROLL + NOBJECTS, IS_FREE);
823         move(TROLL2, objects[TROLL].plac);
824         move(TROLL2 + NOBJECTS, objects[TROLL].fixd);
825         juggle(CHASM);
826         if (game.prop[BEAR] != BEAR_DEAD)
827             DESTROY(BEAR);
828         game.prop[CHAIN] = CHAIN_HEAP;
829         game.fixed[CHAIN] = IS_FREE;
830         game.prop[AXE] = AXE_HERE;
831         game.fixed[AXE] = IS_FREE;
832         rspeak(CAVE_CLOSING);
833         game.clock1 = -1;
834         game.closng = true;
835         return true;
836     } else if (game.clock1 < 0)
837         --game.clock2;
838     if (game.clock2 == 0) {
839         /*  Once he's panicked, and clock2 has run out, we come here
840          *  to set up the storage room.  The room has two locs,
841          *  hardwired as LOC_NE and LOC_SW.  At the ne end, we
842          *  place empty bottles, a nursery of plants, a bed of
843          *  oysters, a pile of lamps, rods with stars, sleeping
844          *  dwarves, and him.  At the sw end we place grate over
845          *  treasures, snake pit, covey of caged birds, more rods, and
846          *  pillows.  A mirror stretches across one wall.  Many of the
847          *  objects come from known locations and/or states (e.g. the
848          *  snake is known to have been destroyed and needn't be
849          *  carried away from its old "place"), making the various
850          *  objects be handled differently.  We also drop all other
851          *  objects he might be carrying (lest he have some which
852          *  could cause trouble, such as the keys).  We describe the
853          *  flash of light and trundle back. */
854         game.prop[BOTTLE] = put(BOTTLE, LOC_NE, EMPTY_BOTTLE);
855         game.prop[PLANT] = put(PLANT, LOC_NE, PLANT_THIRSTY);
856         game.prop[OYSTER] = put(OYSTER, LOC_NE, STATE_FOUND);
857         game.prop[LAMP] = put(LAMP, LOC_NE, LAMP_DARK);
858         game.prop[ROD] = put(ROD, LOC_NE, STATE_FOUND);
859         game.prop[DWARF] = put(DWARF, LOC_NE, 0);
860         game.loc = LOC_NE;
861         game.oldloc = LOC_NE;
862         game.newloc = LOC_NE;
863         /*  Leave the grate with normal (non-negative) property.
864          *  Reuse sign. */
865         put(GRATE, LOC_SW, 0);
866         put(SIGN, LOC_SW, 0);
867         game.prop[SIGN] = ENDGAME_SIGN;
868         game.prop[SNAKE] = put(SNAKE, LOC_SW, SNAKE_CHASED);
869         game.prop[BIRD] = put(BIRD, LOC_SW, BIRD_CAGED);
870         game.prop[CAGE] = put(CAGE, LOC_SW, STATE_FOUND);
871         game.prop[ROD2] = put(ROD2, LOC_SW, STATE_FOUND);
872         game.prop[PILLOW] = put(PILLOW, LOC_SW, STATE_FOUND);
873
874         game.prop[MIRROR] = put(MIRROR, LOC_NE, STATE_FOUND);
875         game.fixed[MIRROR] = LOC_SW;
876
877         for (int i = 1; i <= NOBJECTS; i++) {
878             if (TOTING(i))
879                 DESTROY(i);
880         }
881
882         rspeak(CAVE_CLOSED);
883         game.closed = true;
884         return true;
885     }
886
887     return false;
888 }
889
890 static void lampcheck(void)
891 /* Check game limit and lamp timers */
892 {
893     if (game.prop[LAMP] == LAMP_BRIGHT)
894         --game.limit;
895
896     /*  Another way we can force an end to things is by having the
897      *  lamp give out.  When it gets close, we come here to warn him.
898      *  First following arm checks if the lamp and fresh batteries are
899      *  here, in which case we replace the batteries and continue.
900      *  Second is for other cases of lamp dying.  Even after it goes
901      *  out, he can explore outside for a while if desired. */
902     if (game.limit <= WARNTIME) {
903         if (HERE(BATTERY) && game.prop[BATTERY] == FRESH_BATTERIES && HERE(LAMP)) {
904             rspeak(REPLACE_BATTERIES);
905             game.prop[BATTERY] = DEAD_BATTERIES;
906             if (TOTING(BATTERY))
907                 drop(BATTERY, game.loc);
908             game.limit += BATTERYLIFE;
909             game.lmwarn = false;
910         } else if (!game.lmwarn && HERE(LAMP)) {
911             game.lmwarn = true;
912             if (game.prop[BATTERY] == DEAD_BATTERIES)
913                 rspeak(MISSING_BATTERIES);
914             else if (game.place[BATTERY] == LOC_NOWHERE)
915                 rspeak(LAMP_DIM);
916             else
917                 rspeak(GET_BATTERIES);
918         }
919     }
920     if (game.limit == 0) {
921         game.limit = -1;
922         game.prop[LAMP] = LAMP_DARK;
923         if (HERE(LAMP))
924             rspeak(LAMP_OUT);
925     }
926 }
927
928 static void listobjects(void)
929 /*  Print out descriptions of objects at this location.  If
930  *  not closing and property value is negative, tally off
931  *  another treasure.  Rug is special case; once seen, its
932  *  game.prop is RUG_DRAGON (dragon on it) till dragon is killed.
933  *  Similarly for chain; game.prop is initially CHAINING_BEAR (locked to
934  *  bear).  These hacks are because game.prop=0 is needed to
935  *  get full score. */
936 {
937     if (!DARK(game.loc)) {
938         ++game.abbrev[game.loc];
939         for (int i = game.atloc[game.loc]; i != 0; i = game.link[i]) {
940             long obj = i;
941             if (obj > NOBJECTS)
942                 obj = obj - NOBJECTS;
943             if (obj == STEPS && TOTING(NUGGET))
944                 continue;
945             if (game.prop[obj] < 0) {
946                 if (game.closed)
947                     continue;
948                 game.prop[obj] = STATE_FOUND;
949                 if (obj == RUG)
950                     game.prop[RUG] = RUG_DRAGON;
951                 if (obj == CHAIN)
952                     game.prop[CHAIN] = CHAINING_BEAR;
953                 --game.tally;
954                 /*  Note: There used to be a test here to see whether the
955                  *  player had blown it so badly that he could never ever see
956                  *  the remaining treasures, and if so the lamp was zapped to
957                  *  35 turns.  But the tests were too simple-minded; things
958                  *  like killing the bird before the snake was gone (can never
959                  *  see jewelry), and doing it "right" was hopeless.  E.G.,
960                  *  could cross troll bridge several times, using up all
961                  *  available treasures, breaking vase, using coins to buy
962                  *  batteries, etc., and eventually never be able to get
963                  *  across again.  If bottle were left on far side, could then
964                  *  never get eggs or trident, and the effects propagate.  So
965                  *  the whole thing was flushed.  anyone who makes such a
966                  *  gross blunder isn't likely to find everything else anyway
967                  *  (so goes the rationalisation). */
968             }
969             int kk = game.prop[obj];
970             if (obj == STEPS)
971                 kk = (game.loc == game.fixed[STEPS])
972                      ? STEPS_UP
973                      : STEPS_DOWN;
974             pspeak(obj, look, kk, true);
975         }
976     }
977 }
978
979 static bool get_command_input(struct command_t *command)
980 {
981     char inputbuf[LINESIZE];
982     char word1[TOKLEN + 1];
983     char word2[TOKLEN + 1];
984     char* input;
985
986     for (;;) {
987         input = get_input();
988         if (input == NULL)
989             return false;
990         if (word_count(input) > 2) {
991             rspeak(TWO_WORDS);
992             free(input);
993             continue;
994         }
995         if (strcmp(input, "") != 0)
996             break;
997         free(input);
998     }
999
1000     strncpy(inputbuf, input, LINESIZE - 1);
1001     free(input);
1002
1003     tokenize(inputbuf, command);
1004
1005     packed_to_token(command->wd1, word1);
1006     packed_to_token(command->wd2, word2);
1007     get_vocab_metadata(word1, &(command->id1), &(command->type1));
1008     get_vocab_metadata(word2, &(command->id2), &(command->type2));
1009
1010     return true;
1011 }
1012
1013 static bool do_command()
1014 /* Get and execute a command */
1015 {
1016     static struct command_t command;
1017     char word1[TOKLEN + 1];
1018
1019     command.verb = 0;
1020
1021     /*  Can't leave cave once it's closing (except by main office). */
1022     if (OUTSID(game.newloc) && game.newloc != 0 && game.closng) {
1023         rspeak(EXIT_CLOSED);
1024         game.newloc = game.loc;
1025         if (!game.panic)
1026             game.clock2 = PANICTIME;
1027         game.panic = true;
1028     }
1029
1030     /*  See if a dwarf has seen him and has come from where he
1031      *  wants to go.  If so, the dwarf's blocking his way.  If
1032      *  coming from place forbidden to pirate (dwarves rooted in
1033      *  place) let him get out (and attacked). */
1034     if (game.newloc != game.loc && !FORCED(game.loc) && !CNDBIT(game.loc, COND_NOARRR)) {
1035         for (size_t i = 1; i <= NDWARVES - 1; i++) {
1036             if (game.odloc[i] == game.newloc && game.dseen[i]) {
1037                 game.newloc = game.loc;
1038                 rspeak(DWARF_BLOCK);
1039                 break;
1040             }
1041         }
1042     }
1043     game.loc = game.newloc;
1044
1045     if (!dwarfmove())
1046         croak();
1047
1048     /*  Describe the current location and (maybe) get next command. */
1049
1050     for (;;) {
1051         if (game.loc == 0)
1052             croak();
1053         const char* msg = locations[game.loc].description.small;
1054         if (MOD(game.abbrev[game.loc], game.abbnum) == 0 ||
1055             msg == 0)
1056             msg = locations[game.loc].description.big;
1057         if (!FORCED(game.loc) && DARK(game.loc)) {
1058             /*  The easiest way to get killed is to fall into a pit in
1059              *  pitch darkness. */
1060             if (game.wzdark && PCT(35)) {
1061                 rspeak(PIT_FALL);
1062                 game.oldlc2 = game.loc;
1063                 croak();
1064                 continue;       /* back to top of main interpreter loop */
1065             }
1066             msg = arbitrary_messages[PITCH_DARK];
1067         }
1068         if (TOTING(BEAR))
1069             rspeak(TAME_BEAR);
1070         speak(msg);
1071         if (FORCED(game.loc)) {
1072             playermove(HERE);
1073             return true;
1074         }
1075         if (game.loc == LOC_Y2 && PCT(25) && !game.closng)
1076             rspeak(SAYS_PLUGH);
1077
1078         listobjects();
1079
1080 Lclearobj:
1081         game.oldobj = command.obj;
1082
1083         checkhints();
1084
1085         /*  If closing time, check for any objects being toted with
1086          *  game.prop < 0 and stash them.  This way objects won't be
1087          *  described until they've been picked up and put down
1088          *  separate from their respective piles. */
1089         if (game.closed) {
1090             if (game.prop[OYSTER] < 0 && TOTING(OYSTER))
1091                 pspeak(OYSTER, look, 1, true);
1092             for (size_t i = 1; i <= NOBJECTS; i++) {
1093                 if (TOTING(i) && game.prop[i] < 0)
1094                     game.prop[i] = STASHED(i);
1095             }
1096         }
1097         game.wzdark = DARK(game.loc);
1098         if (game.knfloc > 0 && game.knfloc != game.loc)
1099             game.knfloc = 0;
1100
1101         // Get command input from user
1102         if (!get_command_input(&command))
1103             return false;
1104
1105         ++game.turns;
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 == WATER)) {
1115             if (LIQLOC(game.loc) == WATER)
1116                 rspeak(FEET_WET);
1117             else
1118                 rspeak(WHERE_QUERY);
1119
1120             goto Lclearobj;
1121         }
1122         if (command.id1 == ENTER && command.id2 != WORD_NOT_FOUND && command.id2 != WORD_EMPTY) {
1123             command.id1 = command.id2;
1124             command.type1 = command.type2;
1125             strncpy(command.raw1, command.raw2, LINESIZE - 1);
1126             command.id2 = WORD_EMPTY;
1127             command.type2 = NO_WORD_TYPE;
1128             strncpy(command.raw2, "", LINESIZE - 1);
1129         } else {
1130             if (!((command.id1 != WATER && command.id1 != OIL) || (command.id2 != PLANT && command.id2 != DOOR))) {
1131                 if (AT(command.id2)) {
1132                     command.id2 = POUR;
1133                     command.type2 = ACTION;
1134                     strncpy(command.raw2, "POUR", LINESIZE - 1);
1135                     command.wd2 = token_to_packed("POUR");
1136                 }
1137             }
1138             if (command.id1 == CAGE && command.id2 == BIRD && HERE(CAGE) && HERE(BIRD)) {
1139                 command.id1 = CARRY;
1140                 command.type1 = ACTION;
1141                 strncpy(command.raw2, "CATCH", LINESIZE - 1);
1142                 command.wd1 = token_to_packed("CATCH");
1143             }
1144         }
1145 Lookup:
1146         if (strncasecmp(command.raw1, "west", sizeof("west")) == 0) {
1147             if (++game.iwest == 10)
1148                 rspeak(W_IS_WEST);
1149         }
1150         if (strncasecmp(command.raw1, "go", sizeof("go")) == 0 && command.id2 != WORD_EMPTY) {
1151             if (++game.igo == 10)
1152                 rspeak(GO_UNNEEDED);
1153         }
1154         packed_to_token(command.wd1, word1);
1155         long defn;
1156         enum wordtype type;
1157         get_vocab_metadata(word1, &defn, &type);
1158         if (command.id1 == WORD_NOT_FOUND) {
1159             if (fallback_handler(command))
1160                 continue;
1161             /* Gee, I don't understand. */
1162             sspeak(DONT_KNOW, command.raw1);
1163             goto Lclearobj;
1164         }
1165         switch (type) {
1166         case NO_WORD_TYPE: // FIXME: treating NO_WORD_TYPE as a motion word is confusing
1167         case MOTION:
1168             playermove(command.id1);
1169             return true;
1170         case OBJECT:
1171             command.part = unknown;
1172             command.obj = command.id1;
1173             break;
1174         case ACTION:
1175             command.part = intransitive;
1176             command.verb = defn;
1177             break;
1178         case SPECIAL:
1179             speak(specials[command.id1].message);
1180             goto Lclearobj;
1181         default: // LCOV_EXCL_LINE
1182             BUG(VOCABULARY_TYPE_N_OVER_1000_NOT_BETWEEN_0_AND_3); // LCOV_EXCL_LINE
1183         }
1184
1185         switch (action(&command)) {
1186         case GO_TERMINATE:
1187             return true;
1188         case GO_MOVE:
1189             playermove(NUL);
1190             return true;
1191         case GO_TOP:
1192             continue;   /* back to top of main interpreter loop */
1193         case GO_LOOKUP:
1194             goto Lookup;
1195         case GO_WORD2:
1196             /* Get second word for analysis. */
1197             command.id1 = command.id2;
1198             command.type1 = command.type2;
1199             strncpy(command.raw1, command.raw2, LINESIZE - 1);
1200             command.wd1 = command.wd2;
1201             command.id2 = WORD_EMPTY;
1202             command.type2 = NO_WORD_TYPE;
1203             command.raw2[0] = '\0';
1204             wordclear(&command.wd2);
1205             goto Lookup;
1206         case GO_UNKNOWN:
1207             /*  Random intransitive verbs come here.  Clear obj just in case
1208              *  (see attack()). */
1209             command.raw1[0] = toupper(command.raw1[0]);
1210             sspeak(DO_WHAT, command.raw1);
1211             command.obj = 0;
1212         // Fallthrough
1213         case GO_CHECKHINT: // Fallthrough
1214         case GO_CLEAROBJ:
1215             goto Lclearobj;
1216         case GO_DWARFWAKE:
1217             /*  Oh dear, he's disturbed the dwarves. */
1218             rspeak(DWARVES_AWAKEN);
1219             terminate(endgame);
1220         default: // LCOV_EXCL_LINE
1221             BUG(ACTION_RETURNED_PHASE_CODE_BEYOND_END_OF_SWITCH); // LCOV_EXCL_LINE
1222         }
1223     }
1224 }
1225
1226 /* end */