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