2 * SPDX-FileCopyrightText: Copyright 1977, 2005 by Will Crowther and Don Woods, Copyright 2017 by Eric S. Raymond
3 * SPDX-License-Identifier: BSD-2-Clause
14 #include <editline/readline.h>
17 #define DIM(a) (sizeof(a)/sizeof(a[0]))
19 #if defined ADVENT_AUTOSAVE
20 static FILE* autosave_fp;
23 if (autosave_fp != NULL) {
25 savefile(autosave_fp);
32 // exclude from coverage analysis because it requires interactivity to test
33 static void sig_handler(int signo)
35 if (signo == SIGINT) {
36 if (settings.logfp != NULL)
37 fflush(settings.logfp);
40 #if defined ADVENT_AUTOSAVE
41 if (signo == SIGHUP || signo == SIGTERM)
48 char *myreadline(const char *prompt)
51 * This function isn't required for gameplay, readline() straight
52 * up would suffice for that. It's where we interpret command-line
53 * logfiles for testing purposes.
55 /* Normal case - no script arguments */
56 if (settings.argc == 0) {
57 char *ln = readline(prompt);
59 fputs(prompt, stdout);
64 char *buf = malloc(LINESIZE + 1);
66 if (settings.scriptfp == NULL || feof(settings.scriptfp)) {
67 if (settings.optind >= settings.argc) {
72 char *next = settings.argv[settings.optind++];
74 if (settings.scriptfp != NULL && feof(settings.scriptfp))
75 fclose(settings.scriptfp);
76 if (strcmp(next, "-") == 0)
77 settings.scriptfp = stdin; // LCOV_EXCL_LINE
79 settings.scriptfp = fopen(next, "r");
82 if (isatty(fileno(settings.scriptfp))) {
83 free(buf); // LCOV_EXCL_LINE
84 return readline(prompt); // LCOV_EXCL_LINE
86 char *ln = fgets(buf, LINESIZE, settings.scriptfp);
88 fputs(prompt, stdout);
98 /* Check if this loc is eligible for any hints. If been here int
99 * enough, display. Ignore "HINTS" < 4 (special stuff, see database
101 static void checkhints(void)
103 if (conditions[game.loc] >= game.conds) {
104 for (int hint = 0; hint < NHINTS; hint++) {
105 if (game.hints[hint].used)
107 if (!CNDBIT(game.loc, hint + 1 + COND_HBASE))
108 game.hints[hint].lc = -1;
109 ++game.hints[hint].lc;
110 /* Come here if he's been int enough at required loc(s) for some
112 if (game.hints[hint].lc >= hints[hint].turns) {
118 if (game.objects[GRATE].prop == GRATE_CLOSED && !HERE(KEYS))
120 game.hints[hint].lc = 0;
123 if (game.objects[BIRD].place == game.loc && TOTING(ROD) && game.oldobj == BIRD)
127 if (HERE(SNAKE) && !HERE(BIRD))
129 game.hints[hint].lc = 0;
132 if (game.locs[game.loc].atloc == NO_OBJECT &&
133 game.locs[game.oldloc].atloc == NO_OBJECT &&
134 game.locs[game.oldlc2].atloc == NO_OBJECT &&
137 game.hints[hint].lc = 0;
140 if (!PROP_IS_NOTFOUND(EMERALD) && PROP_IS_NOTFOUND(PYRAMID))
142 game.hints[hint].lc = 0;
149 game.hints[hint].lc = 0;
152 if (game.locs[game.loc].atloc == NO_OBJECT &&
153 game.locs[game.oldloc].atloc == NO_OBJECT &&
154 game.locs[game.oldlc2].atloc == NO_OBJECT)
158 i = atdwrf(game.loc);
160 game.hints[hint].lc = 0;
163 if (HERE(OGRE) && i == 0)
167 if (game.tally == 1 && PROP_IS_STASHED_OR_UNSEEN(JADE))
169 game.hints[hint].lc = 0;
171 default: // LCOV_EXCL_LINE
172 // Should never happen
173 BUG(HINT_NUMBER_EXCEEDS_GOTO_LIST); // LCOV_EXCL_LINE
176 /* Fall through to hint display */
177 game.hints[hint].lc = 0;
178 if (!yes_or_no(hints[hint].question, arbitrary_messages[NO_MESSAGE], arbitrary_messages[OK_MAN]))
180 rspeak(HINT_COST, hints[hint].penalty, hints[hint].penalty);
181 game.hints[hint].used = yes_or_no(arbitrary_messages[WANT_HINT], hints[hint].hint, arbitrary_messages[OK_MAN]);
182 if (game.hints[hint].used && game.limit > WARNTIME)
183 game.limit += WARNTIME * hints[hint].penalty;
189 static bool spotted_by_pirate(int i)
194 /* The pirate's spotted him. Pirate leaves him alone once we've
195 * found chest. K counts if a treasure is here. If not, and
196 * tally=1 for an unseen chest, let the pirate be spotted. Note
197 * that game.objexts,place[CHEST] = LOC_NOWHERE might mean that he's thrown
198 * it to the troll, but in that case he's seen the chest
199 * PROP_IS_FOUND(CHEST) == true. */
200 if (game.loc == game.chloc || !PROP_IS_NOTFOUND(CHEST))
203 bool movechest = false, robplayer = false;
204 for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
205 if (!objects[treasure].is_treasure)
207 /* Pirate won't take pyramid from plover room or dark
208 * room (too easy!). */
209 if (treasure == PYRAMID && (game.loc == objects[PYRAMID].plac ||
210 game.loc == objects[EMERALD].plac)) {
213 if (TOTING(treasure) || HERE(treasure))
215 if (TOTING(treasure)) {
220 /* Force chest placement before player finds last treasure */
221 if (game.tally == 1 && snarfed == 0 && game.objects[CHEST].place == LOC_NOWHERE && HERE(LAMP) && game.objects[LAMP].prop == LAMP_BRIGHT) {
222 rspeak(PIRATE_SPOTTED);
225 /* Do things in this order (chest move before robbery) so chest is listed
226 * last at the maze location. */
228 move(CHEST, game.chloc);
229 move(MESSAG, game.chloc2);
230 game.dwarves[PIRATE].loc = game.chloc;
231 game.dwarves[PIRATE].oldloc = game.chloc;
232 game.dwarves[PIRATE].seen = false;
234 /* You might get a hint of the pirate's presence even if the
235 * chest doesn't move... */
236 if (game.dwarves[PIRATE].oldloc != game.dwarves[PIRATE].loc && PCT(20))
237 rspeak(PIRATE_RUSTLES);
240 rspeak(PIRATE_POUNCES);
241 for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
242 if (!objects[treasure].is_treasure)
244 if (!(treasure == PYRAMID && (game.loc == objects[PYRAMID].plac ||
245 game.loc == objects[EMERALD].plac))) {
246 if (AT(treasure) && game.objects[treasure].fixed == IS_FREE)
247 carry(treasure, game.loc);
248 if (TOTING(treasure))
249 drop(treasure, game.chloc);
257 static bool dwarfmove(void)
258 /* Dwarves move. Return true if player survives, false if he dies. */
260 int kk, stick, attack;
263 /* Dwarf stuff. See earlier comments for description of
264 * variables. Remember sixth dwarf is pirate and is thus
265 * very different except for motion rules. */
267 /* First off, don't let the dwarves follow him into a pit or a
268 * wall. Activate the whole mess the first time he gets as far
269 * as the Hall of Mists (what INDEEP() tests). If game.newloc
270 * is forbidden to pirate (in particular, if it's beyond the
271 * troll bridge), bypass dwarf stuff. That way pirate can't
272 * steal return toll, and dwarves can't meet the bear. Also
273 * means dwarves won't follow him into dead end in maze, but
274 * c'est la vie. They'll wait for him outside the dead end. */
275 if (game.loc == LOC_NOWHERE || FORCED(game.loc) || CNDBIT(game.newloc, COND_NOARRR))
278 /* Dwarf activity level ratchets up */
279 if (game.dflag == 0) {
280 if (INDEEP(game.loc))
285 /* When we encounter the first dwarf, we kill 0, 1, or 2 of
286 * the 5 dwarves. If any of the survivors is at game.loc,
287 * replace him with the alternate. */
288 if (game.dflag == 1) {
289 if (!INDEEP(game.loc) ||
290 (PCT(95) && (!CNDBIT(game.loc, COND_NOBACK) || PCT(85))))
293 for (int i = 1; i <= 2; i++) {
294 int j = 1 + randrange(NDWARVES - 1);
296 game.dwarves[j].loc = 0;
299 /* Alternate initial loc for dwarf, in case one of them
300 * starts out on top of the adventurer. */
301 for (int i = 1; i <= NDWARVES - 1; i++) {
302 if (game.dwarves[i].loc == game.loc)
303 game.dwarves[i].loc = DALTLC; //
304 game.dwarves[i].oldloc = game.dwarves[i].loc;
311 /* Things are in full swing. Move each dwarf at random,
312 * except if he's seen us he sticks with us. Dwarves stay
313 * deep inside. If wandering at random, they don't back up
314 * unless there's no alternative. If they don't have to
315 * move, they attack. And, of course, dead dwarves don't do
316 * much of anything. */
320 for (int i = 1; i <= NDWARVES; i++) {
321 if (game.dwarves[i].loc == 0)
323 /* Fill tk array with all the places this dwarf might go. */
325 kk = tkey[game.dwarves[i].loc];
328 enum desttype_t desttype = travel[kk].desttype;
329 game.newloc = travel[kk].destval;
330 /* Have we avoided a dwarf encounter? */
331 if (desttype != dest_goto)
333 else if (!INDEEP(game.newloc))
335 else if (game.newloc == game.dwarves[i].oldloc)
337 else if (j > 1 && game.newloc == tk[j - 1])
339 else if (j >= DIM(tk) - 1)
340 /* This can't actually happen. */
341 continue; // LCOV_EXCL_LINE
342 else if (game.newloc == game.dwarves[i].loc)
344 else if (FORCED(game.newloc))
346 else if (i == PIRATE && CNDBIT(game.newloc, COND_NOARRR))
348 else if (travel[kk].nodwarves)
350 tk[j++] = game.newloc;
352 (!travel[kk++].stop);
353 tk[j] = game.dwarves[i].oldloc;
356 j = 1 + randrange(j);
357 game.dwarves[i].oldloc = game.dwarves[i].loc;
358 game.dwarves[i].loc = tk[j];
359 game.dwarves[i].seen = (game.dwarves[i].seen && INDEEP(game.loc)) ||
360 (game.dwarves[i].loc == game.loc ||
361 game.dwarves[i].oldloc == game.loc);
362 if (!game.dwarves[i].seen)
364 game.dwarves[i].loc = game.loc;
365 if (spotted_by_pirate(i))
367 /* This threatening little dwarf is in the room with him! */
369 if (game.dwarves[i].oldloc == game.dwarves[i].loc) {
371 if (game.knfloc >= LOC_NOWHERE)
372 game.knfloc = game.loc;
373 if (randrange(1000) < 95 * (game.dflag - 2))
378 /* Now we know what's happening. Let's tell the poor sucker about it. */
379 if (game.dtotal == 0)
381 rspeak(game.dtotal == 1 ? DWARF_SINGLE : DWARF_PACK, game.dtotal);
387 rspeak(THROWN_KNIVES, attack);
388 rspeak(stick > 1 ? MULTIPLE_HITS : (stick == 1 ? ONE_HIT : NONE_HIT), stick);
390 rspeak(KNIFE_THROWN);
391 rspeak(stick ? GETS_YOU : MISSES_YOU);
395 game.oldlc2 = game.loc;
399 /* "You're dead, Jim."
401 * If the current loc is zero, it means the clown got himself killed.
402 * We'll allow this maxdie times. NDEATHS is automatically set based
403 * on the number of snide messages available. Each death results in
404 * a message (obituaries[n]) which offers reincarnation; if accepted,
405 * this results in message obituaries[0], obituaries[2], etc. The
406 * last time, if he wants another chance, he gets a snide remark as
407 * we exit. When reincarnated, all objects being carried get dropped
408 * at game.oldlc2 (presumably the last place prior to being killed)
409 * without change of props. The loop runs backwards to assure that
410 * the bird is dropped before the cage. (This kluge could be changed
411 * once we're sure all references to bird and cage are done by
412 * keywords.) The lamp is a special case (it wouldn't do to leave it
413 * in the cave). It is turned off and left outside the building (only
414 * if he was carrying it, of course). He himself is left inside the
415 * building (and heaven help him if he tries to xyzzy back into the
416 * cave without the lamp!). game.oldloc is zapped so he can't just
418 static void croak(void)
419 /* Okay, he's dead. Let's get on with it. */
421 const char* query = obituaries[game.numdie].query;
422 const char* yes_response = obituaries[game.numdie].yes_response;
427 /* He died during closing time. No resurrection. Tally up a
429 rspeak(DEATH_CLOSING);
431 } else if (!yes_or_no(query, yes_response, arbitrary_messages[OK_MAN])
432 || game.numdie == NDEATHS) {
433 /* Player is asked if he wants to try again. If not, or if
434 * he's already used all of his lives, we end the game */
437 /* If player wishes to continue, we empty the liquids in the
438 * user's inventory, turn off the lamp, and drop all items
440 game.objects[WATER].place = game.objects[OIL].place = LOC_NOWHERE;
442 game.objects[LAMP].prop = LAMP_DARK;
443 for (int j = 1; j <= NOBJECTS; j++) {
444 int i = NOBJECTS + 1 - j;
446 /* Always leave lamp where it's accessible aboveground */
447 drop(i, (i == LAMP) ? LOC_START : game.oldlc2);
450 game.oldloc = game.loc = game.newloc = LOC_BUILDING;
454 static void describe_location(void)
455 /* Describe the location to the user */
457 const char* msg = locations[game.loc].description.small;
459 if (MOD(game.locs[game.loc].abbrev, game.abbnum) == 0 || msg == NO_MESSAGE)
460 msg = locations[game.loc].description.big;
462 if (!FORCED(game.loc) && DARK(game.loc)) {
463 msg = arbitrary_messages[PITCH_DARK];
471 if (game.loc == LOC_Y2 && PCT(25) && !game.closng)
476 static bool traveleq(int a, int b)
477 /* Are two travel entries equal for purposes of skip after failed condition? */
479 return (travel[a].condtype == travel[b].condtype)
480 && (travel[a].condarg1 == travel[b].condarg1)
481 && (travel[a].condarg2 == travel[b].condarg2)
482 && (travel[a].desttype == travel[b].desttype)
483 && (travel[a].destval == travel[b].destval);
486 /* Given the current location in "game.loc", and a motion verb number in
487 * "motion", put the new location in "game.newloc". The current loc is saved
488 * in "game.oldloc" in case he wants to retreat. The current
489 * game.oldloc is saved in game.oldlc2, in case he dies. (if he
490 * does, game.newloc will be limbo, and game.oldloc will be what killed
491 * him, so we need game.oldlc2, which is the last place he was
493 static void playermove(int motion)
495 int scratchloc, travel_entry = tkey[game.loc];
496 game.newloc = game.loc;
497 if (travel_entry == 0)
498 BUG(LOCATION_HAS_NO_TRAVEL_ENTRIES); // LCOV_EXCL_LINE
501 else if (motion == BACK) {
502 /* Handle "go back". Look for verb which goes from game.loc to
503 * game.oldloc, or to game.oldlc2 If game.oldloc has forced-motion.
504 * te_tmp saves entry -> forced loc -> previous loc. */
505 motion = game.oldloc;
507 motion = game.oldlc2;
508 game.oldlc2 = game.oldloc;
509 game.oldloc = game.loc;
510 if (CNDBIT(game.loc, COND_NOBACK)) {
514 if (motion == game.loc) {
521 enum desttype_t desttype = travel[travel_entry].desttype;
522 scratchloc = travel[travel_entry].destval;
523 if (desttype != dest_goto || scratchloc != motion) {
524 if (desttype == dest_goto) {
525 if (FORCED(scratchloc) && travel[tkey[scratchloc]].destval == motion)
526 te_tmp = travel_entry;
528 if (!travel[travel_entry].stop) {
529 ++travel_entry; /* go to next travel entry for this location */
532 /* we've reached the end of travel entries for game.loc */
533 travel_entry = te_tmp;
534 if (travel_entry == 0) {
535 rspeak(NOT_CONNECTED);
540 motion = travel[travel_entry].motion;
541 travel_entry = tkey[game.loc];
542 break; /* fall through to ordinary travel */
544 } else if (motion == LOOK) {
545 /* Look. Can't give more detail. Pretend it wasn't dark
546 * (though it may now be dark) so he won't fall into a
547 * pit while staring into the gloom. */
549 rspeak(NO_MORE_DETAIL);
552 game.locs[game.loc].abbrev = 0;
554 } else if (motion == CAVE) {
555 /* Cave. Different messages depending on whether above ground. */
556 rspeak((OUTSID(game.loc) && game.loc != LOC_GRATE) ? FOLLOW_STREAM : NEED_DETAIL);
559 /* none of the specials */
560 game.oldlc2 = game.oldloc;
561 game.oldloc = game.loc;
564 /* Look for a way to fulfil the motion verb passed in - travel_entry indexes
565 * the beginning of the motion entries for here (game.loc). */
567 if ((travel[travel_entry].motion == HERE) || travel[travel_entry].motion == motion)
569 if (travel[travel_entry].stop) {
570 /* Couldn't find an entry matching the motion word passed
571 * in. Various messages depending on word given. */
583 rspeak(BAD_DIRECTION);
588 rspeak(UNSURE_FACING);
592 rspeak(NO_INOUT_HERE);
596 rspeak(NOTHING_HAPPENS);
609 /* (ESR) We've found a destination that goes with the motion verb.
610 * Next we need to check any conditional(s) on this destination, and
611 * possibly on following entries. */
613 for (;;) { /* L12 loop */
615 enum condtype_t condtype = travel[travel_entry].condtype;
616 int condarg1 = travel[travel_entry].condarg1;
617 int condarg2 = travel[travel_entry].condarg2;
618 if (condtype < cond_not) {
619 /* YAML N and [pct N] conditionals */
620 if (condtype == cond_goto || condtype == cond_pct) {
621 if (condarg1 == 0 || PCT(condarg1))
623 /* else fall through */
625 /* YAML [with OBJ] clause */
626 else if (TOTING(condarg1) || (condtype == cond_with && AT(condarg1)))
628 /* else fall through to check [not OBJ STATE] */
629 } else if (game.objects[condarg1].prop != condarg2)
632 /* We arrive here on conditional failure.
633 * Skip to next non-matching destination */
634 int te_tmp = travel_entry;
636 if (travel[te_tmp].stop)
637 BUG(CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION); // LCOV_EXCL_LINE
640 (traveleq(travel_entry, te_tmp));
641 travel_entry = te_tmp;
644 /* Found an eligible rule, now execute it */
645 enum desttype_t desttype = travel[travel_entry].desttype;
646 game.newloc = travel[travel_entry].destval;
647 if (desttype == dest_goto)
650 if (desttype == dest_speak) {
651 /* Execute a speak rule */
653 game.newloc = game.loc;
656 switch (game.newloc) {
658 /* Special travel 1. Plover-alcove passage. Can carry only
659 * emerald. Note: travel table must include "useless"
660 * entries going through passage, which can never be used
661 * for actual motion, but can be spotted by "go back". */
662 game.newloc = (game.loc == LOC_PLOVER)
665 if (game.holdng > 1 || (game.holdng == 1 && !TOTING(EMERALD))) {
666 game.newloc = game.loc;
671 /* Special travel 2. Plover transport. Drop the
672 * emerald (only use special travel if toting
673 * it), so he's forced to use the plover-passage
674 * to get it out. Having dropped it, go back and
675 * pretend he wasn't carrying it after all. */
676 drop(EMERALD, game.loc);
678 int te_tmp = travel_entry;
680 if (travel[te_tmp].stop)
681 BUG(CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION); // LCOV_EXCL_LINE
684 (traveleq(travel_entry, te_tmp));
685 travel_entry = te_tmp;
687 continue; /* goto L12 */
689 /* Special travel 3. Troll bridge. Must be done
690 * only as special motion so that dwarves won't
691 * wander across and encounter the bear. (They
692 * won't follow the player there because that
693 * region is forbidden to the pirate.) If
694 * game.prop[TROLL]=TROLL_PAIDONCE, he's crossed
695 * since paying, so step out and block him.
696 * (standard travel entries check for
697 * game.prop[TROLL]=TROLL_UNPAID.) Special stuff
699 if (game.objects[TROLL].prop == TROLL_PAIDONCE) {
700 pspeak(TROLL, look, true, TROLL_PAIDONCE);
701 game.objects[TROLL].prop = TROLL_UNPAID;
703 move(TROLL2 + NOBJECTS, IS_FREE);
704 move(TROLL, objects[TROLL].plac);
705 move(TROLL + NOBJECTS, objects[TROLL].fixd);
707 game.newloc = game.loc;
710 game.newloc = objects[TROLL].plac + objects[TROLL].fixd - game.loc;
711 if (game.objects[TROLL].prop == TROLL_UNPAID)
712 game.objects[TROLL].prop = TROLL_PAIDONCE;
715 state_change(CHASM, BRIDGE_WRECKED);
716 game.objects[TROLL].prop = TROLL_GONE;
717 drop(BEAR, game.newloc);
718 game.objects[BEAR].fixed = IS_FIXED;
719 game.objects[BEAR].prop = BEAR_DEAD;
720 game.oldlc2 = game.newloc;
724 default: // LCOV_EXCL_LINE
725 BUG(SPECIAL_TRAVEL_500_GT_L_GT_300_EXCEEDS_GOTO_LIST); // LCOV_EXCL_LINE
728 break; /* Leave L12 loop */
734 static void lampcheck(void)
735 /* Check game limit and lamp timers */
737 if (game.objects[LAMP].prop == LAMP_BRIGHT)
740 /* Another way we can force an end to things is by having the
741 * lamp give out. When it gets close, we come here to warn him.
742 * First following arm checks if the lamp and fresh batteries are
743 * here, in which case we replace the batteries and continue.
744 * Second is for other cases of lamp dying. Even after it goes
745 * out, he can explore outside for a while if desired. */
746 if (game.limit <= WARNTIME) {
747 if (HERE(BATTERY) && game.objects[BATTERY].prop == FRESH_BATTERIES && HERE(LAMP)) {
748 rspeak(REPLACE_BATTERIES);
749 game.objects[BATTERY].prop = DEAD_BATTERIES;
751 /* This code from the original game seems to have been faulty.
752 * No tests ever passed the guard, and with the guard removed
753 * the game hangs when the lamp limit is reached.
756 drop(BATTERY, game.loc);
758 game.limit += BATTERYLIFE;
760 } else if (!game.lmwarn && HERE(LAMP)) {
762 if (game.objects[BATTERY].prop == DEAD_BATTERIES)
763 rspeak(MISSING_BATTERIES);
764 else if (game.objects[BATTERY].place == LOC_NOWHERE)
767 rspeak(GET_BATTERIES);
770 if (game.limit == 0) {
772 game.objects[LAMP].prop = LAMP_DARK;
778 static bool closecheck(void)
779 /* Handle the closing of the cave. The cave closes "clock1" turns
780 * after the last treasure has been located (including the pirate's
781 * chest, which may of course never show up). Note that the
782 * treasures need not have been taken yet, just located. Hence
783 * clock1 must be large enough to get out of the cave (it only ticks
784 * while inside the cave). When it hits zero, we start closing the
785 * cave, and then sit back and wait for him to try to get out. If he
786 * doesn't within clock2 turns, we close the cave; if he does try, we
787 * assume he panics, and give him a few additional turns to get
788 * frantic before we close. When clock2 hits zero, we transport him
789 * into the final puzzle. Note that the puzzle depends upon all
790 * sorts of random things. For instance, there must be no water or
791 * oil, since there are beanstalks which we don't want to be able to
792 * water, since the code can't handle it. Also, we can have no keys,
793 * since there is a grate (having moved the fixed object!) there
794 * separating him from all the treasures. Most of these problems
795 * arise from the use of negative prop numbers to suppress the object
796 * descriptions until he's actually moved the objects. */
798 /* If a turn threshold has been met, apply penalties and tell
799 * the player about it. */
800 for (int i = 0; i < NTHRESHOLDS; ++i) {
801 if (game.turns == turn_thresholds[i].threshold + 1) {
802 game.trnluz += turn_thresholds[i].point_loss;
803 speak(turn_thresholds[i].message);
807 /* Don't tick game.clock1 unless well into cave (and not at Y2). */
808 if (game.tally == 0 && INDEEP(game.loc) && game.loc != LOC_Y2)
811 /* When the first warning comes, we lock the grate, destroy
812 * the bridge, kill all the dwarves (and the pirate), remove
813 * the troll and bear (unless dead), and set "closng" to
814 * true. Leave the dragon; too much trouble to move it.
815 * from now until clock2 runs out, he cannot unlock the
816 * grate, move to any location outside the cave, or create
817 * the bridge. Nor can he be resurrected if he dies. Note
818 * that the snake is already gone, since he got to the
819 * treasure accessible only via the hall of the mountain
820 * king. Also, he's been in giant room (to get eggs), so we
821 * can refer to it. Also also, he's gotten the pearl, so we
822 * know the bivalve is an oyster. *And*, the dwarves must
823 * have been activated, since we've found chest. */
824 if (game.clock1 == 0) {
825 game.objects[GRATE].prop = GRATE_CLOSED;
826 game.objects[FISSURE].prop = UNBRIDGED;
827 for (int i = 1; i <= NDWARVES; i++) {
828 game.dwarves[i].seen = false;
829 game.dwarves[i].loc = LOC_NOWHERE;
832 move(TROLL + NOBJECTS, IS_FREE);
833 move(TROLL2, objects[TROLL].plac);
834 move(TROLL2 + NOBJECTS, objects[TROLL].fixd);
836 if (game.objects[BEAR].prop != BEAR_DEAD)
838 game.objects[CHAIN].prop = CHAIN_HEAP;
839 game.objects[CHAIN].fixed = IS_FREE;
840 game.objects[AXE].prop = AXE_HERE;
841 game.objects[AXE].fixed = IS_FREE;
842 rspeak(CAVE_CLOSING);
846 } else if (game.clock1 < 0)
848 if (game.clock2 == 0) {
849 /* Once he's panicked, and clock2 has run out, we come here
850 * to set up the storage room. The room has two locs,
851 * hardwired as LOC_NE and LOC_SW. At the ne end, we
852 * place empty bottles, a nursery of plants, a bed of
853 * oysters, a pile of lamps, rods with stars, sleeping
854 * dwarves, and him. At the sw end we place grate over
855 * treasures, snake pit, covey of caged birds, more rods, and
856 * pillows. A mirror stretches across one wall. Many of the
857 * objects come from known locations and/or states (e.g. the
858 * snake is known to have been destroyed and needn't be
859 * carried away from its old "place"), making the various
860 * objects be handled differently. We also drop all other
861 * objects he might be carrying (lest he has some which
862 * could cause trouble, such as the keys). We describe the
863 * flash of light and trundle back. */
864 put(BOTTLE, LOC_NE, EMPTY_BOTTLE);
865 put(PLANT, LOC_NE, PLANT_THIRSTY);
866 put(OYSTER, LOC_NE, STATE_FOUND);
867 put(LAMP, LOC_NE, LAMP_DARK);
868 put(ROD, LOC_NE, STATE_FOUND);
869 put(DWARF, LOC_NE, STATE_FOUND);
871 game.oldloc = LOC_NE;
872 game.newloc = LOC_NE;
873 /* Leave the grate with normal (non-negative) property.
877 game.objects[SIGN].prop = ENDGAME_SIGN;
878 put(SNAKE, LOC_SW, SNAKE_CHASED);
879 put(BIRD, LOC_SW, BIRD_CAGED);
880 put(CAGE, LOC_SW, STATE_FOUND);
881 put(ROD2, LOC_SW, STATE_FOUND);
882 put(PILLOW, LOC_SW, STATE_FOUND);
884 put(MIRROR, LOC_NE, STATE_FOUND);
885 game.objects[MIRROR].fixed = LOC_SW;
887 for (int i = 1; i <= NOBJECTS; i++) {
901 static void listobjects(void)
902 /* Print out descriptions of objects at this location. If
903 * not closing and property value is negative, tally off
904 * another treasure. Rug is special case; once seen, its
905 * game.prop is RUG_DRAGON (dragon on it) till dragon is killed.
906 * Similarly for chain; game.prop is initially CHAINING_BEAR (locked to
907 * bear). These hacks are because game.prop=0 is needed to
910 if (!DARK(game.loc)) {
911 ++game.locs[game.loc].abbrev;
912 for (int i = game.locs[game.loc].atloc; i != 0; i = game.link[i]) {
915 obj = obj - NOBJECTS;
916 if (obj == STEPS && TOTING(NUGGET))
918 /* (ESR) Warning: it looks like you could get away with
919 * running this code only on objects with the treasure
920 * property set. Nope. There is mystery here.
922 if (PROP_IS_STASHED_OR_UNSEEN(obj)) {
927 game.objects[RUG].prop = RUG_DRAGON;
929 game.objects[CHAIN].prop = CHAINING_BEAR;
931 game.seenbigwords = true;
933 /* Note: There used to be a test here to see whether the
934 * player had blown it so badly that he could never ever see
935 * the remaining treasures, and if so the lamp was zapped to
936 * 35 turns. But the tests were too simple-minded; things
937 * like killing the bird before the snake was gone (can never
938 * see jewelry), and doing it "right" was hopeless. E.G.,
939 * could cross troll bridge several times, using up all
940 * available treasures, breaking vase, using coins to buy
941 * batteries, etc., and eventually never be able to get
942 * across again. If bottle were left on far side, could then
943 * never get eggs or trident, and the effects propagate. So
944 * the whole thing was flushed. anyone who makes such a
945 * gross blunder isn't likely to find everything else anyway
946 * (so goes the rationalisation). */
948 int kk = game.objects[obj].prop;
950 kk = (game.loc == game.objects[STEPS].fixed)
953 pspeak(obj, look, true, kk);
958 static bool preprocess_command(command_t *command)
959 /* Pre-processes a command input to see if we need to tease out a few specific cases:
960 * - "enter water" or "enter stream":
961 * weird specific case that gets the user wet, and then kicks us back to get another command
963 * Irregular form of input, but should be allowed. We switch back to <verb> <object> form for
964 * further processing.
966 * If in location with grate, we move to that grate. If we're in a number of other places,
967 * we move to the entrance.
968 * - "water plant", "oil plant", "water door", "oil door":
969 * Change to "pour water" or "pour oil" based on context
971 * If bird is present, we change to "carry bird"
973 * Returns true if pre-processing is complete, and we're ready to move to the primary command
974 * processing, false otherwise. */
976 if (command->word[0].type == MOTION && command->word[0].id == ENTER
977 && (command->word[1].id == STREAM || command->word[1].id == WATER)) {
978 if (LIQLOC(game.loc) == WATER)
983 if (command->word[0].type == OBJECT) {
984 /* From OV to VO form */
985 if (command->word[1].type == ACTION) {
986 command_word_t stage = command->word[0];
987 command->word[0] = command->word[1];
988 command->word[1] = stage;
991 if (command->word[0].id == GRATE) {
992 command->word[0].type = MOTION;
993 if (game.loc == LOC_START ||
994 game.loc == LOC_VALLEY ||
995 game.loc == LOC_SLIT) {
996 command->word[0].id = DEPRESSION;
998 if (game.loc == LOC_COBBLE ||
999 game.loc == LOC_DEBRIS ||
1000 game.loc == LOC_AWKWARD ||
1001 game.loc == LOC_BIRDCHAMBER ||
1002 game.loc == LOC_PITTOP) {
1003 command->word[0].id = ENTRANCE;
1006 if ((command->word[0].id == WATER || command->word[0].id == OIL) &&
1007 (command->word[1].id == PLANT || command->word[1].id == DOOR)) {
1008 if (AT(command->word[1].id)) {
1009 command->word[1] = command->word[0];
1010 command->word[0].id = POUR;
1011 command->word[0].type = ACTION;
1012 strncpy(command->word[0].raw, "pour", LINESIZE - 1);
1015 if (command->word[0].id == CAGE && command->word[1].id == BIRD && HERE(CAGE) && HERE(BIRD)) {
1016 command->word[0].id = CARRY;
1017 command->word[0].type = ACTION;
1021 /* If no word type is given for the first word, we assume it's a motion. */
1022 if (command->word[0].type == NO_WORD_TYPE)
1023 command->word[0].type = MOTION;
1025 command->state = PREPROCESSED;
1031 static bool do_move(void)
1032 /* Actually execute the move to the new location and dwarf movement */
1034 /* Can't leave cave once it's closing (except by main office). */
1035 if (OUTSID(game.newloc) && game.newloc != 0 && game.closng) {
1036 rspeak(EXIT_CLOSED);
1037 game.newloc = game.loc;
1039 game.clock2 = PANICTIME;
1043 /* See if a dwarf has seen him and has come from where he
1044 * wants to go. If so, the dwarf's blocking his way. If
1045 * coming from place forbidden to pirate (dwarves rooted in
1046 * place) let him get out (and attacked). */
1047 if (game.newloc != game.loc && !FORCED(game.loc) && !CNDBIT(game.loc, COND_NOARRR)) {
1048 for (size_t i = 1; i <= NDWARVES - 1; i++) {
1049 if (game.dwarves[i].oldloc == game.newloc && game.dwarves[i].seen) {
1050 game.newloc = game.loc;
1051 rspeak(DWARF_BLOCK);
1056 game.loc = game.newloc;
1061 if (game.loc == LOC_NOWHERE)
1064 /* The easiest way to get killed is to fall into a pit in
1065 * pitch darkness. */
1066 if (!FORCED(game.loc) && DARK(game.loc) && game.wzdark && PCT(PIT_KILL_PROB)) {
1068 game.oldlc2 = game.loc;
1076 static bool do_command(void)
1077 /* Get and execute a command */
1079 static command_t command;
1080 clear_command(&command);
1082 /* Describe the current location and (maybe) get next command. */
1083 while (command.state != EXECUTED) {
1084 describe_location();
1086 if (FORCED(game.loc)) {
1093 /* Command not yet given; keep getting commands from user
1094 * until valid command is both given and executed. */
1095 clear_command(&command);
1096 while (command.state <= GIVEN) {
1099 /* If closing time, check for any stashed objects
1100 * being toted and unstash them. This way objects
1101 * won't be described until they've been picked up
1102 * and put down separate from their respective
1104 if ((PROP_IS_NOTFOUND(OYSTER) || PROP_IS_STASHED(OYSTER)) && TOTING(OYSTER))
1105 pspeak(OYSTER, look, true, 1);
1106 for (size_t i = 1; i <= NOBJECTS; i++) {
1107 if (TOTING(i) && (PROP_IS_NOTFOUND(i) || PROP_IS_STASHED(i)))
1108 game.objects[i].prop = PROP_STASHED(i);
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;
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 ) {
1124 /* Get command input from user */
1125 if (!get_command_input(&command))
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
1132 game.foobar = (game.foobar > WORD_EMPTY) ? -game.foobar : WORD_EMPTY;
1135 preprocess_command(&command);
1138 /* check if game is closed, and exit if it is */
1142 /* loop until all words in command are processed */
1143 while (command.state == PREPROCESSED ) {
1144 command.state = PROCESSING;
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);
1153 /* Give user hints of shortcuts */
1154 if (strncasecmp(command.word[0].raw, "west", sizeof("west")) == 0) {
1155 if (++game.iwest == 10)
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);
1163 switch (command.word[0].type) {
1165 playermove(command.word[0].id);
1166 command.state = EXECUTED;
1169 command.part = unknown;
1170 command.obj = command.word[0].id;
1173 if (command.word[1].type == NUMERIC)
1174 command.part = transitive;
1176 command.part = intransitive;
1177 command.verb = command.word[0].id;
1180 if (!settings.oldstyle) {
1181 sspeak(DONT_KNOW, command.word[0].raw);
1182 clear_command(&command);
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
1191 switch (action(command)) {
1193 command.state = EXECUTED;
1197 command.state = EXECUTED;
1201 printf("Word shift\n");
1203 /* Get second word for analysis. */
1204 command.word[0] = command.word[1];
1205 command.word[1] = empty_command_word;
1206 command.state = PREPROCESSED;
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;
1215 /* object cleared; we need to go back to the preprocessing step */
1216 command.state = GIVEN;
1218 case GO_CHECKHINT: // FIXME: re-name to be more contextual; this was previously a label
1219 command.state = GIVEN;
1222 /* Oh dear, he's disturbed the dwarves. */
1223 rspeak(DWARVES_AWAKEN);
1225 case GO_CLEAROBJ: // FIXME: re-name to be more contextual; this was previously a label
1226 clear_command(&command);
1228 case GO_TOP: // FIXME: re-name to be more contextual; this was previously a label
1230 default: // LCOV_EXCL_LINE
1231 BUG(ACTION_RETURNED_PHASE_CODE_BEYOND_END_OF_SWITCH); // LCOV_EXCL_LINE
1233 } /* while command has not been fully processed */
1234 } /* while command is not yet given */
1235 } /* while command is not executed */
1237 /* command completely executed; we return true. */
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.
1252 int main(int argc, char *argv[])
1258 #if defined ADVENT_AUTOSAVE
1259 const char* opts = "dl:oa:";
1260 const char* usage = "Usage: %s [-l logfilename] [-o] [-a filename] [script...]\n";
1262 const char* autosave_filename = NULL;
1263 #elif !defined ADVENT_NOSAVE
1264 const char* opts = "dl:or:";
1265 const char* usage = "Usage: %s [-l logfilename] [-o] [-r restorefilename] [script...]\n";
1268 const char* opts = "dl:o";
1269 const char* usage = "Usage: %s [-l logfilename] [-o] [script...]\n";
1271 while ((ch = getopt(argc, argv, opts)) != EOF) {
1273 case 'd': // LCOV_EXCL_LINE
1274 settings.debug +=1; // LCOV_EXCL_LINE
1275 break; // LCOV_EXCL_LINE
1277 settings.logfp = fopen(optarg, "w");
1278 if (settings.logfp == NULL)
1280 "advent: can't open logfile %s for write\n",
1282 signal(SIGINT, sig_handler);
1285 settings.oldstyle = true;
1286 settings.prompt = false;
1288 #ifdef ADVENT_AUTOSAVE
1290 rfp = fopen(optarg, READ_MODE);
1291 autosave_filename = optarg;
1292 signal(SIGHUP, sig_handler);
1293 signal(SIGTERM, sig_handler);
1295 #elif !defined ADVENT_NOSAVE
1297 rfp = fopen(optarg, "r");
1300 "advent: can't open save file %s for read\n",
1308 " -l create a log file of your game named as specified'\n");
1310 " -o 'oldstyle' (no prompt, no command editing, displays 'Initialising...')\n");
1311 #if defined ADVENT_AUTOSAVE
1313 " -a automatic save/restore from specified saved game file\n");
1314 #elif !defined ADVENT_NOSAVE
1316 " -r restore from specified saved game file\n");
1323 /* copy invocation line part after switches */
1324 settings.argc = argc - optind;
1325 settings.argv = argv + optind;
1326 settings.optind = 0;
1328 /* Initialize game variables */
1329 int seedval = initialise();
1331 #if !defined ADVENT_NOSAVE
1333 game.novice = yes_or_no(arbitrary_messages[WELCOME_YOU], arbitrary_messages[CAVE_NEARBY], arbitrary_messages[NO_MESSAGE]);
1335 game.limit = NOVICELIMIT;
1338 #if defined ADVENT_AUTOSAVE
1342 #if defined ADVENT_AUTOSAVE
1343 if (autosave_filename != NULL) {
1344 if ((autosave_fp = fopen(autosave_filename, WRITE_MODE)) == NULL) {
1345 perror(autosave_filename);
1346 return EXIT_FAILURE;
1352 game.novice = yes_or_no(arbitrary_messages[WELCOME_YOU], arbitrary_messages[CAVE_NEARBY], arbitrary_messages[NO_MESSAGE]);
1354 game.limit = NOVICELIMIT;
1358 fprintf(settings.logfp, "seed %d\n", seedval);
1360 /* interpret commands until EOF or interrupt */
1362 // if we're supposed to move, move
1370 /* show score and exit */
1371 terminate(quitgame);