Some vocabulary lookup code can be hidden from main.c.
[open-adventure.git] / misc.c
1 #include <unistd.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <stdarg.h>
6 #include <sys/time.h>
7 #include <ctype.h>
8 #include <editline/readline.h>
9
10 #include "advent.h"
11 #include "dungeon.h"
12
13 static void* xmalloc(size_t size)
14 {
15     void* ptr = malloc(size);
16     if (ptr == NULL) {
17         // LCOV_EXCL_START
18         // exclude from coverage analysis because we can't simulate an out of memory error in testing
19         fprintf(stderr, "Out of memory!\n");
20         exit(EXIT_FAILURE);
21         // LCOV_EXCL_STOP
22     }
23     return (ptr);
24 }
25
26 void tokenize(char* raw, struct command_t *cmd)
27 {
28     memset(cmd, '\0', sizeof(struct command_t));
29
30     /* Bound prefix on the %s would be needed to prevent buffer
31      * overflow.  but we shortstop this more simply by making each
32      * raw-input buffer as long as the enrire inout buffer. */
33     sscanf(raw, "%s%s", cmd->raw1, cmd->raw2);
34
35     /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
36      * effect on raw tokens of packing them into sixbit characters, 5
37      * to a 32-bit word.  This is something the FORTRAN version did
38      * becuse archaic FORTRAN had no string types.  Don Wood's
39      * mechanical translation of 2.5 to C retained the packing and
40      * thus this misfeature.
41      *
42      * It's philosophically questionable whether this is the right
43      * thing to do even in oldstyle mode.  On one hand, the text
44      * mangling was not authorial intent, but a result of limitations
45      * in their tools. On the other, not simulating this misbehavior
46      * goes against the goal of making oldstyle as accurate as
47      * possible an emulation of the original UI.
48      */
49     if (settings.oldstyle) {
50         cmd->raw1[TOKLEN + TOKLEN] = cmd->raw2[TOKLEN + TOKLEN] = '\0';
51         for (size_t i = 0; i < strlen(cmd->raw1); i++)
52             cmd->raw1[i] = toupper(cmd->raw1[i]);
53         for (size_t i = 0; i < strlen(cmd->raw2); i++)
54             cmd->raw2[i] = toupper(cmd->raw2[i]);
55     }
56 }
57
58 /*  I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
59
60 static void vspeak(const char* msg, bool blank, va_list ap)
61 {
62     // Do nothing if we got a null pointer.
63     if (msg == NULL)
64         return;
65
66     // Do nothing if we got an empty string.
67     if (strlen(msg) == 0)
68         return;
69
70     if (blank == true)
71         printf("\n");
72
73     int msglen = strlen(msg);
74
75     // Rendered string
76     ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
77     char* rendered = xmalloc(size);
78     char* renderp = rendered;
79
80     // Handle format specifiers (including the custom %S) by
81     // adjusting the parameter accordingly, and replacing the
82     // specifier with %s.
83     bool pluralize = false;
84     for (int i = 0; i < msglen; i++) {
85         if (msg[i] != '%') {
86             /* Ugh.  Least obtrusive way to deal with artifacts "on the floor"
87              * being dropped outside of both cave and building. */
88             if (strncmp(msg + i, "floor", 5) == 0 && strchr(" .", msg[i + 5]) && !INSIDE(game.loc)) {
89                 strcpy(renderp, "ground");
90                 renderp += 6;
91                 i += 4;
92                 size -= 5;
93             } else {
94                 *renderp++ = msg[i];
95                 size--;
96             }
97         } else {
98             i++;
99             // Integer specifier. In order to accommodate the fact
100             // that PARMS can have both legitimate integers *and*
101             // packed tokens, stringify everything. Future work may
102             // eliminate the need for this.
103             if (msg[i] == 'd') {
104                 long arg = va_arg(ap, long);
105                 int ret = snprintf(renderp, size, "%ld", arg);
106                 if (ret < size) {
107                     renderp += ret;
108                     size -= ret;
109                 }
110                 pluralize = (arg != 1);
111             }
112
113             // Unmodified string specifier.
114             if (msg[i] == 's') {
115                 char *arg = va_arg(ap, char *);
116                 strncat(renderp, arg, size);
117                 size_t len = strlen(renderp);
118                 renderp += len;
119                 size -= len;
120             }
121
122             // Singular/plural specifier.
123             if (msg[i] == 'S') {
124                 // look at the *previous* numeric parameter
125                 if (pluralize) {
126                     *renderp++ = 's';
127                     size--;
128                 }
129             }
130
131             /* Version specifier */
132             if (msg[i] == 'V') {
133                 strcpy(renderp, VERSION);
134                 size_t len = strlen(VERSION);
135                 renderp += len;
136                 size -= len;
137             }
138         }
139     }
140     *renderp = 0;
141
142     // Print the message.
143     printf("%s\n", rendered);
144
145     free(rendered);
146 }
147
148 void speak(const char* msg, ...)
149 {
150     va_list ap;
151     va_start(ap, msg);
152     vspeak(msg, true, ap);
153     va_end(ap);
154 }
155
156 void sspeak(const long msg, ...)
157 {
158     va_list ap;
159     va_start(ap, msg);
160     fputc('\n', stdout);
161     vprintf(arbitrary_messages[msg], ap);
162     fputc('\n', stdout);
163     va_end(ap);
164 }
165
166 void pspeak(vocab_t msg, enum speaktype mode, int skip, bool blank, ...)
167 /* Find the skip+1st message from msg and print it.  Modes are:
168  * feel = for inventory, what you can touch
169  * look = the long description for the state the object is in
170  * listen = the sound for the state the object is in
171  * study = text on the object. */
172 {
173     va_list ap;
174     va_start(ap, blank);
175     switch (mode) {
176     case touch:
177         vspeak(objects[msg].inventory, blank, ap);
178         break;
179     case look:
180         vspeak(objects[msg].descriptions[skip], blank, ap);
181         break;
182     case hear:
183         vspeak(objects[msg].sounds[skip], blank, ap);
184         break;
185     case study:
186         vspeak(objects[msg].texts[skip], blank, ap);
187         break;
188     case change:
189         vspeak(objects[msg].changes[skip], blank, ap);
190         break;
191     }
192     va_end(ap);
193 }
194
195 void rspeak(vocab_t i, ...)
196 /* Print the i-th "random" message (section 6 of database). */
197 {
198     va_list ap;
199     va_start(ap, i);
200     vspeak(arbitrary_messages[i], true, ap);
201     va_end(ap);
202 }
203
204 void echo_input(FILE* destination, const char* input_prompt, const char* input)
205 {
206     size_t len = strlen(input_prompt) + strlen(input) + 1;
207     char* prompt_and_input = (char*) xmalloc(len);
208     strcpy(prompt_and_input, input_prompt);
209     strcat(prompt_and_input, input);
210     fprintf(destination, "%s\n", prompt_and_input);
211     free(prompt_and_input);
212 }
213
214 int word_count(char* str)
215 {
216     char delims[] = " \t";
217     int count = 0;
218     int inblanks = true;
219
220     for (char *s = str; *s; s++)
221         if (inblanks) {
222             if (strchr(delims, *s) == 0) {
223                 ++count;
224                 inblanks = false;
225             }
226         } else {
227             if (strchr(delims, *s) != 0) {
228                 inblanks = true;
229             }
230         }
231
232     return (count);
233 }
234
235 char* get_input()
236 {
237     // Set up the prompt
238     char input_prompt[] = "> ";
239     if (!settings.prompt)
240         input_prompt[0] = '\0';
241
242     // Print a blank line
243     printf("\n");
244
245     char* input;
246     while (true) {
247         input = readline(input_prompt);
248
249         if (input == NULL) // Got EOF; return with it.
250             return (input);
251         if (input[0] == '#') { // Ignore comments.
252             free(input);
253             continue;
254         }
255         // We have a 'normal' line; leave the loop.
256         break;
257     }
258
259     // Strip trailing newlines from the input
260     input[strcspn(input, "\n")] = 0;
261
262     add_history(input);
263
264     if (!isatty(0))
265         echo_input(stdout, input_prompt, input);
266
267     if (settings.logfp)
268         echo_input(settings.logfp, "", input);
269
270     return (input);
271 }
272
273 bool silent_yes()
274 {
275     bool outcome = false;
276
277     for (;;) {
278         char* reply = get_input();
279         if (reply == NULL) {
280             // LCOV_EXCL_START
281             // Should be unreachable. Reply should never be NULL
282             free(reply);
283             exit(EXIT_SUCCESS);
284             // LCOV_EXCL_STOP
285         }
286         if (strlen(reply) == 0) {
287             free(reply);
288             rspeak(PLEASE_ANSWER);
289             continue;
290         }
291
292         char* firstword = (char*) xmalloc(strlen(reply) + 1);
293         sscanf(reply, "%s", firstword);
294
295         free(reply);
296
297         for (int i = 0; i < (int)strlen(firstword); ++i)
298             firstword[i] = tolower(firstword[i]);
299
300         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
301         int y = strncmp("y", firstword, sizeof("y") - 1);
302         int no = strncmp("no", firstword, sizeof("no") - 1);
303         int n = strncmp("n", firstword, sizeof("n") - 1);
304
305         free(firstword);
306
307         if (yes == 0 ||
308             y == 0) {
309             outcome = true;
310             break;
311         } else if (no == 0 ||
312                    n == 0) {
313             outcome = false;
314             break;
315         } else
316             rspeak(PLEASE_ANSWER);
317     }
318     return (outcome);
319 }
320
321
322 bool yes(const char* question, const char* yes_response, const char* no_response)
323 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
324  *  if no, print Z and return false. */
325 {
326     bool outcome = false;
327
328     for (;;) {
329         speak(question);
330
331         char* reply = get_input();
332         if (reply == NULL) {
333             // LCOV_EXCL_START
334             // Should be unreachable. Reply should never be NULL
335             free(reply);
336             exit(EXIT_SUCCESS);
337             // LCOV_EXCL_STOP
338         }
339
340         if (strlen(reply) == 0) {
341             free(reply);
342             rspeak(PLEASE_ANSWER);
343             continue;
344         }
345
346         char* firstword = (char*) xmalloc(strlen(reply) + 1);
347         sscanf(reply, "%s", firstword);
348
349         free(reply);
350
351         for (int i = 0; i < (int)strlen(firstword); ++i)
352             firstword[i] = tolower(firstword[i]);
353
354         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
355         int y = strncmp("y", firstword, sizeof("y") - 1);
356         int no = strncmp("no", firstword, sizeof("no") - 1);
357         int n = strncmp("n", firstword, sizeof("n") - 1);
358
359         free(firstword);
360
361         if (yes == 0 ||
362             y == 0) {
363             speak(yes_response);
364             outcome = true;
365             break;
366         } else if (no == 0 ||
367                    n == 0) {
368             speak(no_response);
369             outcome = false;
370             break;
371         } else
372             rspeak(PLEASE_ANSWER);
373
374     }
375
376     return (outcome);
377 }
378
379 /*  Data structure  routines */
380
381 static int get_motion_vocab_id(const char* word)
382 // Return the first motion number that has 'word' as one of its words.
383 {
384     for (int i = 0; i < NMOTIONS; ++i) {
385         for (int j = 0; j < motions[i].words.n; ++j) {
386             if (strncasecmp(word, motions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
387                     strchr(ignore, word[0]) == NULL ||
388                     !settings.oldstyle))
389                 return (i);
390         }
391     }
392     // If execution reaches here, we didn't find the word.
393     return (WORD_NOT_FOUND);
394 }
395
396 static int get_object_vocab_id(const char* word)
397 // Return the first object number that has 'word' as one of its words.
398 {
399     for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
400         for (int j = 0; j < objects[i].words.n; ++j) {
401             if (strncasecmp(word, objects[i].words.strs[j], TOKLEN) == 0)
402                 return (i);
403         }
404     }
405     // If execution reaches here, we didn't find the word.
406     return (WORD_NOT_FOUND);
407 }
408
409 static int get_action_vocab_id(const char* word)
410 // Return the first motion number that has 'word' as one of its words.
411 {
412     for (int i = 0; i < NACTIONS; ++i) {
413         for (int j = 0; j < actions[i].words.n; ++j) {
414             if (strncasecmp(word, actions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
415                     strchr(ignore, word[0]) == NULL ||
416                     !settings.oldstyle))
417                 return (i);
418         }
419     }
420     // If execution reaches here, we didn't find the word.
421     return (WORD_NOT_FOUND);
422 }
423
424 static int get_special_vocab_id(const char* word)
425 // Return the first special number that has 'word' as one of its words.
426 {
427     for (int i = 0; i < NSPECIALS; ++i) {
428         for (int j = 0; j < specials[i].words.n; ++j) {
429             if (strncasecmp(word, specials[i].words.strs[j], TOKLEN) == 0)
430                 return (i);
431         }
432     }
433     // If execution reaches here, we didn't find the word.
434     return (WORD_NOT_FOUND);
435 }
436
437 void get_vocab_metadata(const char* word, long* id, enum wordtype* type)
438 {
439     /* Check for an empty string */
440     if (strncmp(word, "", sizeof("")) == 0) {
441         *id = WORD_EMPTY;
442         *type = NO_WORD_TYPE;
443         return;
444     }
445
446     long ref_num;
447
448     ref_num = get_motion_vocab_id(word);
449     if (ref_num != WORD_NOT_FOUND) {
450         *id = ref_num;
451         *type = MOTION;
452         return;
453     }
454
455     ref_num = get_object_vocab_id(word);
456     if (ref_num != WORD_NOT_FOUND) {
457         *id = ref_num;
458         *type = OBJECT;
459         return;
460     }
461
462     ref_num = get_action_vocab_id(word);
463     if (ref_num != WORD_NOT_FOUND) {
464         *id = ref_num;
465         *type = ACTION;
466         return;
467     }
468
469     ref_num = get_special_vocab_id(word);
470     if (ref_num != WORD_NOT_FOUND) {
471         *id = ref_num;
472         *type = SPECIAL;
473         return;
474     }
475
476     // Check for the reservoir magic word.
477     if (strcasecmp(word, game.zzword) == 0) {
478         *id = PART;
479         *type = ACTION;
480         return;
481     }
482
483     *id = WORD_NOT_FOUND;
484     *type = NO_WORD_TYPE;
485     return;
486 }
487
488 void juggle(obj_t object)
489 /*  Juggle an object by picking it up and putting it down again, the purpose
490  *  being to get the object to the front of the chain of things at its loc. */
491 {
492     loc_t i, j;
493
494     i = game.place[object];
495     j = game.fixed[object];
496     move(object, i);
497     move(object + NOBJECTS, j);
498 }
499
500 void move(obj_t object, loc_t where)
501 /*  Place any object anywhere by picking it up and dropping it.  May
502  *  already be toting, in which case the carry is a no-op.  Mustn't
503  *  pick up objects which are not at any loc, since carry wants to
504  *  remove objects from game.atloc chains. */
505 {
506     long from;
507
508     if (object > NOBJECTS)
509         from = game.fixed[object - NOBJECTS];
510     else
511         from = game.place[object];
512     /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong... */
513     if (from != LOC_NOWHERE && from != CARRIED)
514         carry(object, from);
515     drop(object, where);
516 }
517
518 long put(obj_t object, loc_t where, long pval)
519 /*  put() is the same as move(), except it returns a value used to set up the
520  *  negated game.prop values for the repository objects. */
521 {
522     move(object, where);
523     return STASHED(pval);
524 }
525
526 void carry(obj_t object, loc_t where)
527 /*  Start toting an object, removing it from the list of things at its former
528  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
529  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
530 {
531     long temp;
532
533     if (object <= NOBJECTS) {
534         if (game.place[object] == CARRIED)
535             return;
536         game.place[object] = CARRIED;
537         ++game.holdng;
538     }
539     if (game.atloc[where] == object) {
540         game.atloc[where] = game.link[object];
541         return;
542     }
543     temp = game.atloc[where];
544     while (game.link[temp] != object) {
545         temp = game.link[temp];
546     }
547     game.link[temp] = game.link[object];
548 }
549
550 void drop(obj_t object, loc_t where)
551 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
552  *  game.holdng if the object was being toted. */
553 {
554     if (object > NOBJECTS)
555         game.fixed[object - NOBJECTS] = where;
556     else {
557         if (game.place[object] == CARRIED)
558             --game.holdng;
559         game.place[object] = where;
560     }
561     if (where == LOC_NOWHERE ||
562         where == CARRIED)
563         return;
564     game.link[object] = game.atloc[where];
565     game.atloc[where] = object;
566 }
567
568 long atdwrf(loc_t where)
569 /*  Return the index of first dwarf at the given location, zero if no dwarf is
570  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
571  *  the pirate (6th dwarf). */
572 {
573     long at;
574
575     at = 0;
576     if (game.dflag < 2)
577         return (at);
578     at = -1;
579     for (long i = 1; i <= NDWARVES - 1; i++) {
580         if (game.dloc[i] == where)
581             return i;
582         if (game.dloc[i] != 0)
583             at = 0;
584     }
585     return (at);
586 }
587
588 /*  Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
589  *  randrange) */
590
591 long setbit(long bit)
592 /*  Returns 2**bit for use in constructing bit-masks. */
593 {
594     return (1L << bit);
595 }
596
597 bool tstbit(long mask, int bit)
598 /*  Returns true if the specified bit is set in the mask. */
599 {
600     return (mask & (1 << bit)) != 0;
601 }
602
603 void set_seed(long seedval)
604 /* Set the LCG seed */
605 {
606     game.lcg_x = (unsigned long) seedval % game.lcg_m;
607
608     // once seed is set, we need to generate the Z`ZZZ word
609     make_zzword(game.zzword);
610 }
611
612 unsigned long get_next_lcg_value(void)
613 /* Return the LCG's current value, and then iterate it. */
614 {
615     unsigned long old_x = game.lcg_x;
616     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
617     return old_x;
618 }
619
620 long randrange(long range)
621 /* Return a random integer from [0, range). */
622 {
623     return range * get_next_lcg_value() / game.lcg_m;
624 }
625
626 void make_zzword(char zzword[TOKLEN + 1])
627 {
628     for (int i = 0; i < 5; ++i) {
629         zzword[i] = 'A' + randrange(26);
630     }
631     zzword[1] = '\''; // force second char to apostrophe
632     zzword[5] = '\0';
633 }
634
635 // LCOV_EXCL_START
636 void bug(enum bugtype num, const char *error_string)
637 {
638     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
639     exit(EXIT_FAILURE);
640 }
641 // LCOV_EXCL_STOP
642
643 /* end */
644
645 void state_change(obj_t obj, long state)
646 /* Object must have a change-message list for this to be useful; only some do */
647 {
648     game.prop[obj] = state;
649     pspeak(obj, change, state, true);
650 }
651
652 /* end */