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