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