Structurize the informaruin about dwarves.
[open-adventure.git] / main.c
diff --git a/main.c b/main.c
index 809574b6c35cc82e02208a05862133463aa26e2b..3d17ec9c160b1a775eed7a777947f72086aef555 100644 (file)
--- a/main.c
+++ b/main.c
@@ -1,7 +1,7 @@
 /*
- * Copyright (c) 1977, 2005 by Will Crowther and Don Woods
- * Copyright (c) 2017 by Eric S. Raymond
- * SPDX-License-Identifier: BSD-2-clause
+ * SPDX-FileCopyrightText: 1977, 2005 by Will Crowther and Don Woods
+ * SPDX-FileCopyrightText: 2017 by Eric S. Raymond
+ * SPDX-License-Identifier: BSD-2-Clause
  */
 
 #include <stdlib.h>
 
 #define DIM(a) (sizeof(a)/sizeof(a[0]))
 
+#if defined ADVENT_AUTOSAVE
+static FILE* autosave_fp;
+void autosave(void)
+{
+    if (autosave_fp != NULL) {
+        rewind(autosave_fp);
+        savefile(autosave_fp);
+        fflush(autosave_fp);
+    }
+}
+#endif
+
 // LCOV_EXCL_START
 // exclude from coverage analysis because it requires interactivity to test
 static void sig_handler(int signo)
@@ -26,126 +38,30 @@ static void sig_handler(int signo)
         if (settings.logfp != NULL)
             fflush(settings.logfp);
     }
-    exit(EXIT_FAILURE);
-}
-// LCOV_EXCL_STOP
 
-/*
- * MAIN PROGRAM
- *
- *  Adventure (rev 2: 20 treasures)
- *  History: Original idea & 5-treasure version (adventures) by Willie Crowther
- *           15-treasure version (adventure) by Don Woods, April-June 1977
- *           20-treasure version (rev 2) by Don Woods, August 1978
- *             Errata fixed: 78/12/25
- *          Revived 2017 as Open Adventure.
- */
-
-static bool do_command(void);
-static bool do_move(void);
-
-int main(int argc, char *argv[])
-{
-    int ch;
-
-    /*  Options. */
-
-#ifndef ADVENT_NOSAVE
-    const char* opts = "l:or:";
-    const char* usage = "Usage: %s [-l logfilename] [-o] [-r restorefilename] [script...]\n";
-    FILE *rfp = NULL;
-#else
-    const char* opts = "l:o";
-    const char* usage = "Usage: %s [-l logfilename] [-o] [script...]\n";
-#endif
-    while ((ch = getopt(argc, argv, opts)) != EOF) {
-        switch (ch) {
-        case 'l':
-            settings.logfp = fopen(optarg, "w");
-            if (settings.logfp == NULL)
-                fprintf(stderr,
-                        "advent: can't open logfile %s for write\n",
-                        optarg);
-            signal(SIGINT, sig_handler);
-            break;
-        case 'o':
-            settings.oldstyle = true;
-            settings.prompt = false;
-            break;
-#ifndef ADVENT_NOSAVE
-        case 'r':
-            rfp = fopen(optarg, "r");
-            if (rfp == NULL)
-                fprintf(stderr,
-                        "advent: can't open save file %s for read\n",
-                        optarg);
-            break;
+#if defined ADVENT_AUTOSAVE
+    if (signo == SIGHUP || signo == SIGTERM)
+        autosave();
 #endif
-        default:
-            fprintf(stderr,
-                    usage, argv[0]);
-            fprintf(stderr,
-                    "        -l create a log file of your game named as specified'\n");
-            fprintf(stderr,
-                    "        -o 'oldstyle' (no prompt, no command editing, displays 'Initialising...')\n");
-#ifndef ADVENT_NOSAVE
-            fprintf(stderr,
-                    "        -r restore from specified saved game file\n");
-#endif
-            exit(EXIT_FAILURE);
-            break;
-        }
-    }
-
-    /* copy inncation line part after switches */
-    settings.argc = argc - optind;
-    settings.argv = argv + optind;
-    settings.optind = 0;
-
-    /*  Initialize game variables */
-    int seedval = initialise();
-
-#ifndef ADVENT_NOSAVE
-    if (!rfp) {
-        game.novice = yes_or_no(arbitrary_messages[WELCOME_YOU], arbitrary_messages[CAVE_NEARBY], arbitrary_messages[NO_MESSAGE]);
-        if (game.novice)
-            game.limit = NOVICELIMIT;
-    } else {
-        restore(rfp);
-    }
-#else
-    game.novice = yes_or_no(arbitrary_messages[WELCOME_YOU], arbitrary_messages[CAVE_NEARBY], arbitrary_messages[NO_MESSAGE]);
-    if (game.novice)
-        game.limit = NOVICELIMIT;
-#endif
-
-    if (settings.logfp)
-        fprintf(settings.logfp, "seed %d\n", seedval);
-
-    /* interpret commands until EOF or interrupt */
-    for (;;) {
-        // if we're supposed to move, move
-        if (!do_move())
-            continue;
-
-        // get command
-        if (!do_command())
-            break;
-    }
-    /* show score and exit */
-    terminate(quitgame);
+    exit(EXIT_FAILURE);
 }
