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