1416e4110bab64ab3fd9d077eeb3b6065f7625d8
[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     do {
618         for (;;) { /* L12 loop */
619             for (;;) {
620                 long cond = T_CONDITION(travel[kk]);
621                 long arg = MOD(cond, 100);
622                 if (!SPECIAL(cond)) {
623                     /* YAML N and [pct N] conditionals */
624                     if (cond <= 100) {
625                         if (cond == 0 || PCT(cond))
626                             break;
627                         /* else fall through */
628                     }
629                     /* YAML [with OBJ] clause */
630                     if (TOTING(arg) || (cond > 200 && AT(arg)))
631                         break;
632                     /* else fall through to check [not OBJ STATE] */
633                 } else if (game.prop[arg] != cond / 100 - 3)
634                     break;
635
636                 /* We arrive here on conditional failure.
637                  * Skip to next non-matching destination */
638                 long k2 = kk;
639                 do {
640                     if (travel[k2].stop)
641                         BUG(CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION); // LCOV_EXCL_LINE
642                     ++k2;
643                 } while
644                     (T_HIGH(travel[kk]) == T_HIGH(travel[k2]));
645                 kk = k2;
646             }
647
648             /* Found an eligible rule, now execute it */
649             game.newloc = T_DESTINATION(travel[kk]);
650             if (!SPECIAL(game.newloc))
651                 return true;
652
653             if (game.newloc > 500) {
654                 /* Execute a speak rule */
655                 rspeak(L_SPEAK(game.newloc));
656                 game.newloc = game.loc;
657                 return true;
658             } else {
659                 game.newloc -= SPECIALBASE;
660                 switch (game.newloc) {
661                 case 1:
662                     /* Travel 301.  Plover-alcove passage.  Can carry only
663                      * emerald.  Note: travel table must include "useless"
664                      * entries going through passage, which can never be used
665                      * for actual motion, but can be spotted by "go back". */
666                     /* FIXME: Arithmetic on location numbers */
667                     game.newloc = 99 + 100 - game.loc;
668                     if (game.holdng > 1 || (game.holdng == 1 && !TOTING(EMERALD))) {
669                         game.newloc = game.loc;
670                         rspeak(MUST_DROP);
671                     }
672                     return true;
673                 case 2:
674                     /* Travel 302.  Plover transport.  Drop the
675                      * emerald (only use special travel if toting
676                      * it), so he's forced to use the plover-passage
677                      * to get it out.  Having dropped it, go back and
678                      * pretend he wasn't carrying it after all. */
679                     drop(EMERALD, game.loc);
680                     k2 = kk;
681                     do {
682                         if (travel[k2].stop)
683                             BUG(CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION); // LCOV_EXCL_LINE
684                         ++k2;
685                     } while
686                         (T_HIGH(travel[kk]) == T_HIGH(travel[k2]));
687                     kk = k2;
688                     continue; /* goto L12 */
689                 case 3:
690                     /* Travel 303.  Troll bridge.  Must be done only
691                      * as special motion so that dwarves won't wander
692                      * across and encounter the bear.  (They won't
693                      * follow the player there because that region is
694                      * forbidden to the pirate.)  If
695                      * game.prop(TROLL)=1, he's crossed since paying,
696                      * so step out and block him.  (standard travel
697                      * entries check for game.prop(TROLL)=0.)  Special
698                      * stuff for bear. */
699                     if (game.prop[TROLL] == 1) {
700                         pspeak(TROLL,look, 1);
701                         game.prop[TROLL] = 0;
702                         move(TROLL2, 0);
703                         move(TROLL2 + NOBJECTS, 0);
704                         move(TROLL, objects[TROLL].plac);
705                         move(TROLL + NOBJECTS, objects[TROLL].fixd);
706                         juggle(CHASM);
707                         game.newloc = game.loc;
708                         return true;
709                     } else {
710                         game.newloc = objects[TROLL].plac + objects[TROLL].fixd - game.loc;
711                         if (game.prop[TROLL] == 0)game.prop[TROLL] = 1;
712                         if (!TOTING(BEAR)) return true;
713                         rspeak(BRIDGE_COLLAPSE);
714                         game.prop[CHASM] = 1;
715                         game.prop[TROLL] = 2;
716                         drop(BEAR, game.newloc);
717                         game.fixed[BEAR] = -1;
718                         game.prop[BEAR] = BEAR_DEAD;
719                         game.oldlc2 = game.newloc;
720                         croak();
721                         return true;
722                     }
723                 default:
724                     BUG(SPECIAL_TRAVEL_500_GT_L_GT_300_EXCEEDS_GOTO_LIST); // LCOV_EXCL_LINE
725                 }
726             }
727             break; /* Leave L12 loop */
728         }
729     } while
730     (false);
731 }
732
733 static bool closecheck(void)
734 /*  Handle the closing of the cave.  The cave closes "clock1" turns
735  *  after the last treasure has been located (including the pirate's
736  *  chest, which may of course never show up).  Note that the
737  *  treasures need not have been taken yet, just located.  Hence
738  *  clock1 must be large enough to get out of the cave (it only ticks
739  *  while inside the cave).  When it hits zero, we branch to 10000 to
740  *  start closing the cave, and then sit back and wait for him to try
741  *  to get out.  If he doesn't within clock2 turns, we close the cave;
742  *  if he does try, we assume he panics, and give him a few additional
743  *  turns to get frantic before we close.  When clock2 hits zero, we
744  *  transport him into the final puzzle.  Note that the puzzle depends
745  *  upon all sorts of random things.  For instance, there must be no
746  *  water or oil, since there are beanstalks which we don't want to be
747  *  able to water, since the code can't handle it.  Also, we can have
748  *  no keys, since there is a grate (having moved the fixed object!)
749  *  there separating him from all the treasures.  Most of these
750  *  problems arise from the use of negative prop numbers to suppress
751  *  the object descriptions until he's actually moved the objects. */
752 {
753     if (game.tally == 0 && INDEEP(game.loc) && game.loc != LOC_Y2)
754         --game.clock1;
755
756     /*  When the first warning comes, we lock the grate, destroy
757      *  the bridge, kill all the dwarves (and the pirate), remove
758      *  the troll and bear (unless dead), and set "closng" to
759      *  true.  Leave the dragon; too much trouble to move it.
760      *  from now until clock2 runs out, he cannot unlock the
761      *  grate, move to any location outside the cave, or create
762      *  the bridge.  Nor can he be resurrected if he dies.  Note
763      *  that the snake is already gone, since he got to the
764      *  treasure accessible only via the hall of the mountain
765      *  king. Also, he's been in giant room (to get eggs), so we
766      *  can refer to it.  Also also, he's gotten the pearl, so we
767      *  know the bivalve is an oyster.  *And*, the dwarves must
768      *  have been activated, since we've found chest. */
769     if (game.clock1 == 0) {
770         game.prop[GRATE] = GRATE_CLOSED;
771         game.prop[FISSURE] = 0;
772         for (int i = 1; i <= NDWARVES; i++) {
773             game.dseen[i] = false;
774             game.dloc[i] = 0;
775         }
776         move(TROLL, 0);
777         move(TROLL + NOBJECTS, 0);
778         move(TROLL2, objects[TROLL].plac);
779         move(TROLL2 + NOBJECTS, objects[TROLL].fixd);
780         juggle(CHASM);
781         if (game.prop[BEAR] != BEAR_DEAD)
782             DESTROY(BEAR);
783         game.prop[CHAIN] = 0;
784         game.fixed[CHAIN] = 0;
785         game.prop[AXE] = 0;
786         game.fixed[AXE] = 0;
787         rspeak(CAVE_CLOSING);
788         game.clock1 = -1;
789         game.closng = true;
790         return true;
791     } else if (game.clock1 < 0)
792         --game.clock2;
793     if (game.clock2 == 0) {
794         /*  Once he's panicked, and clock2 has run out, we come here
795          *  to set up the storage room.  The room has two locs,
796          *  hardwired as LOC_NE and LOC_SW.  At the ne end, we
797          *  place empty bottles, a nursery of plants, a bed of
798          *  oysters, a pile of lamps, rods with stars, sleeping
799          *  dwarves, and him.  At the sw end we place grate over
800          *  treasures, snake pit, covey of caged birds, more rods, and
801          *  pillows.  A mirror stretches across one wall.  Many of the
802          *  objects come from known locations and/or states (e.g. the
803          *  snake is known to have been destroyed and needn't be
804          *  carried away from its old "place"), making the various
805          *  objects be handled differently.  We also drop all other
806          *  objects he might be carrying (lest he have some which
807          *  could cause trouble, such as the keys).  We describe the
808          *  flash of light and trundle back. */
809         game.prop[BOTTLE] = put(BOTTLE, LOC_NE, EMPTY_BOTTLE);
810         game.prop[PLANT] = put(PLANT, LOC_NE, 0);
811         game.prop[OYSTER] = put(OYSTER, LOC_NE, 0);
812         game.prop[LAMP] = put(LAMP, LOC_NE, 0);
813         game.prop[ROD] = put(ROD, LOC_NE, 0);
814         game.prop[DWARF] = put(DWARF, LOC_NE, 0);
815         game.loc = LOC_NE;
816         game.oldloc = LOC_NE;
817         game.newloc = LOC_NE;
818         /*  Leave the grate with normal (non-negative) property.
819          *  Reuse sign. */
820         put(GRATE, LOC_SW, 0);
821         put(SIGN, LOC_SW, 0);
822         game.prop[SIGN] = ENDGAME_SIGN;
823         game.prop[SNAKE] = put(SNAKE, LOC_SW, 1);
824         game.prop[BIRD] = put(BIRD, LOC_SW, 1);
825         game.prop[CAGE] = put(CAGE, LOC_SW, 0);
826         game.prop[ROD2] = put(ROD2, LOC_SW, 0);
827         game.prop[PILLOW] = put(PILLOW, LOC_SW, 0);
828
829         game.prop[MIRROR] = put(MIRROR, LOC_NE, 0);
830         game.fixed[MIRROR] = LOC_SW;
831
832         for (int i = 1; i <= NOBJECTS; i++) {
833             if (TOTING(i))
834                 DESTROY(i);
835         }
836
837         rspeak(CAVE_CLOSED);
838         game.closed = true;
839         return true;
840     }
841
842     return false;
843 }
844
845 static void lampcheck(void)
846 /* Check game limit and lamp timers */
847 {
848     if (game.prop[LAMP] == LAMP_BRIGHT)
849         --game.limit;
850
851     /*  Another way we can force an end to things is by having the
852      *  lamp give out.  When it gets close, we come here to warn him.
853      *  First following arm checks if the lamp and fresh batteries are
854      *  here, in which case we replace the batteries and continue.
855      *  Second is for other cases of lamp dying.  Eve after it goes
856      *  out, he can explore outside for a while if desired. */
857     if (game.limit <= WARNTIME && HERE(BATTERY) && game.prop[BATTERY] == FRESH_BATTERIES && HERE(LAMP)) {
858         rspeak(REPLACE_BATTERIES);
859         game.prop[BATTERY] = DEAD_BATTERIES;
860         if (TOTING(BATTERY))
861             drop(BATTERY, game.loc);
862         game.limit += BATTERYLIFE;
863         game.lmwarn = false;
864     } else if (game.limit == 0) {
865         game.limit = -1;
866         game.prop[LAMP] = LAMP_DARK;
867         if (HERE(LAMP))
868             rspeak(LAMP_OUT);
869     } else if (game.limit <= WARNTIME) {
870         if (!game.lmwarn && HERE(LAMP)) {
871             game.lmwarn = true;
872             int spk = GET_BATTERIES;
873             if (game.place[BATTERY] == LOC_NOWHERE)spk = LAMP_DIM;
874             if (game.prop[BATTERY] == DEAD_BATTERIES)
875                 spk = MISSING_BATTERIES;
876             rspeak(spk);
877         }
878     }
879 }
880
881 static void listobjects(void)
882 /*  Print out descriptions of objects at this location.  If
883  *  not closing and property value is negative, tally off
884  *  another treasure.  Rug is special case; once seen, its
885  *  game.prop is 1 (dragon on it) till dragon is killed.
886  *  Similarly for chain; game.prop is initially 1 (locked to
887  *  bear).  These hacks are because game.prop=0 is needed to
888  *  get full score. */
889 {
890     if (!DARK(game.loc)) {
891         ++game.abbrev[game.loc];
892         for (int i = game.atloc[game.loc]; i != 0; i = game.link[i]) {
893             long obj = i;
894             if (obj > NOBJECTS)obj = obj - NOBJECTS;
895             if (obj == STEPS && TOTING(NUGGET))
896                 continue;
897             if (game.prop[obj] < 0) {
898                 if (game.closed)
899                     continue;
900                 game.prop[obj] = 0;
901                 if (obj == RUG || obj == CHAIN)
902                     game.prop[obj] = 1;
903                 --game.tally;
904                 /*  Note: There used to be a test here to see whether the
905                  *  player had blown it so badly that he could never ever see
906                  *  the remaining treasures, and if so the lamp was zapped to
907                  *  35 turns.  But the tests were too simple-minded; things
908                  *  like killing the bird before the snake was gone (can never
909                  *  see jewelry), and doing it "right" was hopeless.  E.G.,
910                  *  could cross troll bridge several times, using up all
911                  *  available treasures, breaking vase, using coins to buy
912                  *  batteries, etc., and eventually never be able to get
913                  *  across again.  If bottle were left on far side, could then
914                  *  never get eggs or trident, and the effects propagate.  So
915                  *  the whole thing was flushed.  anyone who makes such a
916                  *  gross blunder isn't likely to find everything else anyway
917                  *  (so goes the rationalisation). */
918             }
919             int kk = game.prop[obj];
920             if (obj == STEPS && game.loc == game.fixed[STEPS])
921                 kk = 1;
922             pspeak(obj, look, kk);
923         }
924     }
925 }
926
927 static bool do_command()
928 /* Get and execute a command */
929 {
930     long V1, V2;
931     long kmod, defn;
932     static long igo = 0;
933     static struct command_t command;
934     command.verb = 0;
935
936     /*  Can't leave cave once it's closing (except by main office). */
937     if (OUTSID(game.newloc) && game.newloc != 0 && game.closng) {
938         rspeak(EXIT_CLOSED);
939         game.newloc = game.loc;
940         if (!game.panic)game.clock2 = PANICTIME;
941         game.panic = true;
942     }
943
944     /*  See if a dwarf has seen him and has come from where he
945      *  wants to go.  If so, the dwarf's blocking his way.  If
946      *  coming from place forbidden to pirate (dwarves rooted in
947      *  place) let him get out (and attacked). */
948     if (game.newloc != game.loc && !FORCED(game.loc) && !CNDBIT(game.loc, COND_NOARRR)) {
949         for (size_t i = 1; i <= NDWARVES - 1; i++) {
950             if (game.odloc[i] == game.newloc && game.dseen[i]) {
951                 game.newloc = game.loc;
952                 rspeak(DWARF_BLOCK);
953                 break;
954             }
955         }
956     }
957     game.loc = game.newloc;
958
959     if (!dwarfmove())
960         croak();
961
962     /*  Describe the current location and (maybe) get next command. */
963
964     for (;;) {
965         if (game.loc == 0)
966             croak();
967         const char* msg = locations[game.loc].description.small;
968         if (MOD(game.abbrev[game.loc], game.abbnum) == 0 || msg == 0)
969             msg = locations[game.loc].description.big;
970         if (!FORCED(game.loc) && DARK(game.loc)) {
971             /*  The easiest way to get killed is to fall into a pit in
972              *  pitch darkness. */
973             if (game.wzdark && PCT(35)) {
974                 rspeak(PIT_FALL);
975                 game.oldlc2 = game.loc;
976                 croak();
977                 continue;       /* back to top of main interpreter loop */
978             }
979             msg = arbitrary_messages[PITCH_DARK];
980         }
981         if (TOTING(BEAR))rspeak(TAME_BEAR);
982         speak(msg);
983         if (FORCED(game.loc)) {
984             if (playermove(command.verb, 1))
985                 return true;
986             else
987                 continue;       /* back to top of main interpreter loop */
988         }
989         if (game.loc == LOC_Y2 && PCT(25) && !game.closng)
990             rspeak(SAYS_PLUGH);
991
992         listobjects();
993
994 L2012:
995         command.verb = 0;
996         game.oldobj = command.obj;
997         command.obj = 0;
998
999 L2600:
1000         checkhints();
1001
1002         /*  If closing time, check for any objects being toted with
1003          *  game.prop < 0 and set the prop to -1-game.prop.  This way
1004          *  objects won't be described until they've been picked up
1005          *  and put down separate from their respective piles.  Don't
1006          *  tick game.clock1 unless well into cave (and not at Y2). */
1007         if (game.closed) {
1008             if (game.prop[OYSTER] < 0 && TOTING(OYSTER))
1009                 pspeak(OYSTER, look, 1);
1010             for (size_t i = 1; i <= NOBJECTS; i++) {
1011                 if (TOTING(i) && game.prop[i] < 0)
1012                     game.prop[i] = -1 - game.prop[i];
1013             }
1014         }
1015         game.wzdark = DARK(game.loc);
1016         if (game.knfloc > 0 && game.knfloc != game.loc)
1017             game.knfloc = 0;
1018
1019         /* This is where we get a new command from the user */
1020         char* input;
1021         for (;;) {
1022           input = get_input();
1023           if (input == NULL)
1024             return(false);
1025           if (word_count(input) > 2)
1026           {
1027             rspeak(TWO_WORDS);
1028             continue;
1029           }
1030           if (strcmp(input, "") != 0)
1031             break;
1032         }
1033         long tokens[4];
1034         tokenize(input, tokens);
1035         command.wd1 = tokens[0];
1036         command.wd1x = tokens[1];
1037         command.wd2 = tokens[2];
1038         command.wd2x = tokens[3];
1039
1040         /*  Every input, check "game.foobar" flag.  If zero, nothing's
1041          *  going on.  If pos, make neg.  If neg, he skipped a word,
1042          *  so make it zero. */
1043 L2607:
1044         game.foobar = (game.foobar > 0 ? -game.foobar : 0);
1045         ++game.turns;
1046
1047         /* If a turn threshold has been met, apply penalties and tell
1048          * the player about it. */
1049         for (int i = 0; i < NTHRESHOLDS; ++i)
1050           {
1051             if (game.turns == turn_thresholds[i].threshold + 1)
1052               {
1053                 game.trnluz += turn_thresholds[i].point_loss;
1054                 speak(turn_thresholds[i].message);
1055               }
1056           }
1057
1058         if (command.verb == SAY && command.wd2 > 0)
1059             command.verb = 0;
1060         if (command.verb == SAY) {
1061             command.part = transitive;
1062             goto Laction;
1063         }
1064         if (closecheck()) {
1065             if (game.closed)
1066                 return true;
1067         } else
1068             lampcheck();
1069
1070         char word1[6];
1071         char word2[6];
1072         packed_to_token(command.wd1, word1);
1073         packed_to_token(command.wd2, word2);
1074         V1 = get_vocab_id(word1);
1075         V2 = get_vocab_id(word2);
1076         if (V1 == ENTER && (V2 == STREAM || V2 == 1000 + WATER)) {
1077             if (LIQLOC(game.loc) == WATER) {
1078                 rspeak(FEET_WET);
1079             } else {
1080                 rspeak(WHERE_QUERY);
1081             }
1082             goto L2012;
1083         }
1084         if (V1 == ENTER && command.wd2 > 0) {
1085             command.wd1 = command.wd2;
1086             command.wd1x = command.wd2x;
1087             wordclear(&command.wd2);
1088         } else {
1089             /* FIXME: Magic numbers */
1090             if (!((V1 != 1000 + WATER && V1 != 1000 + OIL) ||
1091                   (V2 != 1000 + PLANT && V2 != 1000 + DOOR))) {
1092                 if (AT(V2 - 1000))
1093                     command.wd2 = token_to_packed("POUR");
1094             }
1095             if (V1 == 1000 + CAGE && V2 == 1000 + BIRD && HERE(CAGE) && HERE(BIRD))
1096                 command.wd1 = token_to_packed("CATCH");
1097         }
1098 L2620:
1099         if (wordeq(command.wd1, token_to_packed("WEST"))) {
1100             ++game.iwest;
1101             if (game.iwest == 10)
1102                 rspeak(W_IS_WEST);
1103         }
1104         if (wordeq(command.wd1, token_to_packed("GO")) && !wordempty(command.wd2)) {
1105             if (++igo == 10)
1106                 rspeak(GO_UNNEEDED);
1107         }
1108 Lookup:
1109         packed_to_token(command.wd1, word1);
1110         defn = get_vocab_id(word1);
1111         if (defn == -1) {
1112             /* Gee, I don't understand. */
1113             if (fallback_handler(input))
1114                 continue;
1115             rspeak(DONT_KNOW, command.wd1, command.wd1x);
1116             goto L2600;
1117         }
1118         kmod = MOD(defn, 1000);
1119         switch (defn / 1000) {
1120         case 0:
1121             if (playermove(command.verb, kmod))
1122                 return true;
1123             else
1124                 continue;       /* back to top of main interpreter loop */
1125         case 1:
1126             command.part = unknown;
1127             command.obj = kmod;
1128             break;
1129         case 2:
1130             command.part = intransitive;
1131             command.verb = kmod;
1132             break;
1133         case 3:
1134             rspeak(specials[kmod].message);
1135             goto L2012;
1136         default:
1137             BUG(VOCABULARY_TYPE_N_OVER_1000_NOT_BETWEEN_0_AND_3); // LCOV_EXCL_LINE
1138         }
1139
1140 Laction:
1141         switch (action(&command)) {
1142         case GO_TERMINATE:
1143             return true;
1144         case GO_MOVE:
1145             playermove(command.verb, NUL);
1146             return true;
1147         case GO_TOP:
1148             continue;   /* back to top of main interpreter loop */
1149         case GO_CLEAROBJ:
1150             goto L2012;
1151         case GO_CHECKHINT:
1152             goto L2600;
1153         case GO_CHECKFOO:
1154             goto L2607;
1155         case GO_LOOKUP:
1156             goto Lookup;
1157         case GO_WORD2:
1158             /* Get second word for analysis. */
1159             command.wd1 = command.wd2;
1160             command.wd1x = command.wd2x;
1161             wordclear(&command.wd2);
1162             goto L2620;
1163         case GO_UNKNOWN:
1164             /*  Random intransitive verbs come here.  Clear obj just in case
1165              *  (see attack()). */
1166             rspeak(DO_WHAT, command.wd1, command.wd1x);
1167             command.obj = 0;
1168             goto L2600;
1169         case GO_DWARFWAKE:
1170             /*  Oh dear, he's disturbed the dwarves. */
1171             rspeak(DWARVES_AWAKEN);
1172             terminate(endgame);
1173         default:
1174             BUG(ACTION_RETURNED_PHASE_CODE_BEYOND_END_OF_SWITCH); // LCOV_EXCL_LINE
1175         }
1176         linenoiseFree(input);
1177     }
1178 }
1179
1180 /* end */