+// LCOV_EXCL_STOP
 
 char *myreadline(const char *prompt)
 {
     /*
-     * This function isbn't required for gameplay, readline() straight
-     * up would suffice for tat.  It's where we interpret command-line
+     * This function isn't required for gameplay, readline() straight
+     * up would suffice for that.  It's where we interpret command-line
      * logfiles for testing purposes.
      */
     /* Normal case - no script arguments */
-    if (settings.argc == 0)
-        return readline(prompt);
+    if (settings.argc == 0) {
+       char *ln = readline(prompt);
+       if (ln == NULL) {
+           fputs(prompt, stdout);
+       }
+        return ln;
+    }
 
     char *buf = malloc(LINESIZE + 1);
     for (;;) {
@@ -171,9 +87,9 @@ char *myreadline(const char *prompt)
         } else {
             char *ln = fgets(buf, LINESIZE, settings.scriptfp);
             if (ln != NULL) {
-                fputs(PROMPT, stdout);
+               fputs(prompt, stdout);
                 fputs(ln, stdout);
-                return ln;
+               return ln;
             }
         }
     }
@@ -283,8 +199,7 @@ static bool spotted_by_pirate(int i)
      *  that game.place[CHEST] = LOC_NOWHERE might mean that he's thrown
      *  it to the troll, but in that case he's seen the chest
      *  (game.prop[CHEST] == STATE_FOUND). */
-    if (game.loc == game.chloc ||
-        game.prop[CHEST] != STATE_NOTFOUND)
+    if (game.loc == game.chloc || game.prop[CHEST] != STATE_NOTFOUND)
         return true;
     int snarfed = 0;
     bool movechest = false, robplayer = false;
@@ -297,8 +212,7 @@ static bool spotted_by_pirate(int i)
                                     game.loc == objects[EMERALD].plac)) {
             continue;
         }
