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