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