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