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