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