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