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