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