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