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