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