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