Remove extraneous listing of files
[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     {
407         if (!isdigit(*str))
408             return false;
409         else
410             ++str;
411     }
412
413     return true;
414 }
415
416 static void get_vocab_metadata(command_word_t* word)
417 {
418     /* Check for an empty string */
419     if (strncmp(word->raw, "", sizeof("")) == 0) {
420         word->id = WORD_EMPTY;
421         word->type = NO_WORD_TYPE;
422         return;
423     }
424
425     vocab_t ref_num;
426
427     ref_num = get_motion_vocab_id(word->raw);
428     if (ref_num != WORD_NOT_FOUND) {
429         word->id = ref_num;
430         word->type = MOTION;
431         return;
432     }
433
434     ref_num = get_object_vocab_id(word->raw);
435     if (ref_num != WORD_NOT_FOUND) {
436         word->id = ref_num;
437         word->type = OBJECT;
438         return;
439     }
440
441     ref_num = get_action_vocab_id(word->raw);
442     if (ref_num != WORD_NOT_FOUND) {
443         word->id = ref_num;
444         word->type = ACTION;
445         return;
446     }
447
448     // Check for the reservoir magic word.
449     if (strcasecmp(word->raw, game.zzword) == 0) {
450         word->id = PART;
451         word->type = ACTION;
452         return;
453     }
454
455     // Check words that are actually numbers.
456     if (is_valid_int(word->raw)) {
457         word->id = WORD_EMPTY;
458         word->type = NUMERIC;
459         return;
460     }
461
462     word->id = WORD_NOT_FOUND;
463     word->type = NO_WORD_TYPE;
464     return;
465 }
466
467 static void tokenize(char* raw, command_t *cmd)
468 {
469     memset(cmd, '\0', sizeof(command_t));
470
471     /* Bound prefix on the %s would be needed to prevent buffer
472      * overflow.  but we shortstop this more simply by making each
473      * raw-input buffer as long as the entire input buffer. */
474     sscanf(raw, "%s%s", cmd->word[0].raw, cmd->word[1].raw);
475
476     /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
477      * effect on raw tokens of packing them into sixbit characters, 5
478      * to a 32-bit word.  This is something the FORTRAN version did
479      * becuse archaic FORTRAN had no string types.  Don Wood's
480      * mechanical translation of 2.5 to C retained the packing and
481      * thus this misfeature.
482      *
483      * It's philosophically questionable whether this is the right
484      * thing to do even in oldstyle mode.  On one hand, the text
485      * mangling was not authorial intent, but a result of limitations
486      * in their tools. On the other, not simulating this misbehavior
487      * goes against the goal of making oldstyle as accurate as
488      * possible an emulation of the original UI.
489      */
490     if (settings.oldstyle) {
491         cmd->word[0].raw[TOKLEN + TOKLEN] = cmd->word[1].raw[TOKLEN + TOKLEN] = '\0';
492         for (size_t i = 0; i < strlen(cmd->word[0].raw); i++)
493             cmd->word[0].raw[i] = toupper(cmd->word[0].raw[i]);
494         for (size_t i = 0; i < strlen(cmd->word[1].raw); i++)
495             cmd->word[1].raw[i] = toupper(cmd->word[1].raw[i]);
496     }
497
498     /* populate command with parsed vocabulary metadata */
499     get_vocab_metadata(&(cmd->word[0]));
500     get_vocab_metadata(&(cmd->word[1]));
501 }
502
503 bool get_command_input(command_t *command)
504 /* Get user input on stdin, parse and map to command */
505 {
506     char inputbuf[LINESIZE];
507     char* input;
508
509     for (;;) {
510         input = get_input();
511         if (input == NULL)
512             return false;
513         if (word_count(input) > 2) {
514             rspeak(TWO_WORDS);
515             free(input);
516             continue;
517         }
518         if (strcmp(input, "") != 0)
519             break;
520         free(input);
521     }
522
523     strncpy(inputbuf, input, LINESIZE - 1);
524     free(input);
525
526     tokenize(inputbuf, command);
527
528     return true;
529 }
530
531 void juggle(obj_t object)
532 /*  Juggle an object by picking it up and putting it down again, the purpose
533  *  being to get the object to the front of the chain of things at its loc. */
534 {
535     loc_t i, j;
536
537     i = game.place[object];
538     j = game.fixed[object];
539     move(object, i);
540     move(object + NOBJECTS, j);
541 }
542
543 void move(obj_t object, loc_t where)
544 /*  Place any object anywhere by picking it up and dropping it.  May
545  *  already be toting, in which case the carry is a no-op.  Mustn't
546  *  pick up objects which are not at any loc, since carry wants to
547  *  remove objects from game.atloc chains. */
548 {
549     loc_t from;
550
551     if (object > NOBJECTS)
552         from = game.fixed[object - NOBJECTS];
553     else
554         from = game.place[object];
555     /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong... */
556     if (from != LOC_NOWHERE && from != CARRIED)
557         carry(object, from);
558     drop(object, where);
559 }
560
561 loc_t put(obj_t object, loc_t where, long pval)
562 /*  put() is the same as move(), except it returns a value used to set up the
563  *  negated game.prop values for the repository objects. */
564 {
565     move(object, where);
566     return STASHED(pval);
567 }
568
569 void carry(obj_t object, loc_t where)
570 /*  Start toting an object, removing it from the list of things at its former
571  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
572  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
573 {
574     long temp;
575
576     if (object <= NOBJECTS) {
577         if (game.place[object] == CARRIED)
578             return;
579         game.place[object] = CARRIED;
580         ++game.holdng;
581     }
582     if (game.atloc[where] == object) {
583         game.atloc[where] = game.link[object];
584         return;
585     }
586     temp = game.atloc[where];
587     while (game.link[temp] != object) {
588         temp = game.link[temp];
589     }
590     game.link[temp] = game.link[object];
591 }
592
593 void drop(obj_t object, loc_t where)
594 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
595  *  game.holdng if the object was being toted. */
596 {
597     if (object > NOBJECTS)
598         game.fixed[object - NOBJECTS] = where;
599     else {
600         if (game.place[object] == CARRIED)
601             --game.holdng;
602         game.place[object] = where;
603     }
604     if (where == LOC_NOWHERE ||
605         where == CARRIED)
606         return;
607     game.link[object] = game.atloc[where];
608     game.atloc[where] = object;
609 }
610
611 int atdwrf(loc_t where)
612 /*  Return the index of first dwarf at the given location, zero if no dwarf is
613  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
614  *  the pirate (6th dwarf). */
615 {
616     int at;
617
618     at = 0;
619     if (game.dflag < 2)
620         return at;
621     at = -1;
622     for (long i = 1; i <= NDWARVES - 1; i++) {
623         if (game.dloc[i] == where)
624             return i;
625         if (game.dloc[i] != 0)
626             at = 0;
627     }
628     return at;
629 }
630
631 /*  Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
632  *  randrange) */
633
634 long setbit(int bit)
635 /*  Returns 2**bit for use in constructing bit-masks. */
636 {
637     return (1L << bit);
638 }
639
640 bool tstbit(long mask, int bit)
641 /*  Returns true if the specified bit is set in the mask. */
642 {
643     return (mask & (1 << bit)) != 0;
644 }
645
646 void set_seed(long seedval)
647 /* Set the LCG seed */
648 {
649     game.lcg_x = (unsigned long) seedval % game.lcg_m;
650
651     // once seed is set, we need to generate the Z`ZZZ word
652     for (int i = 0; i < 5; ++i) {
653         game.zzword[i] = 'A' + randrange(26);
654     }
655     game.zzword[1] = '\''; // force second char to apostrophe
656     game.zzword[5] = '\0';
657 }
658
659 static unsigned long get_next_lcg_value(void)
660 /* Return the LCG's current value, and then iterate it. */
661 {
662     unsigned long old_x = game.lcg_x;
663     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
664     return old_x;
665 }
666
667 long randrange(long range)
668 /* Return a random integer from [0, range). */
669 {
670     return range * get_next_lcg_value() / game.lcg_m;
671 }
672
673 // LCOV_EXCL_START
674 void bug(enum bugtype num, const char *error_string)
675 {
676     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
677     exit(EXIT_FAILURE);
678 }
679 // LCOV_EXCL_STOP
680
681 /* end */
682
683 void state_change(obj_t obj, int state)
684 /* Object must have a change-message list for this to be useful; only some do */
685 {
686     game.prop[obj] = state;
687     pspeak(obj, change, state, true);
688 }
689
690 /* end */