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