centralize calls to make_zzword()
[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 "dungeon.h"
25
26 #define DIM(a) (sizeof(a)/sizeof(a[0]))
27
28 FILE  *logfp = NULL, *rfp = NULL;
29 bool oldstyle = false;
30 bool prompt = true;
31
32 // LCOV_EXCL_START
33 // exclude from coverage analysis because it requires interactivity to test
34 static void sig_handler(int signo)
35 {
36     if (signo == SIGINT) {
37         if (logfp != NULL)
38             fflush(logfp);
39     }
40     exit(EXIT_FAILURE);
41 }
42 // LCOV_EXCL_STOP
43
44 /*
45  * MAIN PROGRAM
46  *
47  *  Adventure (rev 2: 20 treasures)
48  *  History: Original idea & 5-treasure version (adventures) by Willie Crowther
49  *           15-treasure version (adventure) by Don Woods, April-June 1977
50  *           20-treasure version (rev 2) by Don Woods, August 1978
51  *              Errata fixed: 78/12/25
52  *           Revived 2017 as Open Adventure.
53  */
54
55 static bool do_command(void);
56
57 int main(int argc, char *argv[])
58 {
59     int ch;
60
61     /*  Options. */
62
63 #ifndef ADVENT_NOSAVE
64     const char* opts = "l:or:";
65     const char* usage = "Usage: %s [-l logfilename] [-o] [-r restorefilename]\n";
66 #else
67     const char* opts = "l:o";
68     const char* usage = "Usage: %s [-l logfilename] [-o]\n";
69 #endif
70     while ((ch = getopt(argc, argv, opts)) != EOF) {
71         switch (ch) {
72         case 'l':
73             logfp = fopen(optarg, "w");
74             if (logfp == NULL)
75                 fprintf(stderr,
76                         "advent: can't open logfile %s for write\n",
77                         optarg);
78             signal(SIGINT, sig_handler);
79             break;
80         case 'o':
81             oldstyle = true;
82             prompt = false;
83             break;
84 #ifndef ADVENT_NOSAVE
85         case 'r':
86             rfp = fopen(optarg, "r");
87             if (rfp == NULL)
88                 fprintf(stderr,
89                         "advent: can't open save file %s for read\n",
90                         optarg);
91             signal(SIGINT, sig_handler);
92             break;
93 #endif
94         default:
95             fprintf(stderr,
96                     usage, argv[0]);
97             fprintf(stderr,
98                     "        -l create a log file of your game named as specified'\n");
99             fprintf(stderr,
100                     "        -o 'oldstyle' (no prompt, no command editing, displays 'Initialising...')\n");
101 #ifndef ADVENT_NOSAVE
102             fprintf(stderr,
103                     "        -r restore from specified saved game file\n");
104 #endif
105             exit(EXIT_FAILURE);
106             break;
107         }
108     }
109
110     /*  Initialize game variables */
111     long seedval = initialise();
112
113 #ifndef ADVENT_NOSAVE
114     if (!rfp) {
115         game.novice = yes(arbitrary_messages[WELCOME_YOU], arbitrary_messages[CAVE_NEARBY], arbitrary_messages[NO_MESSAGE]);
116         if (game.novice)
117             game.limit = NOVICELIMIT;
118     } else {
119         restore(rfp);
120     }
121 #endif
122
123     if (logfp)
124         fprintf(logfp, "seed %ld\n", seedval);
125
126     /* interpret commands until EOF or interrupt */
127     for (;;) {
128         if (!do_command())
129             break;
130     }
131     /* show score and exit */
132     terminate(quitgame);
133 }
134
135 static bool fallback_handler(char *buf)
136 /* fallback handler for commands not handled by FORTRANish parser */
137 {
138     long sv;
139     if (sscanf(buf, "seed %ld", &sv) == 1) {
140         set_seed(sv);
141         printf("Seed set to %ld\n", sv);
142         // autogenerated, so don't charge user time for it.
143         --game.turns;
144         return true;
145     }
146     return false;
147 }
148
149 /*  Check if this loc is eligible for any hints.  If been here long
150  *  enough, display.  Ignore "HINTS" < 4 (special stuff, see database
151  *  notes). */
152 static void checkhints(void)
153 {
154     if (conditions[game.loc] >= game.conds) {
155         for (int hint = 0; hint < NHINTS; hint++) {
156             if (game.hinted[hint])
157                 continue;
158             if (!CNDBIT(game.loc, hint + 1 + COND_HBASE))
159                 game.hintlc[hint] = -1;
160             ++game.hintlc[hint];
161             /*  Come here if he's been long enough at required loc(s) for some
162              *  unused hint. */
163             if (game.hintlc[hint] >= hints[hint].turns) {
164                 int i;
165
166                 switch (hint) {
167                 case 0:
168                     /* cave */
169                     if (game.prop[GRATE] == GRATE_CLOSED && !HERE(KEYS))
170                         break;
171                     game.hintlc[hint] = 0;
172                     return;
173                 case 1: /* bird */
174                     if (game.place[BIRD] == game.loc && TOTING(ROD) && game.oldobj == BIRD)
175                         break;
176                     return;
177                 case 2: /* snake */
178                     if (HERE(SNAKE) && !HERE(BIRD))
179                         break;
180                     game.hintlc[hint] = 0;
181                     return;
182                 case 3: /* maze */
183                     if (game.atloc[game.loc] == 0 &&
184                         game.atloc[game.oldloc] == 0 &&
185                         game.atloc[game.oldlc2] == 0 &&
186                         game.holdng > 1)
187                         break;
188                     game.hintlc[hint] = 0;
189                     return;
190                 case 4: /* dark */
191                     if (game.prop[EMERALD] != -1 && game.prop[PYRAMID] == -1)
192                         break;
193                     game.hintlc[hint] = 0;
194                     return;
195                 case 5: /* witt */
196                     break;
197                 case 6: /* urn */
198                     if (game.dflag == 0)
199                         break;
200                     game.hintlc[hint] = 0;
201                     return;
202                 case 7: /* woods */
203                     if (game.atloc[game.loc] == 0 &&
204                         game.atloc[game.oldloc] == 0 &&
205                         game.atloc[game.oldlc2] == 0)
206                         break;
207                     return;
208                 case 8: /* ogre */
209                     i = atdwrf(game.loc);
210                     if (i < 0) {
211                         game.hintlc[hint] = 0;
212                         return;
213                     }
214                     if (HERE(OGRE) && i == 0)
215                         break;
216                     return;
217                 case 9: /* jade */
218                     if (game.tally == 1 && game.prop[JADE] < 0)
219                         break;
220                     game.hintlc[hint] = 0;
221                     return;
222                 default:
223                     BUG(HINT_NUMBER_EXCEEDS_GOTO_LIST); // LCOV_EXCL_LINE
224                     break;
225                 }
226
227                 /* Fall through to hint display */
228                 game.hintlc[hint] = 0;
229                 if (!yes(hints[hint].question, arbitrary_messages[NO_MESSAGE], arbitrary_messages[OK_MAN]))
230                     return;
231                 rspeak(HINT_COST, hints[hint].penalty, hints[hint].penalty);
232                 game.hinted[hint] = yes(arbitrary_messages[WANT_HINT], hints[hint].hint, arbitrary_messages[OK_MAN]);
233                 if (game.hinted[hint] && game.limit > WARNTIME)
234                     game.limit += WARNTIME * hints[hint].penalty;
235             }
236         }
237     }
238 }
239
240 static bool spotted_by_pirate(int i)
241 {
242     if (i != PIRATE)
243         return false;
244
245     /*  The pirate's spotted him.  He leaves him alone once we've
246      *  found chest.  K counts if a treasure is here.  If not, and
247      *  tally=1 for an unseen chest, let the pirate be spotted.  Note
248      *  that game.place[CHEST] = LOC_NOWHERE might mean that he's thrown
249      *  it to the troll, but in that case he's seen the chest
250      *  (game.prop=0). */
251     if (game.loc == game.chloc || game.prop[CHEST] >= 0)
252         return true;
253     int snarfed = 0;
254     bool movechest = false, robplayer = false;
255     for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
256         if (!objects[treasure].is_treasure)
257             continue;
258         /*  Pirate won't take pyramid from plover room or dark
259          *  room (too easy!). */
260         if (treasure == PYRAMID && (game.loc == objects[PYRAMID].plac || game.loc == objects[EMERALD].plac)) {
261             continue;
262         }
263         if (TOTING(treasure) || HERE(treasure))
264             ++snarfed;
265         if (TOTING(treasure)) {
266             movechest = true;
267             robplayer = true;
268         }
269     }
270     /* Force chest placement before player finds last treasure */
271     if (game.tally == 1 && snarfed == 0 && game.place[CHEST] == LOC_NOWHERE && HERE(LAMP) && game.prop[LAMP] == LAMP_BRIGHT) {
272         rspeak(PIRATE_SPOTTED);
273         movechest = true;
274     }
275     /* Do things in this order (chest move before robbery) so chest is listed
276      * last at the maze location. */
277     if (movechest) {
278         move(CHEST, game.chloc);
279         move(MESSAG, game.chloc2);
280         game.dloc[PIRATE] = game.chloc;
281         game.odloc[PIRATE] = game.chloc;
282         game.dseen[PIRATE] = false;
283     } else {
284         /* You might get a hint of the pirate's presence even if the
285          * chest doesn't move... */
286         if (game.odloc[PIRATE] != game.dloc[PIRATE] && PCT(20))
287             rspeak(PIRATE_RUSTLES);
288     }
289     if (robplayer) {
290         rspeak(PIRATE_POUNCES);
291         for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
292             if (!objects[treasure].is_treasure)
293                 continue;
294             if (!(treasure == PYRAMID && (game.loc == objects[PYRAMID].plac || game.loc == objects[EMERALD].plac))) {
295                 if (AT(treasure) && game.fixed[treasure] == 0)
296                     carry(treasure, game.loc);
297                 if (TOTING(treasure))
298                     drop(treasure, game.chloc);
299             }
300         }
301     }
302
303     return true;
304 }
305
306 static bool dwarfmove(void)
307 /* Dwarves move.  Return true if player survives, false if he dies. */
308 {
309     int kk, stick, attack;
310     long tk[21];
311
312     /*  Dwarf stuff.  See earlier comments for description of
313      *  variables.  Remember sixth dwarf is pirate and is thus
314      *  very different except for motion rules. */
315
316     /*  First off, don't let the dwarves follow him into a pit or
317      *  a wall.  Activate the whole mess the first time he gets as
318      *  far as the hall of mists (loc 15).  If game.newloc is
319      *  forbidden to pirate (in particular, if it's beyond the
320      *  troll bridge), bypass dwarf stuff.  That way pirate can't
321      *  steal return toll, and dwarves can't meet the bear.  Also
322      *  means dwarves won't follow him into dead end in maze, but
323      *  c'est la vie.  They'll wait for him outside the dead
324      *  end. */
325     if (game.loc == 0 || FORCED(game.loc) || CNDBIT(game.newloc, COND_NOARRR))
326         return true;
327
328     /* Dwarf activity level ratchets up */
329     if (game.dflag == 0) {
330         if (INDEEP(game.loc))
331             game.dflag = 1;
332         return true;
333     }
334
335     /*  When we encounter the first dwarf, we kill 0, 1, or 2 of
336      *  the 5 dwarves.  If any of the survivors is at loc,
337      *  replace him with the alternate. */
338     if (game.dflag == 1) {
339         if (!INDEEP(game.loc) || (PCT(95) && (!CNDBIT(game.loc, COND_NOBACK) || PCT(85))))
340             return true;
341         game.dflag = 2;
342         for (int i = 1; i <= 2; i++) {
343             int j = 1 + randrange(NDWARVES - 1);
344             if (PCT(50))
345                 game.dloc[j] = 0;
346         }
347
348         /* Alternate initial loc for dwarf, in case one of them
349         *  starts out on top of the adventurer. */
350         for (int i = 1; i <= NDWARVES - 1; i++) {
351             if (game.dloc[i] == game.loc)
352                 game.dloc[i] = DALTLC; //
353             game.odloc[i] = game.dloc[i];
354         }
355         rspeak(DWARF_RAN);
356         drop(AXE, game.loc);
357         return true;
358     }
359
360     /*  Things are in full swing.  Move each dwarf at random,
361      *  except if he's seen us he sticks with us.  Dwarves stay
362      *  deep inside.  If wandering at random, they don't back up
363      *  unless there's no alternative.  If they don't have to
364      *  move, they attack.  And, of course, dead dwarves don't do
365      *  much of anything. */
366     game.dtotal = 0;
367     attack = 0;
368     stick = 0;
369     for (int i = 1; i <= NDWARVES; i++) {
370         if (game.dloc[i] == 0)
371             continue;
372         /*  Fill tk array with all the places this dwarf might go. */
373         unsigned int j = 1;
374         kk = tkey[game.dloc[i]];
375         if (kk != 0)
376             do {
377                 game.newloc = travel[kk].dest;
378                 /* Have we avoided a dwarf encounter? */
379                 if (SPECIAL(game.newloc))
380                     continue;
381                 else if (!INDEEP(game.newloc))
382                     continue;
383                 else if (game.newloc == game.odloc[i])
384                     continue;
385                 else if (j > 1 && game.newloc == tk[j - 1])
386                     continue;
387                 else if (j >= DIM(tk) - 1)
388                     continue;
389                 else if (game.newloc == game.dloc[i])
390                     continue;
391                 else if (FORCED(game.newloc))
392                     continue;
393                 else if (i == PIRATE && CNDBIT(game.newloc, COND_NOARRR))
394                     continue;
395                 else if (travel[kk].nodwarves)
396                     continue;
397                 tk[j++] = game.newloc;
398             } while
399                 (!travel[kk++].stop);
400         tk[j] = game.odloc[i];
401         if (j >= 2)
402             --j;
403         j = 1 + randrange(j);
404         game.odloc[i] = game.dloc[i];
405         game.dloc[i] = tk[j];
406         game.dseen[i] = (game.dseen[i] && INDEEP(game.loc)) || (game.dloc[i] == game.loc || game.odloc[i] == game.loc);
407         if (!game.dseen[i])
408             continue;
409         game.dloc[i] = game.loc;
410         if (spotted_by_pirate(i))
411             continue;
412         /* This threatening little dwarf is in the room with him! */
413         ++game.dtotal;
414         if (game.odloc[i] == game.dloc[i]) {
415             ++attack;
416             if (game.knfloc >= 0)
417                 game.knfloc = game.loc;
418             if (randrange(1000) < 95 * (game.dflag - 2))
419                 ++stick;
420         }
421     }
422
423     /*  Now we know what's happening.  Let's tell the poor sucker about it.
424      *  Note that various of the "knife" messages must have specific relative
425      *  positions in the rspeak database. */
426     if (game.dtotal == 0)
427         return true;
428     rspeak(game.dtotal == 1 ? DWARF_SINGLE : DWARF_PACK, game.dtotal);
429     if (attack == 0)
430         return true;
431     if (game.dflag == 2)
432         game.dflag = 3;
433     if (attack > 1) {
434         rspeak(THROWN_KNIVES, attack);
435         rspeak(stick > 1 ? MULTIPLE_HITS : (stick == 1 ? ONE_HIT : NONE_HIT), stick);
436     } else {
437         rspeak(KNIFE_THROWN);
438         rspeak(MISSES_YOU);
439     }
440     if (stick == 0)
441         return true;
442     game.oldlc2 = game.loc;
443     return false;
444 }
445
446 /*  "You're dead, Jim."
447  *
448  *  If the current loc is zero, it means the clown got himself killed.
449  *  We'll allow this maxdie times.  NDEATHS is automatically set based
450  *  on the number of snide messages available.  Each death results in
451  *  a message (obituaries[n]) which offers reincarnation; if accepted,
452  *  this results in message obituaries[0], obituaries[2], etc.  The
453  *  last time, if he wants another chance, he gets a snide remark as
454  *  we exit.  When reincarnated, all objects being carried get dropped
455  *  at game.oldlc2 (presumably the last place prior to being killed)
456  *  without change of props.  The loop runs backwards to assure that
457  *  the bird is dropped before the cage.  (This kluge could be changed
458  *  once we're sure all references to bird and cage are done by
459  *  keywords.)  The lamp is a special case (it wouldn't do to leave it
460  *  in the cave). It is turned off and left outside the building (only
461  *  if he was carrying it, of course).  He himself is left inside the
462  *  building (and heaven help him if he tries to xyzzy back into the
463  *  cave without the lamp!).  game.oldloc is zapped so he can't just
464  *  "retreat". */
465
466 static void croak(void)
467 /*  Okay, he's dead.  Let's get on with it. */
468 {
469     const char* query = obituaries[game.numdie].query;
470     const char* yes_response = obituaries[game.numdie].yes_response;
471     ++game.numdie;
472     if (game.closng) {
473         /*  He died during closing time.  No resurrection.  Tally up a
474          *  death and exit. */
475         rspeak(DEATH_CLOSING);
476         terminate(endgame);
477     } else if (game.numdie == NDEATHS || !yes(query, yes_response, arbitrary_messages[OK_MAN]))
478         terminate(endgame);
479     else {
480         game.place[WATER] = game.place[OIL] = LOC_NOWHERE;
481         if (TOTING(LAMP))
482             game.prop[LAMP] = LAMP_DARK;
483         for (int j = 1; j <= NOBJECTS; j++) {
484             int i = NOBJECTS + 1 - j;
485             if (TOTING(i)) {
486                 /* Always leave lamp where it's accessible aboveground */
487                 drop(i, (i == LAMP) ? LOC_START : game.oldlc2);
488             }
489         }
490         game.loc = LOC_BUILDING;
491         game.oldloc = game.loc;
492     }
493 }
494
495 static bool traveleq(long a, long b)
496 /* Are two travel entries equal for purposes of skip after failed condition? */
497 {
498     return (travel[a].cond == travel[b].cond)
499         && (travel[a].dest == travel[b].dest);
500 }
501
502 /*  Given the current location in "game.loc", and a motion verb number in
503  *  "motion", put the new location in "game.newloc".  The current loc is saved
504  *  in "game.oldloc" in case he wants to retreat.  The current
505  *  game.oldloc is saved in game.oldlc2, in case he dies.  (if he
506  *  does, game.newloc will be limbo, and game.oldloc will be what killed
507  *  him, so we need game.oldlc2, which is the last place he was
508  *  safe.) */
509
510 static bool playermove( int motion)
511 {
512     int scratchloc, travel_entry = tkey[game.loc];
513     game.newloc = game.loc;
514     if (travel_entry == 0)
515         BUG(LOCATION_HAS_NO_TRAVEL_ENTRIES); // LCOV_EXCL_LINE
516     if (motion == NUL)
517         return true;
518     else if (motion == BACK) {
519         /*  Handle "go back".  Look for verb which goes from game.loc to
520          *  game.oldloc, or to game.oldlc2 If game.oldloc has forced-motion.
521          *  te_tmp saves entry -> forced loc -> previous loc. */
522         motion = game.oldloc;
523         if (FORCED(motion))
524             motion = game.oldlc2;
525         game.oldlc2 = game.oldloc;
526         game.oldloc = game.loc;
527         int spk = 0;
528         if (motion == game.loc)
529             spk = FORGOT_PATH;
530         if (CNDBIT(game.loc, COND_NOBACK))
531             spk = TWIST_TURN;
532         if (spk == 0) {
533             int te_tmp = 0;
534             for (;;) {
535                 scratchloc = travel[travel_entry].dest;
536                 if (scratchloc != motion) {
537                     if (!SPECIAL(scratchloc)) {
538                         if (FORCED(scratchloc) && travel[tkey[scratchloc]].dest == motion)
539                             te_tmp = travel_entry;
540                     }
541                     if (!travel[travel_entry].stop) {
542                         ++travel_entry; /* go to next travel entry for this location */
543                         continue;
544                     }
545                     /* we've reached the end of travel entries for game.loc */
546                     travel_entry = te_tmp;
547                     if (travel_entry == 0) {
548                         rspeak(NOT_CONNECTED);
549                         return true;
550                     }
551                 }
552
553                 motion = travel[travel_entry].motion;
554                 travel_entry = tkey[game.loc];
555                 break; /* fall through to ordinary travel */
556             }
557         } else {
558             rspeak(spk);
559             return true;
560         }
561     } else if (motion == LOOK) {
562         /*  Look.  Can't give more detail.  Pretend it wasn't dark
563          *  (though it may now be dark) so he won't fall into a
564          *  pit while staring into the gloom. */
565         if (game.detail < 3)
566             rspeak(NO_MORE_DETAIL);
567         ++game.detail;
568         game.wzdark = false;
569         game.abbrev[game.loc] = 0;
570         return true;
571     } else if (motion == CAVE) {
572         /*  Cave.  Different messages depending on whether above ground. */
573         rspeak((OUTSID(game.loc) && game.loc != LOC_GRATE) ? FOLLOW_STREAM : NEED_DETAIL);
574         return true;
575     } else {
576         /* none of the specials */
577         game.oldlc2 = game.oldloc;
578         game.oldloc = game.loc;
579     }
580
581     /* Look for a way to fulfil the motion verb passed in - travel_entry indexes
582      * the beginning of the motion entries for here (game.loc). */
583     for (;;) {
584         if (T_TERMINATE(travel[travel_entry]) || travel[travel_entry].motion == motion)
585             break;
586         if (travel[travel_entry].stop) {
587             /*  Couldn't find an entry matching the motion word passed
588              *  in.  Various messages depending on word given. */
589             int spk = CANT_APPLY;
590             if (motion >= EAST && motion <= NW)
591                 spk = BAD_DIRECTION;
592             if (motion == UP || motion == DOWN)
593                 spk = BAD_DIRECTION;
594             if (motion == FORWARD || motion == LEFT || motion == RIGHT)
595                 spk = UNSURE_FACING;
596             if (motion == OUTSIDE || motion == INSIDE)
597                 spk = NO_INOUT_HERE;
598             if (motion == XYZZY || motion == PLUGH)
599                 spk = NOTHING_HAPPENS;
600             if (motion == CRAWL)
601                 spk = WHICH_WAY;
602             rspeak(spk);
603             return true;
604         }
605         ++travel_entry;
606     }
607
608     /* (ESR) We've found a destination that goes with the motion verb.
609      * Next we need to check any conditional(s) on this destination, and
610      * possibly on following entries. */
611     /* FIXME: Magic numbers related to move opcodes */
612     do {
613         for (;;) { /* L12 loop */
614             for (;;) {
615                 long cond = travel[travel_entry].cond;
616                 long arg = MOD(cond, 100);
617                 if (!SPECIAL(cond)) {
618                     /* YAML N and [pct N] conditionals */
619                     if (cond <= 100) {
620                         if (cond == 0 || PCT(cond))
621                             break;
622                         /* else fall through */
623                     }
624                     /* YAML [with OBJ] clause */
625                     if (TOTING(arg) || (cond > 200 && AT(arg)))
626                         break;
627                     /* else fall through to check [not OBJ STATE] */
628                 } else if (game.prop[arg] != cond / 100 - 3)
629                     break;
630
631                 /* We arrive here on conditional failure.
632                  * Skip to next non-matching destination */
633                 long te_tmp = travel_entry;
634                 do {
635                     if (travel[te_tmp].stop)
636                         BUG(CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION); // LCOV_EXCL_LINE
637                     ++te_tmp;
638                 } while
639                     (traveleq(travel_entry, te_tmp));
640                 travel_entry = te_tmp;
641             }
642
643             /* Found an eligible rule, now execute it */
644             game.newloc = travel[travel_entry].dest;
645             if (!SPECIAL(game.newloc))
646                 return true;
647
648             if (game.newloc > 500) {
649                 /* Execute a speak rule */
650                 rspeak(L_SPEAK(game.newloc));
651                 game.newloc = game.loc;
652                 return true;
653             } else {
654                 game.newloc -= SPECIALBASE;
655                 switch (game.newloc) {
656                 case 1:
657                     /* Travel 301.  Plover-alcove passage.  Can carry only
658                      * emerald.  Note: travel table must include "useless"
659                      * entries going through passage, which can never be used
660                      * for actual motion, but can be spotted by "go back". */
661                     /* FIXME: Arithmetic on location numbers */
662                     game.newloc = 99 + 100 - game.loc;
663                     if (game.holdng > 1 || (game.holdng == 1 && !TOTING(EMERALD))) {
664                         game.newloc = game.loc;
665                         rspeak(MUST_DROP);
666                     }
667                     return true;
668                 case 2:
669                     /* Travel 302.  Plover transport.  Drop the
670                      * emerald (only use special travel if toting
671                      * it), so he's forced to use the plover-passage
672                      * to get it out.  Having dropped it, go back and
673                      * pretend he wasn't carrying it after all. */
674                     drop(EMERALD, game.loc);
675                     int te_tmp = travel_entry;
676                     do {
677                         if (travel[te_tmp].stop)
678                             BUG(CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION); // LCOV_EXCL_LINE
679                         ++te_tmp;
680                     } while
681                         (traveleq(travel_entry, te_tmp));
682                     travel_entry = te_tmp;
683                     continue; /* goto L12 */
684                 case 3:
685                     /* Travel 303.  Troll bridge.  Must be done only
686                      * as special motion so that dwarves won't wander
687                      * across and encounter the bear.  (They won't
688                      * follow the player there because that region is
689                      * forbidden to the pirate.)  If
690                      * game.prop(TROLL)=1, he's crossed since paying,
691                      * so step out and block him.  (standard travel
692                      * entries check for game.prop(TROLL)=0.)  Special
693                      * stuff for bear. */
694                     if (game.prop[TROLL] == TROLL_PAIDONCE) {
695                         pspeak(TROLL, look, TROLL_PAIDONCE);
696                         game.prop[TROLL] = TROLL_UNPAID;
697                         move(TROLL2, 0);
698                         move(TROLL2 + NOBJECTS, 0);
699                         move(TROLL, objects[TROLL].plac);
700                         move(TROLL + NOBJECTS, objects[TROLL].fixd);
701                         juggle(CHASM);
702                         game.newloc = game.loc;
703                         return true;
704                     } else {
705                         game.newloc = objects[TROLL].plac + objects[TROLL].fixd - game.loc;
706                         if (game.prop[TROLL] == TROLL_UNPAID)
707                             game.prop[TROLL] = TROLL_PAIDONCE;
708                         if (!TOTING(BEAR))
709                             return true;
710                         rspeak(BRIDGE_COLLAPSE);
711                         game.prop[CHASM] = BRIDGE_WRECKED;
712                         game.prop[TROLL] = TROLL_GONE;
713                         drop(BEAR, game.newloc);
714                         game.fixed[BEAR] = -1;
715                         game.prop[BEAR] = BEAR_DEAD;
716                         game.oldlc2 = game.newloc;
717                         croak();
718                         return true;
719                     }
720                 default:
721                     BUG(SPECIAL_TRAVEL_500_GT_L_GT_300_EXCEEDS_GOTO_LIST); // LCOV_EXCL_LINE
722                 }
723             }
724             break; /* Leave L12 loop */
725         }
726     } while
727     (false);
728 }
729
730 static bool closecheck(void)
731 /*  Handle the closing of the cave.  The cave closes "clock1" turns
732  *  after the last treasure has been located (including the pirate's
733  *  chest, which may of course never show up).  Note that the
734  *  treasures need not have been taken yet, just located.  Hence
735  *  clock1 must be large enough to get out of the cave (it only ticks
736  *  while inside the cave).  When it hits zero, we branch to 10000 to
737  *  start closing the cave, and then sit back and wait for him to try
738  *  to get out.  If he doesn't within clock2 turns, we close the cave;
739  *  if he does try, we assume he panics, and give him a few additional
740  *  turns to get frantic before we close.  When clock2 hits zero, we
741  *  transport him into the final puzzle.  Note that the puzzle depends
742  *  upon all sorts of random things.  For instance, there must be no
743  *  water or oil, since there are beanstalks which we don't want to be
744  *  able to water, since the code can't handle it.  Also, we can have
745  *  no keys, since there is a grate (having moved the fixed object!)
746  *  there separating him from all the treasures.  Most of these
747  *  problems arise from the use of negative prop numbers to suppress
748  *  the object descriptions until he's actually moved the objects. */
749 {
750     if (game.tally == 0 && INDEEP(game.loc) && game.loc != LOC_Y2)
751         --game.clock1;
752
753     /*  When the first warning comes, we lock the grate, destroy
754      *  the bridge, kill all the dwarves (and the pirate), remove
755      *  the troll and bear (unless dead), and set "closng" to
756      *  true.  Leave the dragon; too much trouble to move it.
757      *  from now until clock2 runs out, he cannot unlock the
758      *  grate, move to any location outside the cave, or create
759      *  the bridge.  Nor can he be resurrected if he dies.  Note
760      *  that the snake is already gone, since he got to the
761      *  treasure accessible only via the hall of the mountain
762      *  king. Also, he's been in giant room (to get eggs), so we
763      *  can refer to it.  Also also, he's gotten the pearl, so we
764      *  know the bivalve is an oyster.  *And*, the dwarves must
765      *  have been activated, since we've found chest. */
766     if (game.clock1 == 0) {
767         game.prop[GRATE] = GRATE_CLOSED;
768         game.prop[FISSURE] = UNBRIDGED;
769         for (int i = 1; i <= NDWARVES; i++) {
770             game.dseen[i] = false;
771             game.dloc[i] = 0;
772         }
773         move(TROLL, 0);
774         move(TROLL + NOBJECTS, 0);
775         move(TROLL2, objects[TROLL].plac);
776         move(TROLL2 + NOBJECTS, objects[TROLL].fixd);
777         juggle(CHASM);
778         if (game.prop[BEAR] != BEAR_DEAD)
779             DESTROY(BEAR);
780         game.prop[CHAIN] = CHAIN_HEAP;
781         game.fixed[CHAIN] = CHAIN_HEAP;
782         game.prop[AXE] = 0;
783         game.fixed[AXE] = 0;
784         rspeak(CAVE_CLOSING);
785         game.clock1 = -1;
786         game.closng = true;
787         return true;
788     } else if (game.clock1 < 0)
789         --game.clock2;
790     if (game.clock2 == 0) {
791         /*  Once he's panicked, and clock2 has run out, we come here
792          *  to set up the storage room.  The room has two locs,
793          *  hardwired as LOC_NE and LOC_SW.  At the ne end, we
794          *  place empty bottles, a nursery of plants, a bed of
795          *  oysters, a pile of lamps, rods with stars, sleeping
796          *  dwarves, and him.  At the sw end we place grate over
797          *  treasures, snake pit, covey of caged birds, more rods, and
798          *  pillows.  A mirror stretches across one wall.  Many of the
799          *  objects come from known locations and/or states (e.g. the
800          *  snake is known to have been destroyed and needn't be
801          *  carried away from its old "place"), making the various
802          *  objects be handled differently.  We also drop all other
803          *  objects he might be carrying (lest he have some which
804          *  could cause trouble, such as the keys).  We describe the
805          *  flash of light and trundle back. */
806         game.prop[BOTTLE] = put(BOTTLE, LOC_NE, EMPTY_BOTTLE);
807         game.prop[PLANT] = put(PLANT, LOC_NE, 0);
808         game.prop[OYSTER] = put(OYSTER, LOC_NE, 0);
809         game.prop[LAMP] = put(LAMP, LOC_NE, 0);
810         game.prop[ROD] = put(ROD, LOC_NE, 0);
811         game.prop[DWARF] = put(DWARF, LOC_NE, 0);
812         game.loc = LOC_NE;
813         game.oldloc = LOC_NE;
814         game.newloc = LOC_NE;
815         /*  Leave the grate with normal (non-negative) property.
816          *  Reuse sign. */
817         put(GRATE, LOC_SW, 0);
818         put(SIGN, LOC_SW, 0);
819         game.prop[SIGN] = ENDGAME_SIGN;
820         game.prop[SNAKE] = put(SNAKE, LOC_SW, 1);
821         game.prop[BIRD] = put(BIRD, LOC_SW, 1);
822         game.prop[CAGE] = put(CAGE, LOC_SW, 0);
823         game.prop[ROD2] = put(ROD2, LOC_SW, 0);
824         game.prop[PILLOW] = put(PILLOW, LOC_SW, 0);
825
826         game.prop[MIRROR] = put(MIRROR, LOC_NE, 0);
827         game.fixed[MIRROR] = LOC_SW;
828
829         for (int i = 1; i <= NOBJECTS; i++) {
830             if (TOTING(i))
831                 DESTROY(i);
832         }
833
834         rspeak(CAVE_CLOSED);
835         game.closed = true;
836         return true;
837     }
838
839     return false;
840 }
841
842 static void lampcheck(void)
843 /* Check game limit and lamp timers */
844 {
845     if (game.prop[LAMP] == LAMP_BRIGHT)
846         --game.limit;
847
848     /*  Another way we can force an end to things is by having the
849      *  lamp give out.  When it gets close, we come here to warn him.
850      *  First following arm checks if the lamp and fresh batteries are
851      *  here, in which case we replace the batteries and continue.
852      *  Second is for other cases of lamp dying.  Eve after it goes
853      *  out, he can explore outside for a while if desired. */
854     if (game.limit <= WARNTIME && HERE(BATTERY) && game.prop[BATTERY] == FRESH_BATTERIES && HERE(LAMP)) {
855         rspeak(REPLACE_BATTERIES);
856         game.prop[BATTERY] = DEAD_BATTERIES;
857         if (TOTING(BATTERY))
858             drop(BATTERY, game.loc);
859         game.limit += BATTERYLIFE;
860         game.lmwarn = false;
861     } else if (game.limit == 0) {
862         game.limit = -1;
863         game.prop[LAMP] = LAMP_DARK;
864         if (HERE(LAMP))
865             rspeak(LAMP_OUT);
866     } else if (game.limit <= WARNTIME) {
867         if (!game.lmwarn && HERE(LAMP)) {
868             game.lmwarn = true;
869             int spk = GET_BATTERIES;
870             if (game.place[BATTERY] == LOC_NOWHERE)
871                 spk = LAMP_DIM;
872             if (game.prop[BATTERY] == DEAD_BATTERIES)
873                 spk = MISSING_BATTERIES;
874             rspeak(spk);
875         }
876     }
877 }
878
879 static void listobjects(void)
880 /*  Print out descriptions of objects at this location.  If
881  *  not closing and property value is negative, tally off
882  *  another treasure.  Rug is special case; once seen, its
883  *  game.prop is RUG_DRAGON (dragon on it) till dragon is killed.
884  *  Similarly for chain; game.prop is initially CHAINING_BEAR (locked to
885  *  bear).  These hacks are because game.prop=0 is needed to
886  *  get full score. */
887 {
888     if (!DARK(game.loc)) {
889         ++game.abbrev[game.loc];
890         for (int i = game.atloc[game.loc]; i != 0; i = game.link[i]) {
891             long obj = i;
892             if (obj > NOBJECTS)
893                 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)
901                     game.prop[RUG] = RUG_DRAGON;
902                 if (obj == CHAIN)
903                     game.prop[CHAIN] = CHAINING_BEAR;
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         free(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             speak(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 */