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