-        if (TOTING(treasure) ||
-            HERE(treasure))
+        if (TOTING(treasure) || HERE(treasure))
             ++snarfed;
         if (TOTING(treasure)) {
             movechest = true;
@@ -315,13 +229,13 @@ static bool spotted_by_pirate(int i)
     if (movechest) {
         move(CHEST, game.chloc);
         move(MESSAG, game.chloc2);
-        game.dloc[PIRATE] = game.chloc;
-        game.odloc[PIRATE] = game.chloc;
-        game.dseen[PIRATE] = false;
+        game.dwarves[PIRATE].loc = game.chloc;
+        game.dwarves[PIRATE].oldloc = game.chloc;
+        game.dwarves[PIRATE].seen = false;
     } else {
         /* You might get a hint of the pirate's presence even if the
          * chest doesn't move... */
-        if (game.odloc[PIRATE] != game.dloc[PIRATE] && PCT(20))
+        if (game.dwarves[PIRATE].oldloc != game.dwarves[PIRATE].loc && PCT(20))
             rspeak(PIRATE_RUSTLES);
     }
     if (robplayer) {
@@ -360,9 +274,7 @@ static bool dwarfmove(void)
      *  steal return toll, and dwarves can't meet the bear.  Also
      *  means dwarves won't follow him into dead end in maze, but
      *  c'est la vie.  They'll wait for him outside the dead end. */
-    if (game.loc == LOC_NOWHERE ||
-        FORCED(game.loc) ||
-        CNDBIT(game.newloc, COND_NOARRR))
+    if (game.loc == LOC_NOWHERE || FORCED(game.loc) || CNDBIT(game.newloc, COND_NOARRR))
         return true;
 
     /* Dwarf activity level ratchets up */
@@ -377,22 +289,21 @@ static bool dwarfmove(void)
      *  replace him with the alternate. */
     if (game.dflag == 1) {
         if (!INDEEP(game.loc) ||
-            (PCT(95) && (!CNDBIT(game.loc, COND_NOBACK) ||
-                         PCT(85))))
+            (PCT(95) && (!CNDBIT(game.loc, COND_NOBACK) || PCT(85))))
             return true;
         game.dflag = 2;
         for (int i = 1; i <= 2; i++) {
             int j = 1 + randrange(NDWARVES - 1);
             if (PCT(50))
-                game.dloc[j] = 0;
+                game.dwarves[j].loc = 0;
         }
 
         /* Alternate initial loc for dwarf, in case one of them
         *  starts out on top of the adventurer. */
         for (int i = 1; i <= NDWARVES - 1; i++) {
-            if (game.dloc[i] == game.loc)
-                game.dloc[i] = DALTLC; //
-            game.odloc[i] = game.dloc[i];
+            if (game.dwarves[i].loc == game.loc)
+                game.dwarves[i].loc = DALTLC; //
+            game.dwarves[i].oldloc = game.dwarves[i].loc;
         }
         rspeak(DWARF_RAN);
         drop(AXE, game.loc);
@@ -409,11 +320,11 @@ static bool dwarfmove(void)
     attack = 0;
     stick = 0;
     for (int i = 1; i <= NDWARVES; i++) {
-        if (game.dloc[i] == 0)
+        if (game.dwarves[i].loc == 0)
             continue;
         /*  Fill tk array with all the places this dwarf might go. */
         unsigned int j = 1;
-        kk = tkey[game.dloc[i]];
+        kk = tkey[game.dwarves[i].loc];
         if (kk != 0)
             do {
                 enum desttype_t desttype = travel[kk].desttype;
@@ -423,14 +334,14 @@ static bool dwarfmove(void)
                     continue;
                 else if (!INDEEP(game.newloc))
                     continue;
-                else if (game.newloc == game.odloc[i])
+                else if (game.newloc == game.dwarves[i].oldloc)
                     continue;
                 else if (j > 1 && game.newloc == tk[j - 1])
                     continue;
                 else if (j >= DIM(tk) - 1)
                     /* This can't actually happen. */
                     continue; // LCOV_EXCL_LINE
-                else if (game.newloc == game.dloc[i])
+                else if (game.newloc == game.dwarves[i].loc)
                     continue;
                 else if (FORCED(game.newloc))
                     continue;
@@ -441,25 +352,25 @@ static bool dwarfmove(void)
                 tk[j++] = game.newloc;
             } while
             (!travel[kk++].stop);
-        tk[j] = game.odloc[i];
+        tk[j] = game.dwarves[i].oldloc;
         if (j >= 2)
             --j;
         j = 1 + randrange(j);
-        game.odloc[i] = game.dloc[i];
-        game.dloc[i] = tk[j];
-        game.dseen[i] = (game.dseen[i] && INDEEP(game.loc)) ||
-                        (game.dloc[i] == game.loc ||
-                         game.odloc[i] == game.loc);
-        if (!game.dseen[i])
+        game.dwarves[i].oldloc = game.dwarves[i].loc;
+        game.dwarves[i].loc = tk[j];
+        game.dwarves[i].seen = (game.dwarves[i].seen && INDEEP(game.loc)) ||
+                        (game.dwarves[i].loc == game.loc ||
+                         game.dwarves[i].oldloc == game.loc);
+        if (!game.dwarves[i].seen)
             continue;
-        game.dloc[i] = game.loc;
+        game.dwarves[i].loc = game.loc;
         if (spotted_by_pirate(i))
             continue;
         /* This threatening little dwarf is in the room with him! */
         ++game.dtotal;
-        if (game.odloc[i] == game.dloc[i]) {
+        if (game.dwarves[i].oldloc == game.dwarves[i].loc) {
             ++attack;
-            if (game.knfloc >= 0)
+            if (game.knfloc >= LOC_NOWHERE)
                 game.knfloc = game.loc;
             if (randrange(1000) < 95 * (game.dflag - 2))
                 ++stick;
@@ -547,8 +458,7 @@ static void describe_location(void)
 {
     const char* msg = locations[game.loc].description.small;
 
-    if (MOD(game.abbrev[game.loc], game.abbnum) == 0 ||
-        msg == NO_MESSAGE)
+    if (MOD(game.abbrev[game.loc], game.abbnum) == 0 || msg == NO_MESSAGE)
         msg = locations[game.loc].description.big;
 
     if (!FORCED(game.loc) && DARK(game.loc)) {
@@ -656,8 +566,7 @@ static void playermove(int motion)
     /* Look for a way to fulfil the motion verb passed in - travel_entry indexes
      * the beginning of the motion entries for here (game.loc). */
     for (;;) {
-        if (T_TERMINATE(travel[travel_entry]) ||
-            travel[travel_entry].motion == motion)
+        if ((travel[travel_entry].motion == HERE) || travel[travel_entry].motion == motion)
             break;
         if (travel[travel_entry].stop) {
             /*  Couldn't find an entry matching the motion word passed
@@ -711,14 +620,12 @@ static void playermove(int motion)
                 if (condtype < cond_not) {
                     /* YAML N and [pct N] conditionals */
                     if (condtype == cond_goto || condtype == cond_pct) {
-                        if (condarg1 == 0 ||
-                            PCT(condarg1))
+                        if (condarg1 == 0 || PCT(condarg1))
                             break;
                         /* else fall through */
                     }
                     /* YAML [with OBJ] clause */
-                    else if (TOTING(condarg1) ||
-                             (condtype == cond_with && AT(condarg1)))
+                    else if (TOTING(condarg1) || (condtype == cond_with && AT(condarg1)))
                         break;
                     /* else fall through to check [not OBJ STATE] */
                 } else if (game.prop[condarg1] != condarg2)
@@ -757,8 +664,7 @@ static void playermove(int motion)
                     game.newloc = (game.loc == LOC_PLOVER)
                                   ? LOC_ALCOVE
                                   : LOC_PLOVER;
-                    if (game.holdng > 1 ||
-                        (game.holdng == 1 && !TOTING(EMERALD))) {
+                    if (game.holdng > 1 || (game.holdng == 1 && !TOTING(EMERALD))) {
                         game.newloc = game.loc;
                         rspeak(MUST_DROP);
                     }
@@ -921,8 +827,8 @@ static bool closecheck(void)
         game.prop[GRATE] = GRATE_CLOSED;
         game.prop[FISSURE] = UNBRIDGED;
         for (int i = 1; i <= NDWARVES; i++) {
-            game.dseen[i] = false;
-            game.dloc[i] = LOC_NOWHERE;
+            game.dwarves[i].seen = false;
+            game.dwarves[i].loc = LOC_NOWHERE;
         }
         DESTROY(TROLL);
         move(TROLL + NOBJECTS, IS_FREE);
@@ -1019,6 +925,8 @@ static void listobjects(void)
                     game.prop[RUG] = RUG_DRAGON;
                 if (obj == CHAIN)
                     game.prop[CHAIN] = CHAINING_BEAR;
+               if (obj == EGGS)
+                   game.seenbigwords = true;
                 --game.tally;
                 /*  Note: There used to be a test here to see whether the
                  *  player had blown it so badly that he could never ever see
@@ -1048,10 +956,10 @@ static void listobjects(void)
 static bool preprocess_command(command_t *command)
 /* Pre-processes a command input to see if we need to tease out a few specific cases:
  * - "enter water" or "enter stream":
- *   wierd specific case that gets the user wet, and then kicks us back to get another command
+ *   weird specific case that gets the user wet, and then kicks us back to get another command
  * - <object> <verb>:
  *   Irregular form of input, but should be allowed. We switch back to <verb> <object> form for
- *   furtherprocessing.
+ *   further processing.
  * - "grate":
  *   If in location with grate, we move to that grate. If we're in a number of other places,
  *   we move to the entrance.
@@ -1136,7 +1044,7 @@ static bool do_move(void)
      *  place) let him get out (and attacked). */
     if (game.newloc != game.loc && !FORCED(game.loc) && !CNDBIT(game.loc, COND_NOARRR)) {
         for (size_t i = 1; i <= NDWARVES - 1; i++) {
-            if (game.odloc[i] == game.newloc && game.dseen[i]) {
+            if (game.dwarves[i].oldloc == game.newloc && game.dwarves[i].seen) {
                 game.newloc = game.loc;
                 rspeak(DWARF_BLOCK);
                 break;
@@ -1153,7 +1061,7 @@ static bool do_move(void)
 
     /* The easiest way to get killed is to fall into a pit in
      * pitch darkness. */
-    if (!FORCED(game.loc) && DARK(game.loc) && game.wzdark && PCT(35)) { // FIXME: magic number
+    if (!FORCED(game.loc) && DARK(game.loc) && game.wzdark && PCT(PIT_KILL_PROB)) {
         rspeak(PIT_FALL);
         game.oldlc2 = game.loc;
         croak();
@@ -1163,7 +1071,7 @@ static bool do_move(void)
     return true;
 }
 
-static bool do_command()
+static bool do_command(void)
 /* Get and execute a command */
 {
     static command_t command;
@@ -1214,6 +1122,12 @@ static bool do_command()
                 if (!get_command_input(&command))
                     return false;
 
+                /* Every input, check "foobar" flag. If zero, nothing's going
+                 * on. If pos, make neg. If neg, he skipped a word, so make it
+                 * zero.
+                 */
+                game.foobar = (game.foobar > WORD_EMPTY) ? -game.foobar : WORD_EMPTY;
+
                 ++game.turns;
                 preprocess_command(&command);
             }
@@ -1222,7 +1136,7 @@ static bool do_command()
             if (closecheck() )
                 return true;
 
-            /* loop until all words in command are procesed */
+            /* loop until all words in command are processed */
             while (command.state == PREPROCESSED ) {
                 command.state = PROCESSING;
 
@@ -1313,7 +1227,7 @@ static bool do_command()
                 default: // LCOV_EXCL_LINE
                     BUG(ACTION_RETURNED_PHASE_CODE_BEYOND_END_OF_SWITCH); // LCOV_EXCL_LINE
                 }
-            } /* while command has nob been fully processed */
+            } /* while command has not been fully processed */
         } /* while command is not yet given */
     } /* while command is not executed */
 
@@ -1321,4 +1235,137 @@ static bool do_command()
     return true;
 }
 
+/*
+ * MAIN PROGRAM
+ *
+ *  Adventure (rev 2: 20 treasures)
+ *  History: Original idea & 5-treasure version (adventures) by Willie Crowther
+ *           15-treasure version (adventure) by Don Woods, April-June 1977
+ *           20-treasure version (rev 2) by Don Woods, August 1978
+ *             Errata fixed: 78/12/25
+ *          Revived 2017 as Open Adventure.
+ */
+
+int main(int argc, char *argv[])
+{
+    int ch;
+
+    /*  Options. */
+
+#if defined ADVENT_AUTOSAVE
+    const char* opts = "dl:oa:";
+    const char* usage = "Usage: %s [-l logfilename] [-o] [-a filename] [script...]\n";
+    FILE *rfp = NULL;
+    const char* autosave_filename = NULL;
+#elif !defined ADVENT_NOSAVE
+    const char* opts = "dl:or:";
+    const char* usage = "Usage: %s [-l logfilename] [-o] [-r restorefilename] [script...]\n";
+    FILE *rfp = NULL;
+#else
+    const char* opts = "dl:o";
+    const char* usage = "Usage: %s [-l logfilename] [-o] [script...]\n";
+#endif
+    while ((ch = getopt(argc, argv, opts)) != EOF) {
+        switch (ch) {
+       case 'd': // LCOV_EXCL_LINE
+           settings.debug +=1; // LCOV_EXCL_LINE
+           break; // LCOV_EXCL_LINE
+        case 'l':
+            settings.logfp = fopen(optarg, "w");
+            if (settings.logfp == NULL)
+                fprintf(stderr,
+                        "advent: can't open logfile %s for write\n",
+                        optarg);
+            signal(SIGINT, sig_handler);
+            break;
+        case 'o':
+            settings.oldstyle = true;
+            settings.prompt = false;
+            break;
+#ifdef ADVENT_AUTOSAVE
+        case 'a':
+            rfp = fopen(optarg, READ_MODE);
+            autosave_filename = optarg;
+            signal(SIGHUP, sig_handler);
+            signal(SIGTERM, sig_handler);
+            break;
+#elif !defined ADVENT_NOSAVE
+        case 'r':
+            rfp = fopen(optarg, "r");
+            if (rfp == NULL)
+                fprintf(stderr,
+                        "advent: can't open save file %s for read\n",
+                        optarg);
+            break;
+#endif
+        default:
+            fprintf(stderr,
+                    usage, argv[0]);
+            fprintf(stderr,
+                    "        -l create a log file of your game named as specified'\n");
+            fprintf(stderr,
+                    "        -o 'oldstyle' (no prompt, no command editing, displays 'Initialising...')\n");
+#if defined ADVENT_AUTOSAVE
+            fprintf(stderr,
+                    "        -a automatic save/restore from specified saved game file\n");
+#elif !defined ADVENT_NOSAVE
+            fprintf(stderr,
+                    "        -r restore from specified saved game file\n");
+#endif
+            exit(EXIT_FAILURE);
+            break;
+        }
+    }
+
+    /* copy invocation line part after switches */
+    settings.argc = argc - optind;
+    settings.argv = argv + optind;
+    settings.optind = 0;
+
+    /*  Initialize game variables */
+    int seedval = initialise();
+
+#if !defined ADVENT_NOSAVE
+    if (!rfp) {
+        game.novice = yes_or_no(arbitrary_messages[WELCOME_YOU], arbitrary_messages[CAVE_NEARBY], arbitrary_messages[NO_MESSAGE]);
+        if (game.novice)
+            game.limit = NOVICELIMIT;
+    } else {
+        restore(rfp);
+#if defined ADVENT_AUTOSAVE
+        score(scoregame);
+#endif
+    }
+#if defined ADVENT_AUTOSAVE
+    if (autosave_filename != NULL) {
+        if ((autosave_fp = fopen(autosave_filename, WRITE_MODE)) == NULL) {
+            perror(autosave_filename);
+            return EXIT_FAILURE;
+        }
+        autosave();
+    }
+#endif
+#else
+    game.novice = yes_or_no(arbitrary_messages[WELCOME_YOU], arbitrary_messages[CAVE_NEARBY], arbitrary_messages[NO_MESSAGE]);
+    if (game.novice)
+        game.limit = NOVICELIMIT;
+#endif
+
+    if (settings.logfp)
+        fprintf(settings.logfp, "seed %d\n", seedval);
+
+    /* interpret commands until EOF or interrupt */
+    for (;;) {
+        // if we're supposed to move, move
+        if (!do_move())
+            continue;
+
+        // get command
+        if (!do_command())
+            break;
+    }
+    /* show score and exit */
+    terminate(quitgame);
+}
+
 /* end */