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