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