Reissue 1.18 - same code, corrected metadata.
[open-adventure.git] / advent.h
1 /*
2  * Dungeon types and macros.
3  *
4  * SPDX-FileCopyrightText: (C) 1977, 2005 by Will Crowther and Don Woods
5  * SPDX-License-Identifier: BSD-2-Clause
6  */
7 #include <inttypes.h>
8 #include <stdarg.h>
9 #include <stdbool.h>
10 #include <stdio.h>
11 #include <stdlib.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                                                         \
34         -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)                                                     \
94         (game.objects[obj].found && game.objects[obj].prop == 0)
95 #define PROP_IS_STASHED_OR_UNSEEN(obj)                                         \
96         (!game.objects[obj].found || game.objects[obj].prop < 0)
97 #define PROP_SET_FOUND(obj)                                                    \
98         do {                                                                   \
99                 game.objects[obj].found = true;                                \
100                 game.objects[obj].prop = STATE_FOUND;                          \
101         } while (0)
102 #define PROP_SET_NOT_FOUND(obj) game.objects[obj].found = false
103 #define PROP_IS_NOTFOUND2(g, o) (!g.objects[o].found)
104 #define PROP_IS_INVALID(val) (val < -MAX_STATE || val > MAX_STATE)
105 #define PROP_SET_SEEN(obj) game.objects[object].found = true
106 #endif
107 #define PROP_STASHED(obj) PROP_STASHIFY(game.objects[obj].prop)
108
109 #define PROMPT "> "
110
111 /*
112  *  DESTROY(N)  = Get rid of an item by putting it in LOC_NOWHERE
113  *  MOD(N,M)    = Arithmetic modulus
114  *  TOTING(OBJ) = true if the OBJ is being carried
115  *  AT(OBJ)     = true if on either side of two-placed object
116  *  HERE(OBJ)   = true if the OBJ is at "LOC" (or is being carried)
117  *  CNDBIT(L,N) = true if COND(L) has bit n set (bit 0 is units bit)
118  *  LIQUID()    = object number of liquid in bottle
119  *  LIQLOC(LOC) = object number of liquid (if any) at LOC
120  *  FORCED(LOC) = true if LOC moves without asking for input (COND=2)
121  *  DARK(LOC)   = true if location "LOC" is dark
122  *  PCT(N)      = true N% of the time (N integer from 0 to 100)
123  *  GSTONE(OBJ) = true if OBJ is a gemstone
124  *  FOREST(LOC) = true if LOC is part of the forest
125  *  OUTSID(LOC) = true if location not in the cave
126  *  INSIDE(LOC) = true if location is in the cave or the building at the
127  * beginning of the game INDEEP(LOC) = true if location is in the Hall of Mists
128  * or deeper BUG(X)      = report bug and exit
129  */
130 #define DESTROY(N) move(N, LOC_NOWHERE)
131 #define MOD(N, M) ((N) % (M))
132 #define TOTING(OBJ) (game.objects[OBJ].place == CARRIED)
133 #define AT(OBJ)                                                                \
134         (game.objects[OBJ].place == game.loc ||                                \
135          game.objects[OBJ].fixed == game.loc)
136 #define HERE(OBJ) (AT(OBJ) || TOTING(OBJ))
137 #define CNDBIT(L, N) (tstbit(conditions[L], N))
138 #define LIQUID()                                                               \
139         (game.objects[BOTTLE].prop == WATER_BOTTLE ? WATER                     \
140          : game.objects[BOTTLE].prop == OIL_BOTTLE ? OIL                       \
141                                                    : NO_OBJECT)
142 #define LIQLOC(LOC)                                                            \
143         (CNDBIT((LOC), COND_FLUID) ? CNDBIT((LOC), COND_OILY) ? OIL : WATER    \
144                                    : NO_OBJECT)
145 #define FORCED(LOC) CNDBIT(LOC, COND_FORCED)
146 #define DARK(DUMMY)                                                            \
147         (!CNDBIT(game.loc, COND_LIT) &&                                        \
148          (game.objects[LAMP].prop == LAMP_DARK || !HERE(LAMP)))
149 #define PCT(N) (randrange(100) < (N))
150 #define GSTONE(OBJ)                                                            \
151         ((OBJ) == EMERALD || (OBJ) == RUBY || (OBJ) == AMBER || (OBJ) == SAPPH)
152 #define FOREST(LOC) CNDBIT(LOC, COND_FOREST)
153 #define OUTSID(LOC) (CNDBIT(LOC, COND_ABOVE) || FOREST(LOC))
154 #define INSIDE(LOC) (!OUTSID(LOC) || LOC == LOC_BUILDING)
155 #define INDEEP(LOC) CNDBIT((LOC), COND_DEEP)
156 #define BUG(x) bug(x, #x)
157
158 enum bugtype {
159         SPECIAL_TRAVEL_500_GT_L_GT_300_EXCEEDS_GOTO_LIST,
160         VOCABULARY_TYPE_N_OVER_1000_NOT_BETWEEN_0_AND_3,
161         INTRANSITIVE_ACTION_VERB_EXCEEDS_GOTO_LIST,
162         TRANSITIVE_ACTION_VERB_EXCEEDS_GOTO_LIST,
163         CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION,
164         LOCATION_HAS_NO_TRAVEL_ENTRIES,
165         HINT_NUMBER_EXCEEDS_GOTO_LIST,
166         SPEECHPART_NOT_TRANSITIVE_OR_INTRANSITIVE_OR_UNKNOWN,
167         ACTION_RETURNED_PHASE_CODE_BEYOND_END_OF_SWITCH,
168 };
169
170 enum speaktype { touch, look, hear, study, change };
171
172 enum termination { endgame, quitgame, scoregame };
173
174 enum speechpart { unknown, intransitive, transitive };
175
176 typedef enum { NO_WORD_TYPE, MOTION, OBJECT, ACTION, NUMERIC } word_type_t;
177
178 typedef enum scorebonus { none, splatter, defeat, victory } score_t;
179
180 /* Phase codes for action returns.
181  * These were at one time FORTRAN line numbers.
182  */
183 typedef enum {
184         GO_TERMINATE,
185         GO_MOVE,
186         GO_TOP,
187         GO_CLEAROBJ,
188         GO_CHECKHINT,
189         GO_WORD2,
190         GO_UNKNOWN,
191         GO_DWARFWAKE,
192 } phase_codes_t;
193
194 /* Use fixed-lwength types to make the save format moore portable */
195 typedef int32_t vocab_t;  // index into a vocabulary array */
196 typedef int32_t verb_t;   // index into an actions array */
197 typedef int32_t obj_t;    // index into the object array */
198 typedef int32_t loc_t;    // index into the locations array */
199 typedef int32_t turn_t;   // turn counter or threshold */
200 typedef int32_t bool32_t; // turn counter or threshold */
201
202 struct game_t {
203         int32_t lcg_x;
204         int32_t abbnum;   // How often to print int descriptions
205         score_t bonus;    // What kind of finishing bonus we are getting
206         loc_t chloc;      // pirate chest location
207         loc_t chloc2;     // pirate chest alternate location
208         turn_t clock1;    // # turns from finding last treasure to close
209         turn_t clock2;    // # turns from warning till blinding flash
210         bool32_t clshnt;  // has player read the clue in the endgame?
211         bool32_t closed;  // whether we're all the way closed
212         bool32_t closng;  // whether it's closing time yet
213         bool32_t lmwarn;  // has player been warned about lamp going dim?
214         bool32_t novice;  // asked for instructions at start-up?
215         bool32_t panic;   // has player found out he's trapped?
216         bool32_t wzdark;  // whether the loc he's leaving was dark
217         bool32_t blooded; // has player drunk of dragon's blood?
218         int32_t conds;    // min value for cond[loc] if loc has any hints
219         int32_t detail;   // level of detail in descriptions
220
221         /*  dflag controls the level of activation of dwarves:
222          *      0       No dwarf stuff yet (wait until reaches Hall Of Mists)
223          *      1       Reached Hall Of Mists, but hasn't met first dwarf
224          *      2       Met 1t dwarf, others start moving, no knives thrown yet
225          *      3       A knife has been thrown (first set always misses) 3+
226          * Dwarves are mad (increases their accuracy) */
227         int32_t dflag;
228
229         int32_t dkill;  // dwarves killed
230         int32_t dtotal; // total dwarves (including pirate) in loc
231         int32_t foobar; // progress in saying "FEE FIE FOE FOO".
232         int32_t holdng; // number of objects being carried
233         int32_t igo;    // # uses of "go" instead of a direction
234         int32_t iwest;  // # times he's said "west" instead of "w"
235         loc_t knfloc;   // knife location; LOC_NOWERE if none, -1 after caveat
236         turn_t limit;   // lifetime of lamp
237         loc_t loc;      // where player is now
238         loc_t newloc;   // where player is going
239         turn_t numdie;  // number of times killed so far
240         loc_t oldloc;   // where player was
241         loc_t oldlc2;   // where player was two moves ago
242         obj_t oldobj;   // last object player handled
243         int32_t saved;  // point penalty for saves
244         int32_t tally;  // count of treasures gained
245         int32_t thresh; // current threshold for endgame scoring tier
246         bool32_t seenbigwords; // have we red the graffiti in the Giant's Room?
247         turn_t trnluz;         // # points lost so far due to turns used
248         turn_t turns;          // counts commands given (ignores yes/no)
249         char zzword[TOKLEN + 1]; // randomly generated magic word from bird
250         struct {
251                 int32_t abbrev; // has location been seen?
252                 int32_t atloc;  // head of object linked list per location
253         } locs[NLOCATIONS + 1];
254         struct {
255                 int32_t seen; // true if dwarf has seen him
256                 loc_t loc;    // location of dwarves, initially hard-wired in
257                 loc_t oldloc; // prior loc of each dwarf, initially garbage
258         } dwarves[NDWARVES + 1];
259         struct {
260 #ifdef FOUNDBOOL
261                 bool32_t found; // has the location of this object been found?
262 #endif
263                 loc_t fixed;  // fixed location of object (if not IS_FREE)
264                 int32_t prop; // object state */
265                 loc_t place;  // location of object
266         } objects[NOBJECTS + 1];
267         struct {
268                 bool32_t used; // hints[i].used = true iff hint i has been used.
269                 int32_t lc;    // hints[i].lc = show int at LOC with cond bit i
270         } hints[NHINTS];
271         obj_t link[NOBJECTS * 2 + 1]; // object-list links
272 };
273
274 /*
275  * Game application settings - settings, but not state of the game, per se.
276  * This data is not saved in a saved game.
277  */
278 struct settings_t {
279         FILE *logfp;
280         bool oldstyle;
281         bool prompt;
282         char **argv;
283         int argc;
284         int optind;
285         FILE *scriptfp;
286         int debug;
287 };
288
289 typedef struct {
290         char raw[LINESIZE];
291         vocab_t id;
292         word_type_t type;
293 } command_word_t;
294
295 typedef enum {
296         EMPTY,
297         RAW,
298         TOKENIZED,
299         GIVEN,
300         PREPROCESSED,
301         PROCESSING,
302         EXECUTED
303 } command_state_t;
304
305 typedef struct {
306         enum speechpart part;
307         command_word_t word[2];
308         verb_t verb;
309         obj_t obj;
310         command_state_t state;
311 } command_t;
312
313 /*
314  * Bump on save format change.
315  *
316  * Note: Verify that the tests run clean before bumping this, then rebuild the
317  * check files afterwards.  Otherwise you will get a spurious failure due to the
318  * old version having been generated into a check file.
319  */
320 #define SAVE_VERSION 31
321
322 /*
323  * Goes at start of file so saves can be identified by file(1) and the like.
324  */
325 #define ADVENT_MAGIC "open-adventure\n"
326
327 /*
328  * If you change the first three members, the resume function may not properly
329  * reject saves from older versions. Later members can change, but bump the
330  * version when you do that.
331  */
332 struct save_t {
333         char magic[sizeof(ADVENT_MAGIC)];
334         int32_t version;
335         int32_t canary;
336         struct game_t game;
337 };
338
339 extern struct game_t game;
340 extern struct save_t save;
341 extern struct settings_t settings;
342
343 extern char *myreadline(const char *);
344 extern bool get_command_input(command_t *);
345 extern void clear_command(command_t *);
346 extern void speak(const char *, ...);
347 extern void sspeak(int msg, ...);
348 extern void pspeak(vocab_t, enum speaktype, bool, int, ...);
349 extern void rspeak(vocab_t, ...);
350 extern void echo_input(FILE *, const char *, const char *);
351 extern bool silent_yes_or_no(void);
352 extern bool yes_or_no(const char *, const char *, const char *);
353 extern void juggle(obj_t);
354 extern void move(obj_t, loc_t);
355 extern void put(obj_t, loc_t, int);
356 extern void carry(obj_t, loc_t);
357 extern void drop(obj_t, loc_t);
358 extern int atdwrf(loc_t);
359 extern int setbit(int);
360 extern bool tstbit(int, int);
361 extern void set_seed(int32_t);
362 extern int32_t randrange(int32_t);
363 extern int score(enum termination);
364 extern void terminate(enum termination) __attribute__((noreturn));
365 extern int savefile(FILE *);
366 #if defined ADVENT_AUTOSAVE
367 extern void autosave(void);
368 #endif
369 extern int suspend(void);
370 extern int resume(void);
371 extern int restore(FILE *);
372 extern int initialise(void);
373 extern phase_codes_t action(command_t);
374 extern void state_change(obj_t, int);
375 extern bool is_valid(struct game_t);
376 extern void bug(enum bugtype, const char *) __attribute__((__noreturn__));
377
378 /* represent an empty command word */
379 static const command_word_t empty_command_word = {
380     .raw = "",
381     .id = WORD_EMPTY,
382     .type = NO_WORD_TYPE,
383 };
384
385 /* end */