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