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