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