Fix bug that made YES() case-sensitive.
[open-adventure.git] / misc.c
1 #include <unistd.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <sys/time.h>
6 #include <ctype.h>
7
8 #include "advent.h"
9 #include "database.h"
10 #include "linenoise/linenoise.h"
11 #include "newdb.h"
12
13 void* xmalloc(size_t size)
14 {
15   void* ptr = malloc(size);
16   if (ptr == NULL)
17     {
18       fprintf(stderr, "Out of memory!\n");
19       exit(EXIT_FAILURE);
20     }
21   return(ptr);
22 }
23
24 char* xstrdup(const char* s)
25 {
26     char* ptr = strdup(s);
27     if (ptr == NULL) {
28         fprintf(stderr, "Out of memory!\n");
29         exit(EXIT_FAILURE);
30     }
31     return (ptr);
32 }
33
34 void packed_to_token(long packed, char token[6])
35 {
36     // Unpack and map back to ASCII.
37     for (int i = 0; i < 5; ++i) {
38         char advent = (packed >> i * 6) & 63;
39         token[4 - i] = advent_to_ascii[(int) advent];
40     }
41
42     // Ensure the last character is \0.
43     token[5] = '\0';
44
45     // Replace trailing whitespace with \0.
46     for (int i = 4; i >= 0; --i) {
47         if (token[i] == ' ' || token[i] == '\t')
48             token[i] = '\0';
49         else
50             break;
51     }
52 }
53
54 /*  I/O routines (SPEAK, PSPEAK, RSPEAK, SETPRM, GETIN, YES) */
55
56 void speak(const char* msg)
57 {
58     // Do nothing if we got a null pointer.
59     if (msg == NULL)
60         return;
61
62     // Do nothing if we got an empty string.
63     if (strlen(msg) == 0)
64         return;
65
66     // Print a newline if the global game.blklin says to.
67     if (game.blklin == true)
68         printf("\n");
69
70     // Create a copy of our string, so we can edit it.
71     char* copy = xstrdup(msg);
72
73     // Staging area for stringified parameters.
74     char parameters[5][100]; // FIXME: to be replaced with dynamic allocation
75
76     // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
77     int pi = 0; // parameter index
78     for (int i = 0; i < (int)strlen(msg); ++i) {
79         if (msg[i] == '%') {
80             ++pi;
81
82             // Integer specifier. In order to accommodate the fact that PARMS can have both legitimate integers *and* packed tokens, stringify everything. Future work may eliminate the need for this.
83             if (msg[i + 1] == 'd') {
84                 copy[i + 1] = 's';
85                 sprintf(parameters[pi], "%ld", PARMS[pi]);
86             }
87
88             // Unmodified string specifier.
89             if (msg[i + 1] == 's') {
90                 packed_to_token(PARMS[pi], parameters[pi]);
91             }
92
93             // Singular/plural specifier.
94             if (msg[i + 1] == 'S') {
95                 copy[i + 1] = 's';
96                 if (PARMS[pi - 1] > 1) { // look at the *previous* parameter (which by necessity must be numeric)
97                     sprintf(parameters[pi], "%s", "s");
98                 } else {
99                     sprintf(parameters[pi], "%s", "");
100                 }
101             }
102
103             // All-lowercase specifier.
104             if (msg[i + 1] == 'L') {
105                 copy[i + 1] = 's';
106                 packed_to_token(PARMS[pi], parameters[pi]);
107                 for (int j = 0; j < (int)strlen(parameters[pi]); ++j) {
108                     parameters[pi][j] = tolower(parameters[pi][j]);
109                 }
110             }
111
112             // First char uppercase, rest lowercase.
113             if (msg[i + 1] == 'C') {
114                 copy[i + 1] = 's';
115                 packed_to_token(PARMS[pi], parameters[pi]);
116                 for (int j = 0; j < (int)strlen(parameters[pi]); ++j) {
117                     parameters[pi][j] = tolower(parameters[pi][j]);
118                 }
119                 parameters[pi][0] = toupper(parameters[pi][0]);
120             }
121         }
122     }
123
124     // Render the final string.
125     char rendered[2000]; // FIXME: to be replaced with dynamic allocation
126     sprintf(rendered, copy, parameters[1], parameters[2], parameters[3], parameters[4]); // FIXME: to be replaced with vsprintf()
127
128     // Print the message.
129     printf("%s\n", rendered);
130
131     free(copy);
132 }
133
134 void PSPEAK(vocab_t msg, int skip)
135 /*  Find the skip+1st message from msg and print it.  msg should be
136  *  the index of the inventory message for object.  (INVEN+N+1 message
137  *  is game.prop=N message). */
138 {
139     if (skip >= 0)
140         speak(object_descriptions[msg].longs[skip]);
141     else
142         speak(object_descriptions[msg].inventory);
143 }
144
145 void RSPEAK(vocab_t i)
146 /* Print the i-th "random" message (section 6 of database). */
147 {
148     speak(arbitrary_messages[i]);
149 }
150
151 void SETPRM(long first, long p1, long p2)
152 /*  Stores parameters into the PRMCOM parms array for use by speak.  P1 and P2
153  *  are stored into PARMS(first) and PARMS(first+1). */
154 {
155     if (first >= MAXPARMS)
156         BUG(29);
157     else {
158         PARMS[first] = p1;
159         PARMS[first + 1] = p2;
160     }
161 }
162
163 bool GETIN(FILE *input,
164            long *pword1, long *pword1x,
165            long *pword2, long *pword2x)
166 /*  Get a command from the adventurer.  Snarf out the first word, pad it with
167  *  blanks, and return it in WORD1.  Chars 6 thru 10 are returned in WORD1X, in
168  *  case we need to print out the whole word in an error message.  Any number of
169  *  blanks may follow the word.  If a second word appears, it is returned in
170  *  WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
171 {
172     long junk;
173
174     for (;;) {
175         if (game.blklin)
176             fputc('\n', stdout);;
177         if (!MAPLIN(input))
178             return false;
179         *pword1 = GETTXT(true, true, true);
180         if (game.blklin && *pword1 < 0)
181             continue;
182         *pword1x = GETTXT(false, true, true);
183         do {
184             junk = GETTXT(false, true, true);
185         } while
186         (junk > 0);
187         *pword2 = GETTXT(true, true, true);
188         *pword2x = GETTXT(false, true, true);
189         do {
190             junk = GETTXT(false, true, true);
191         } while
192         (junk > 0);
193         if (GETTXT(true, true, true) <= 0)
194             return true;
195         RSPEAK(TWO_WORDS);
196     }
197 }
198
199 void echo_input(FILE* destination, char* input_prompt, char* input)
200 {
201   size_t len = strlen(input_prompt) + strlen(input) + 1;
202   char* prompt_and_input = (char*) xmalloc(len);
203   strcpy(prompt_and_input, input_prompt);
204   strcat(prompt_and_input, input);
205   fprintf(destination, "%s\n", prompt_and_input);
206   free(prompt_and_input);
207 }
208
209 char* get_input()
210
211   // Set up the prompt
212   char input_prompt[] = "> ";
213   if (!prompt)
214     input_prompt[0] = '\0';
215   
216   // Print a blank line if game.blklin tells us to.
217   if (game.blklin == true)
218     printf("\n");
219
220   char* input;
221   while (true)
222     {
223       if (editline)
224         input = linenoise(input_prompt);
225       else
226         {
227           input = NULL;
228           size_t n = 0;
229           if (isatty(0))
230             printf("%s", input_prompt);
231           getline(&input, &n, stdin);
232         }
233       
234       if (input == NULL) // Got EOF; quit.
235         exit(EXIT_SUCCESS);
236       else if (input[0] == '#') // Ignore comments.
237         continue;
238       else // We have a 'normal' line; leave the loop.
239         break;
240     }
241
242   // Strip trailing newlines from the input
243   input[strcspn(input, "\n")] = 0;
244
245   linenoiseHistoryAdd(input);
246
247   if (!isatty(0))
248     echo_input(stdout, input_prompt, input);
249
250   if (logfp)
251     echo_input(logfp, input_prompt, input);
252     
253   return(input);
254 }
255
256 bool YES(vocab_t question, vocab_t yes_response, vocab_t no_response)
257 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
258  *  if no, print Z and return false. */
259 {
260     char* reply;
261     bool outcome;
262    
263     for (;;) {
264         RSPEAK(question);
265
266         reply = get_input();
267
268         char* firstword = (char*) xmalloc(strlen(reply));
269         sscanf(reply, "%s", firstword);
270
271         for (int i = 0; i < strlen(firstword); ++i)
272             firstword[i] = tolower(firstword[i]);
273         
274         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
275         int y = strncmp("y", firstword, sizeof("y") - 1);
276         int no = strncmp("no", firstword, sizeof("no") - 1);
277         int n = strncmp("n", firstword, sizeof("n") - 1);
278
279         free(firstword);
280         
281         if (yes == 0 || y == 0) {
282             RSPEAK(yes_response);
283             outcome = true;
284             break;
285         }
286         else if (no == 0 || n == 0) {
287             RSPEAK(no_response);
288             outcome = false;
289             break;
290         }
291         else
292             RSPEAK(PLEASE_ANSWER);
293     }
294     linenoiseFree(reply);
295     return(outcome);
296 }
297
298 /*  Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT) */
299
300 long GETTXT(bool skip, bool onewrd, bool upper)
301 /*  Take characters from an input line and pack them into 30-bit words.
302  *  Skip says to skip leading blanks.  ONEWRD says stop if we come to a
303  *  blank.  UPPER says to map all letters to uppercase.  If we reach the
304  *  end of the line, the word is filled up with blanks (which encode as 0's).
305  *  If we're already at end of line when TEXT is called, we return -1. */
306 {
307     long text;
308     static long splitting = -1;
309
310     if (LNPOSN != splitting)
311         splitting = -1;
312     text = -1;
313     while (true) {
314         if (LNPOSN > LNLENG)
315             return (text);
316         if ((!skip) || INLINE[LNPOSN] != 0)
317             break;
318         ++LNPOSN;
319     }
320
321     text = 0;
322     for (int I = 1; I <= TOKLEN; I++) {
323         text = text * 64;
324         if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
325             continue;
326         char current = INLINE[LNPOSN];
327         if (current < ascii_to_advent['%']) {
328             splitting = -1;
329             if (upper && current >= ascii_to_advent['a'])
330                 current = current - 26;
331             text = text + current;
332             ++LNPOSN;
333             continue;
334         }
335         if (splitting != LNPOSN) {
336             text = text + ascii_to_advent['%'];
337             splitting = LNPOSN;
338             continue;
339         }
340
341         text = text + current - ascii_to_advent['%'];
342         splitting = -1;
343         ++LNPOSN;
344     }
345
346     return text;
347 }
348
349 token_t MAKEWD(long letters)
350 /*  Combine TOKLEN (currently 5) uppercase letters (represented by
351  *  pairs of decimal digits in lettrs) to form a 30-bit value matching
352  *  the one that GETTXT would return given those characters plus
353  *  trailing blanks.  Caution: lettrs will overflow 31 bits if
354  *  5-letter word starts with V-Z.  As a kludgey workaround, you can
355  *  increment a letter by 5 by adding 50 to the next pair of
356  *  digits. */
357 {
358     long i = 1, word = 0;
359
360     for (long k = letters; k != 0; k = k / 100) {
361         word = word + i * (MOD(k, 50) + 10);
362         i = i * 64;
363         if (MOD(k, 100) > 50)word = word + i * 5;
364     }
365     i = 64L * 64L * 64L * 64L * 64L / i;
366     word = word * i;
367     return word;
368 }
369
370 /*  Data structure  routines */
371
372 long VOCAB(long id, long init)
373 /*  Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
374  *  -1 if not found.  If INIT is positive, this is an initialisation call setting
375  *  up a keyword variable, and not finding it constitutes a bug.  It also means
376  *  that only KTAB values which taken over 1000 equal INIT may be considered.
377  *  (Thus "STEPS", which is a motion verb as well as an object, may be located
378  *  as an object.)  And it also means the KTAB value is taken modulo 1000. */
379 {
380     long lexeme;
381
382     for (long i = 1; i <= TABSIZ; i++) {
383         if (KTAB[i] == -1) {
384             lexeme = -1;
385             if (init < 0)
386                 return (lexeme);
387             BUG(5);
388         }
389         if (init >= 0 && KTAB[i] / 1000 != init)
390             continue;
391         if (ATAB[i] == id) {
392             lexeme = KTAB[i];
393             if (init >= 0)
394                 lexeme = MOD(lexeme, 1000);
395             return (lexeme);
396         }
397     }
398     BUG(21);
399 }
400
401 void JUGGLE(long object)
402 /*  Juggle an object by picking it up and putting it down again, the purpose
403  *  being to get the object to the front of the chain of things at its loc. */
404 {
405     long i, j;
406
407     i = game.place[object];
408     j = game.fixed[object];
409     MOVE(object, i);
410     MOVE(object + NOBJECTS, j);
411 }
412
413 void MOVE(long object, long where)
414 /*  Place any object anywhere by picking it up and dropping it.  May
415  *  already be toting, in which case the carry is a no-op.  Mustn't
416  *  pick up objects which are not at any loc, since carry wants to
417  *  remove objects from game.atloc chains. */
418 {
419     long from;
420
421     if (object > NOBJECTS)
422         from = game.fixed[object - NOBJECTS];
423     else
424         from = game.place[object];
425     if (from != NOWHERE && from != CARRIED && !SPECIAL(from))
426         CARRY(object, from);
427     DROP(object, where);
428 }
429
430 long PUT(long object, long where, long pval)
431 /*  PUT is the same as MOVE, except it returns a value used to set up the
432  *  negated game.prop values for the repository objects. */
433 {
434     MOVE(object, where);
435     return (-1) - pval;;
436 }
437
438 void CARRY(long object, long where)
439 /*  Start toting an object, removing it from the list of things at its former
440  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
441  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
442 {
443     long temp;
444
445     if (object <= NOBJECTS) {
446         if (game.place[object] == CARRIED)
447             return;
448         game.place[object] = CARRIED;
449         ++game.holdng;
450     }
451     if (game.atloc[where] == object) {
452         game.atloc[where] = game.link[object];
453         return;
454     }
455     temp = game.atloc[where];
456     while (game.link[temp] != object) {
457         temp = game.link[temp];
458     }
459     game.link[temp] = game.link[object];
460 }
461
462 void DROP(long object, long where)
463 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
464  *  game.holdng if the object was being toted. */
465 {
466     if (object > NOBJECTS)
467         game.fixed[object - NOBJECTS] = where;
468     else {
469         if (game.place[object] == CARRIED)
470             --game.holdng;
471         game.place[object] = where;
472     }
473     if (where <= 0)
474         return;
475     game.link[object] = game.atloc[where];
476     game.atloc[where] = object;
477 }
478
479 long ATDWRF(long where)
480 /*  Return the index of first dwarf at the given location, zero if no dwarf is
481  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
482  *  the pirate (6th dwarf). */
483 {
484     long at;
485
486     at = 0;
487     if (game.dflag < 2)
488         return (at);
489     at = -1;
490     for (long i = 1; i <= NDWARVES - 1; i++) {
491         if (game.dloc[i] == where)
492             return i;
493         if (game.dloc[i] != 0)
494             at = 0;
495     }
496     return (at);
497 }
498
499 /*  Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
500  *  randrange, RNDVOC, BUG) */
501
502 long SETBIT(long bit)
503 /*  Returns 2**bit for use in constructing bit-masks. */
504 {
505     return (1 << bit);
506 }
507
508 bool TSTBIT(long mask, int bit)
509 /*  Returns true if the specified bit is set in the mask. */
510 {
511     return (mask & (1 << bit)) != 0;
512 }
513
514 void set_seed(long seedval)
515 /* Set the LCG seed */
516 {
517     game.lcg_x = (unsigned long) seedval % game.lcg_m;
518 }
519
520 unsigned long get_next_lcg_value(void)
521 /* Return the LCG's current value, and then iterate it. */
522 {
523     unsigned long old_x = game.lcg_x;
524     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
525     return old_x;
526 }
527
528 long randrange(long range)
529 /* Return a random integer from [0, range). */
530 {
531     return range * get_next_lcg_value() / game.lcg_m;
532 }
533
534 long RNDVOC(long second, long force)
535 /*  Searches the vocabulary ATAB for a word whose second character is
536  *  char, and changes that word such that each of the other four
537  *  characters is a random letter.  If force is non-zero, it is used
538  *  as the new word.  Returns the new word. */
539 {
540     long rnd = force;
541
542     if (rnd == 0) {
543         for (int i = 1; i <= 5; i++) {
544             long j = 11 + randrange(26);
545             if (i == 2)
546                 j = second;
547             rnd = rnd * 64 + j;
548         }
549     }
550
551     long div = 64L * 64L * 64L;
552     for (int i = 1; i <= TABSIZ; i++) {
553         if (MOD(ATAB[i] / div, 64L) == second) {
554             ATAB[i] = rnd;
555             break;
556         }
557     }
558
559     return rnd;
560 }
561
562 void BUG(long num)
563 /*  The following conditions are currently considered fatal bugs.  Numbers < 20
564  *  are detected while reading the database; the others occur at "run time".
565  *      0       Message line > 70 characters
566  *      1       Null line in message
567  *      2       Too many words of messages
568  *      3       Too many travel options
569  *      4       Too many vocabulary words
570  *      5       Required vocabulary word not found
571  *      6       Too many RTEXT messages
572  *      7       Too many hints
573  *      8       Location has cond bit being set twice
574  *      9       Invalid section number in database
575  *      10      Too many locations
576  *      11      Too many class or turn messages
577  *      20      Special travel (500>L>300) exceeds goto list
578  *      21      Ran off end of vocabulary table
579  *      22      Vocabulary type (N/1000) not between 0 and 3
580  *      23      Intransitive action verb exceeds goto list
581  *      24      Transitive action verb exceeds goto list
582  *      25      Conditional travel entry with no alternative
583  *      26      Location has no travel entries
584  *      27      Hint number exceeds goto list
585  *      28      Invalid month returned by date function
586  *      29      Too many parameters given to SETPRM */
587 {
588
589     printf("Fatal error %ld.  See source code for interpretation.\n", num);
590     exit(0);
591 }
592
593 /*  Machine dependent routines (MAPLIN, SAVEIO) */
594
595 bool MAPLIN(FILE *fp)
596 {
597     bool eof;
598
599     /* Read a line of input, from the specified input source.
600      * This logic is complicated partly because it has to serve
601      * several cases with different requirements and partly because
602      * of a quirk in linenoise().
603      *
604      * The quirk shows up when you paste a test log from the clipboard
605      * to the program's command prompt.  While fgets (as expected)
606      * consumes it a line at a time, linenoise() returns the first
607      * line and discards the rest.  Thus, there needs to be an
608      * editline (-s) option to fall back to fgets while still
609      * prompting.  Note that linenoise does behave properly when
610      * fed redirected stdin.
611      *
612      * The logging is a bit of a mess because there are two distinct cases
613      * in which you want to echo commands.  One is when shipping them to
614      * a log under the -l option, in which case you want to suppress
615      * prompt generation (so test logs are unadorned command sequences).
616      * On the other hand, if you redirected stdin and are feeding the program
617      * a logfile, you *do* want prompt generation - it makes checkfiles
618      * easier to read when the commands are marked by a preceding prompt.
619      */
620     do {
621         if (!editline) {
622             if (prompt)
623                 fputs("> ", stdout);
624             IGNORE(fgets(rawbuf, sizeof(rawbuf) - 1, fp));
625             eof = (feof(fp));
626         } else {
627             char *cp = linenoise("> ");
628             eof = (cp == NULL);
629             if (!eof) {
630                 strncpy(rawbuf, cp, sizeof(rawbuf) - 1);
631                 linenoiseHistoryAdd(rawbuf);
632                 strncat(rawbuf, "\n", sizeof(rawbuf) - strlen(rawbuf) - 1);
633                 linenoiseFree(cp);
634             }
635         }
636     } while
637     (!eof && rawbuf[0] == '#');
638     if (eof) {
639         if (logfp && fp == stdin)
640             fclose(logfp);
641         return false;
642     } else {
643         FILE *efp = NULL;
644         if (logfp && fp == stdin)
645             efp = logfp;
646         else if (!isatty(0))
647             efp = stdout;
648         if (efp != NULL) {
649             if (prompt && efp == stdout)
650                 fputs("> ", efp);
651             IGNORE(fputs(rawbuf, efp));
652         }
653         strcpy(INLINE + 1, rawbuf);
654         /*  translate the chars to integers in the range 0-126 and store
655          *  them in the common array "INLINE".  Integer values are as follows:
656          *     0   = space [ASCII CODE 40 octal, 32 decimal]
657          *    1-2  = !" [ASCII 41-42 octal, 33-34 decimal]
658          *    3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
659          *   11-36 = upper-case letters
660          *   37-62 = lower-case letters
661          *    63   = percent (%) [ASCII 45 octal, 37 decimal]
662          *   64-73 = digits, 0 through 9
663          *  Remaining characters can be translated any way that is convenient;
664          *  The above mappings are required so that certain special
665          *  characters are known to fit in 6 bits and/or can be easily spotted.
666          *  Array elements beyond the end of the line should be filled with 0,
667          *  and LNLENG should be set to the index of the last character.
668          *
669          *  If the data file uses a character other than space (e.g., tab) to
670          *  separate numbers, that character should also translate to 0.
671          *
672          *  This procedure may use the map1,map2 arrays to maintain static data for
673          *  the mapping.  MAP2(1) is set to 0 when the program starts
674          *  and is not changed thereafter unless the routines on this page choose
675          *  to do so. */
676         LNLENG = 0;
677         for (long i = 1; i <= (long)sizeof(INLINE) && INLINE[i] != 0; i++) {
678             long val = INLINE[i];
679             INLINE[i] = ascii_to_advent[val];
680             if (INLINE[i] != 0)
681                 LNLENG = i;
682         }
683         LNPOSN = 1;
684         return true;
685     }
686 }
687
688 void DATIME(long* d, long* t)
689 {
690     struct timeval tv;
691     gettimeofday(&tv, NULL);
692     *d = (long) tv.tv_sec;
693     *t = (long) tv.tv_usec;
694 }
695
696 /* end */