Add explanatory comments.
[open-adventure.git] / advent.h
1 /*
2  * Dungeon types and macros.
3  *
4  * SPDX-FileCopyrightText: 1977, 2005 by Will Crowther and Don Woods
5  * SPDX-FileCopyrightText: 2017 by Eric S. Raymond
6  * SPDX-License-Identifier: BSD-2-Clause
7  */
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <stdbool.h>
11 #include <stdarg.h>
12 #include <inttypes.h>
13
14 #include "dungeon.h"
15
16 /* LCG PRNG parameters tested against
17  * Knuth vol. 2. by the original authors */
18 #define LCG_A 1093L
19 #define LCG_C 221587L
20 #define LCG_M 1048576L
21
22 #define LINESIZE       1024
23 #define TOKLEN         5          // # outputting characters in a token */
24 #define NDWARVES       6          // number of dwarves
25 #define PIRATE         NDWARVES   // must be NDWARVES-1 when zero-origin
26 #define DALTLC         LOC_NUGGET // alternate dwarf location
27 #define INVLIMIT       7          // inventory limit (# of objects)
28 #define INTRANSITIVE   -1         // illegal object number
29 #define GAMELIMIT      330        // base limit of turns
30 #define NOVICELIMIT    1000       // limit of turns for novice
31 #define WARNTIME       30         // late game starts at game.limit-this
32 #define FLASHTIME      50         // turns from first warning till blinding flash
33 #define PANICTIME      15         // time left after closing
34 #define BATTERYLIFE    2500       // turn limit increment from batteries
35 #define WORD_NOT_FOUND -1         // "Word not found" flag value for the vocab hash functions.
36 #define WORD_EMPTY     0          // "Word empty" flag value for the vocab hash functions
37 #define PIT_KILL_PROB  35         // Percentage probability of dying from fall in pit.
38 #define CARRIED        -1         // Player is toting it
39 #define READ_MODE      "rb"       // b is not needed for POSIX but harmless
40 #define WRITE_MODE     "wb"       // b is not needed for POSIX but harmless
41
42 /* Special object-state values - integers > 0 are object-specific */
43 #define STATE_NOTFOUND  -1        // 'Not found" state of treasures
44 #define STATE_FOUND     0         // After discovered, before messed with
45 #define STATE_IN_CAVITY 1         // State value common to all gemstones
46
47 /* Special fixed object-state values - integers > 0 are location */
48 #define IS_FIXED -1
49 #define IS_FREE 0
50
51 #ifndef FOUNDBOOL
52 /* (ESR) It is fitting that translation of the original ADVENT should
53  * have left us a maze of twisty little conditionals that resists all
54  * understanding.  Setting and use of what is now the per-object state
55  * member (which used to be an array of its own) is our mystery. This
56  * state tangles together information about whether the object is a
57  * treasure, whether the player has seen it yet, and its activation
58  * state.
59  *
60  * Things we think we know:
61  *
62  * STATE_NOTFOUND is only set on treasures. Non-treasures start the
63  * game in STATE_FOUND.
64  *
65  * PROP_STASHED is supposed to map a state property value to a
66  * negative range, where the object cannot be picked up but the value
67  * can be recovered later.  Various objects get this peoperty when
68  * the cave starts to close. On;y seems to be signifucant for the bird 
69  * and readable objects, notably the clam/oyster - but the code around
70  * those test is difficult to read. */
71 #define PROP_STASHED(obj)       (-1 - game.objects[obj].prop)
72 #define PROP_IS_STASHED(obj)    (game.objects[obj].prop < STATE_NOTFOUND)
73 #define PROP_IS_NOTFOUND(obj)   (game.objects[obj].prop == STATE_NOTFOUND)
74 #define PROP_IS_FOUND(obj)      (game.objects[obj].prop == STATE_FOUND)
75 #define PROP_IS_STASHED_OR_UNSEEN(obj)  (game.objects[obj].prop < 0)
76 #define PROP_SET_FOUND(obj)     (game.objects[obj].prop = STATE_FOUND)
77 #define PROP_SET_NOT_FOUND(obj) (game.objects[obj].prop = STATE_NOTFOUND)
78 #define PROP_IS_NOTFOUND2(g, o) (g.objects[o].prop == STATE_NOTFOUND)
79 #define PROP_IS_INVALID(val)    (val < -MAX_STATE - 1 || val > MAX_STATE)
80 #else
81 /* (ESR) Only the boldest of adventurers will explore here.  This
82  * alternate set of definitions for the macros above was an attempt to
83  * break from out of the state encoding a per-object "found" member
84  * telling whether or not the player has seen the object. These is one
85  * accompanying change in misc.c.  What's broken when you try to use
86  * thus is PROP_IS_STASHED_OR_UNSEEN.
87  */
88 #define PROP_STASHED(obj)       (-game.objects[obj].prop)
89 #define PROP_IS_STASHED(obj)    (game.objects[obj].prop < 0)
90 #define PROP_IS_NOTFOUND(obj)   (!game.objects[obj].found)
91 #define PROP_IS_FOUND(obj)      (game.objects[obj].found && game.objects[obj].prop == 0)
92 #define PROP_IS_STASHED_OR_UNSEEN(obj)  (!game.objects[obj].found || game.objects[obj].prop < 0)
93 #define PROP_SET_FOUND(obj)     do {game.objects[obj].found = true; game.objects[obj].prop = STATE_FOUND;} while(0)
94 #define PROP_SET_NOT_FOUND(obj) game.objects[obj].found = false
95 #define PROP_IS_NOTFOUND2(g, o) (!g.objects[o].found)
96 #define PROP_IS_INVALID(val)    (val < -MAX_STATE || val > MAX_STATE)
97 #endif
98
99 #define PROMPT  "> "
100
101 /*
102  *  DESTROY(N)  = Get rid of an item by putting it in LOC_NOWHERE
103  *  MOD(N,M)    = Arithmetic modulus
104  *  TOTING(OBJ) = true if the OBJ is being carried
105  *  AT(OBJ)     = true if on either side of two-placed object
106  *  HERE(OBJ)   = true if the OBJ is at "LOC" (or is being carried)
107  *  CNDBIT(L,N) = true if COND(L) has bit n set (bit 0 is units bit)
108  *  LIQUID()    = object number of liquid in bottle
109  *  LIQLOC(LOC) = object number of liquid (if any) at LOC
110  *  FORCED(LOC) = true if LOC moves without asking for input (COND=2)
111  *  DARK(LOC)   = true if location "LOC" is dark
112  *  PCT(N)      = true N% of the time (N integer from 0 to 100)
113  *  GSTONE(OBJ) = true if OBJ is a gemstone
114  *  FOREST(LOC) = true if LOC is part of the forest
115  *  OUTSID(LOC) = true if location not in the cave
116  *  INSIDE(LOC) = true if location is in the cave or the building at the beginning of the game
117  *  INDEEP(LOC) = true if location is in the Hall of Mists or deeper
118  *  BUG(X)      = report bug and exit
119  */
120 #define DESTROY(N)   move(N, LOC_NOWHERE)
121 #define MOD(N,M)     ((N) % (M))
122 #define TOTING(OBJ)  (game.objects[OBJ].place == CARRIED)
123 #define AT(OBJ)      (game.objects[OBJ].place == game.loc || game.objects[OBJ].fixed == game.loc)
124 #define HERE(OBJ)    (AT(OBJ) || TOTING(OBJ))
125 #define CNDBIT(L,N)  (tstbit(conditions[L],N))
126 #define LIQUID()     (game.objects[BOTTLE].prop == WATER_BOTTLE? WATER : game.objects[BOTTLE].prop == OIL_BOTTLE ? OIL : NO_OBJECT )
127 #define LIQLOC(LOC)  (CNDBIT((LOC),COND_FLUID)? CNDBIT((LOC),COND_OILY) ? OIL : WATER : NO_OBJECT)
128 #define FORCED(LOC)  CNDBIT(LOC, COND_FORCED)
129 #define DARK(DUMMY)  (!CNDBIT(game.loc,COND_LIT) && (game.objects[LAMP].prop == LAMP_DARK || !HERE(LAMP)))
130 #define PCT(N)       (randrange(100) < (N))
131 #define GSTONE(OBJ)  ((OBJ) == EMERALD || (OBJ) == RUBY || (OBJ) == AMBER || (OBJ) == SAPPH)
132 #define FOREST(LOC)  CNDBIT(LOC, COND_FOREST)
133 #define OUTSID(LOC)  (CNDBIT(LOC, COND_ABOVE) || FOREST(LOC))
134 #define INSIDE(LOC)  (!OUTSID(LOC) || LOC == LOC_BUILDING)
135 #define INDEEP(LOC)  CNDBIT((LOC),COND_DEEP)
136 #define BUG(x)       bug(x, #x)
137
138 enum bugtype {
139     SPECIAL_TRAVEL_500_GT_L_GT_300_EXCEEDS_GOTO_LIST,
140     VOCABULARY_TYPE_N_OVER_1000_NOT_BETWEEN_0_AND_3,
141     INTRANSITIVE_ACTION_VERB_EXCEEDS_GOTO_LIST,
142     TRANSITIVE_ACTION_VERB_EXCEEDS_GOTO_LIST,
143     CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION,
144     LOCATION_HAS_NO_TRAVEL_ENTRIES,
145     HINT_NUMBER_EXCEEDS_GOTO_LIST,
146     SPEECHPART_NOT_TRANSITIVE_OR_INTRANSITIVE_OR_UNKNOWN,
147     ACTION_RETURNED_PHASE_CODE_BEYOND_END_OF_SWITCH,
148 };
149
150 enum speaktype {touch, look, hear, study, change};
151
152 enum termination {endgame, quitgame, scoregame};
153
154 enum speechpart {unknown, intransitive, transitive};
155
156 typedef enum {NO_WORD_TYPE, MOTION, OBJECT, ACTION, NUMERIC} word_type_t;
157
158 typedef enum scorebonus {none, splatter, defeat, victory} score_t;
159
160 /* Phase codes for action returns.
161  * These were at one time FORTRAN line numbers.
162  */
163 typedef enum {
164     GO_TERMINATE,
165     GO_MOVE,
166     GO_TOP,
167     GO_CLEAROBJ,
168     GO_CHECKHINT,
169     GO_WORD2,
170     GO_UNKNOWN,
171     GO_DWARFWAKE,
172 } phase_codes_t;
173
174 typedef int vocab_t;  // index into a vocabulary array */
175 typedef int verb_t;   // index into an actions array */
176 typedef int obj_t;    // index into the object array */
177 typedef int loc_t;    // index into the locations array */
178 typedef int turn_t;   // turn counter or threshold */
179
180 struct game_t {
181     int32_t lcg_x;
182     int abbnum;                  // How often to print int descriptions
183     score_t bonus;               // What kind of finishing bonus we are getting
184     loc_t chloc;                 // pirate chest location
185     loc_t chloc2;                // pirate chest alternate location
186     turn_t clock1;               // # turns from finding last treasure to close
187     turn_t clock2;               // # turns from warning till blinding flash
188     bool clshnt;                 // has player read the clue in the endgame?
189     bool closed;                 // whether we're all the way closed
190     bool closng;                 // whether it's closing time yet
191     bool lmwarn;                 // has player been warned about lamp going dim?
192     bool novice;                 // asked for instructions at start-up?
193     bool panic;                  // has player found out he's trapped?
194     bool wzdark;                 // whether the loc he's leaving was dark
195     bool blooded;                // has player drunk of dragon's blood?
196     int conds;                   // min value for cond[loc] if loc has any hints
197     int detail;                  // level of detail in descriptions
198
199     /*  dflag controls the level of activation of dwarves:
200      *  0       No dwarf stuff yet (wait until reaches Hall Of Mists)
201      *  1       Reached Hall Of Mists, but hasn't met first dwarf
202      *  2       Met first dwarf, others start moving, no knives thrown yet
203      *  3       A knife has been thrown (first set always misses)
204      *  3+      Dwarves are mad (increases their accuracy) */
205     int dflag;
206
207     int dkill;                   // dwarves killed
208     int dtotal;                  // total dwarves (including pirate) in loc
209     int foobar;                  // progress in saying "FEE FIE FOE FOO".
210     int holdng;                  // number of objects being carried
211     int igo;                     // # uses of "go" instead of a direction
212     int iwest;                   // # times he's said "west" instead of "w"
213     loc_t knfloc;                // knife location; LOC_NOWERE if none, -1 after caveat
214     turn_t limit;                // lifetime of lamp
215     loc_t loc;                   // where player is now
216     loc_t newloc;                // where player is going
217     turn_t numdie;               // number of times killed so far
218     loc_t oldloc;                // where player was
219     loc_t oldlc2;                // where player was two moves ago
220     obj_t oldobj;                // last object player handled
221     int saved;                   // point penalty for saves
222     int tally;                   // count of treasures gained
223     int thresh;                  // current threshold for endgame scoring tier
224     bool seenbigwords;           // have we red the graffiti in the Giant's Room? 
225     turn_t trnluz;               // # points lost so far due to turns used
226     turn_t turns;                // counts commands given (ignores yes/no)
227     char zzword[TOKLEN + 1];     // randomly generated magic word from bird
228     struct {
229         int abbrev;              // has location been seen?
230         int atloc;               // head of object linked list per location
231     } locs[NLOCATIONS + 1];
232     struct {
233         int seen;                // true if dwarf has seen him
234         loc_t loc;               // location of dwarves, initially hard-wired in
235         loc_t oldloc;            // prior loc of each dwarf, initially garbage
236     } dwarves[NDWARVES + 1];
237     struct {
238 #ifdef FOUNDBOOL
239         bool found;              // has the location of this object bween found?
240 #endif
241         loc_t fixed;             // fixed location of object (if not IS_FREE)
242         int prop;                // object state */
243         loc_t place;             // location of object
244     } objects[NOBJECTS + 1];
245     struct { 
246         bool used;               // hints[i].used = true iff hint i has been used.
247 #ifndef FOUNDBOOL
248         int lc;                 // hints[i].lc = show int at LOC with cond bit i
249 #else
250         int lc;                  // hints[i].lc = show int at LOC with cond bit i
251 #endif
252     } hints[NHINTS];
253     obj_t link[NOBJECTS * 2 + 1];// object-list links
254 };
255
256 /*
257  * Game application settings - settings, but not state of the game, per se.
258  * This data is not saved in a saved game.
259  */
260 struct settings_t {
261     FILE *logfp;
262     bool oldstyle;
263     bool prompt;
264     char **argv;
265     int argc;
266     int optind;
267     FILE *scriptfp;
268     int debug;
269 };
270
271 typedef struct {
272     char raw[LINESIZE];
273     vocab_t id;
274     word_type_t type;
275 } command_word_t;
276
277 typedef enum {EMPTY, RAW, TOKENIZED, GIVEN, PREPROCESSED, PROCESSING, EXECUTED} command_state_t;
278
279 typedef struct {
280     enum speechpart part;
281     command_word_t word[2];
282     verb_t verb;
283     obj_t obj;
284     command_state_t state;
285 } command_t;
286
287 /*
288  * Bump on save format change.
289  *
290  * Note: Verify that the tests run clean before bumping this, then rebuild the check
291  * files afterwards.  Otherwise you will get a spurious failure due to the old version
292  * having been generated into a check file.
293  */
294 #define SAVE_VERSION    30
295
296 /*
297  * Goes at start of file so saves can be identified by file(1) and the like.
298  */
299 #define ADVENT_MAGIC    "open-adventure\n"
300
301 /*
302  * If you change the first three members, the resume function may not properly
303  * reject saves from older versions. Later members can change, but bump the version
304  * when you do that.
305  */
306 struct save_t {
307     char magic[sizeof(ADVENT_MAGIC)];
308     int32_t version;
309     int32_t canary;
310     struct game_t game;
311 };
312
313 extern struct game_t game;
314 extern struct save_t save;
315 extern struct settings_t settings;
316
317 extern char *myreadline(const char *);
318 extern bool get_command_input(command_t *);
319 extern void clear_command(command_t *);
320 extern void speak(const char*, ...);
321 extern void sspeak(int msg, ...);
322 extern void pspeak(vocab_t, enum speaktype, bool, int, ...);
323 extern void rspeak(vocab_t, ...);
324 extern void echo_input(FILE*, const char*, const char*);
325 extern bool silent_yes_or_no(void);
326 extern bool yes_or_no(const char*, const char*, const char*);
327 extern void juggle(obj_t);
328 extern void move(obj_t, loc_t);
329 extern void put(obj_t, loc_t, int);
330 extern void carry(obj_t, loc_t);
331 extern void drop(obj_t, loc_t);
332 extern int atdwrf(loc_t);
333 extern int setbit(int);
334 extern bool tstbit(int, int);
335 extern void set_seed(int32_t);
336 extern int32_t randrange(int32_t);
337 extern int score(enum termination);
338 extern void terminate(enum termination) __attribute__((noreturn));
339 extern int savefile(FILE *);
340 #if defined ADVENT_AUTOSAVE
341 extern void autosave(void);
342 #endif
343 extern int suspend(void);
344 extern int resume(void);
345 extern int restore(FILE *);
346 extern int initialise(void);
347 extern phase_codes_t action(command_t);
348 extern void state_change(obj_t, int);
349 extern bool is_valid(struct game_t);
350 extern void bug(enum bugtype, const char *) __attribute__((__noreturn__));
351
352 /* represent an empty command word */
353 static const command_word_t empty_command_word = {
354     .raw = "",
355     .id = WORD_EMPTY,
356     .type = NO_WORD_TYPE,
357 };
358
359 /* end */