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