10 #include "linenoise/linenoise.h"
13 void* xmalloc(size_t size)
15 void* ptr = malloc(size);
18 fprintf(stderr, "Out of memory!\n");
24 void packed_to_token(long packed, char token[6])
26 for (int i = 0; i < 5; ++i)
28 char advent = (packed >> i * 6) & 63;
29 token[i] = advent_to_ascii[advent];
34 /* I/O routines (SPEAK, PSPEAK, RSPEAK, SETPRM, GETIN, YES) */
36 void newspeak(char* msg)
38 // Do nothing if we got a null pointer.
42 // Do nothing if we got an empty string.
46 // Print a newline if the global game.blklin says to.
47 if (game.blklin == true)
50 // Create a copy of our string, so we can edit it.
51 char* copy = (char*) xmalloc(strlen(msg) + 1);
52 strncpy(copy, msg, strlen(msg) + 1);
54 // Staging area for parameters.
55 char parameters[2000][5];
57 // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
59 for (int i = 0; i < strlen(msg); ++i)
65 // Integer specifier. In order to accommodate the fact that PARMS can have both legitimate integers *and* packed tokens, stringify these. Future work may eliminate the need for this.
66 if (msg[i + 1] == 'd')
69 sprintf(parameters[param_index], "%d", PARMS[param_index]);
72 // Plain string specifier.
73 if (msg[i + 1] == 's')
75 packed_to_token(PARMS[param_index], parameters[param_index]);
78 // Plural replacement specifier.
79 if (msg[i + 1] == 'S')
82 if (PARMS[param_index - 1] > 1)
84 sprintf(parameters[param_index], "%s", "s");
88 sprintf(parameters[param_index], "%s", "");
94 // Render the final string.
96 sprintf(&rendered, copy, parameters[1], parameters[2], parameters[3], parameters[4]);
99 printf("%s\n", rendered);
102 void SPEAK(vocab_t msg)
103 /* Print the message which starts at LINES[N]. Precede it with a blank line
104 * unless game.blklin is false. */
106 long blank, casemake, i, nxt, neg, nparms, param, prmtyp, state;
113 nxt=labs(LINES[msg])-1;
118 for (i = msg; i <= nxt; i++) {
119 PUTTXT(LINES[i],&state,2);
124 while (LNPOSN <= LNLENG) {
125 if (INLINE[LNPOSN] != ascii_to_advent['%']) {
129 prmtyp = INLINE[LNPOSN+1];
130 /* A "%"; the next character determine the type of
131 * parameter: 1 (!) = suppress message completely, 29 (S) = NULL
132 * If PARAM=1, else 'S' (optional plural ending), 33 (W) = word
133 * (two 30-bit values) with trailing spaces suppressed, 22 (L) or
134 * 31 (U) = word but map to lower/upper case, 13 (C) = word in
135 * lower case with first letter capitalised, 65-73 (1-9) =
136 * number using that many characters. */
137 if (prmtyp == ascii_to_advent['!'])
139 if (prmtyp == ascii_to_advent['S']) {
141 INLINE[LNPOSN] = ascii_to_advent['s'];
142 if (PARMS[nparms] == 1)
147 if (prmtyp == ascii_to_advent['W'] || prmtyp == ascii_to_advent['L'] || prmtyp == ascii_to_advent['U'] || prmtyp == ascii_to_advent['C']) {
151 if (prmtyp == ascii_to_advent['U'])
153 if (prmtyp == ascii_to_advent['W'])
156 PUTTXT(PARMS[nparms],&state,casemake);
157 PUTTXT(PARMS[nparms+1],&state,casemake);
158 if (prmtyp == ascii_to_advent['C'] && INLINE[i] >= ascii_to_advent['a'] && INLINE[i] <= ascii_to_advent['z'])
160 // Convert to uppercase.
161 // Round-trip to ASCII and back so that this code doesn't break when the mapping changes.
162 // This can be simplified when mapping goes away.
163 char this = advent_to_ascii[INLINE[i]];
164 char uc_this = toupper(this);
165 INLINE[i] = ascii_to_advent[uc_this];
172 if (prmtyp < ascii_to_advent['!'] || prmtyp > ascii_to_advent['-']) {
176 SHFTXT(LNPOSN+2,prmtyp-2);
178 param=labs(PARMS[nparms]);
180 if (PARMS[nparms] < 0)
182 for (i=1; i <= prmtyp; i++) {
184 INLINE[LNPOSN]=MOD(param,10)+64;
185 if (i != 1 && param == 0) {
205 void PSPEAK(vocab_t msg,int skip)
206 /* Find the skip+1st message from msg and print it. msg should be
207 * the index of the inventory message for object. (INVEN+N+1 message
208 * is game.prop=N message). */
211 newspeak(object_descriptions[msg].longs[skip]);
213 newspeak(object_descriptions[msg].inventory);
216 void RSPEAK(vocab_t i)
217 /* Print the i-th "random" message (section 6 of database). */
219 newspeak(arbitrary_messages[i]);
222 void SETPRM(long first, long p1, long p2)
223 /* Stores parameters into the PRMCOM parms array for use by speak. P1 and P2
224 * are stored into PARMS(first) and PARMS(first+1). */
226 if (first >= MAXPARMS)
234 bool GETIN(FILE *input,
235 long *pword1, long *pword1x,
236 long *pword2, long *pword2x)
237 /* Get a command from the adventurer. Snarf out the first word, pad it with
238 * blanks, and return it in WORD1. Chars 6 thru 10 are returned in WORD1X, in
239 * case we need to print out the whole word in an error message. Any number of
240 * blanks may follow the word. If a second word appears, it is returned in
241 * WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
250 *pword1=GETTXT(true,true,true);
251 if (game.blklin && *pword1 < 0)
253 *pword1x=GETTXT(false,true,true);
255 junk=GETTXT(false,true,true);
258 *pword2=GETTXT(true,true,true);
259 *pword2x=GETTXT(false,true,true);
261 junk=GETTXT(false,true,true);
264 if (GETTXT(true,true,true) <= 0)
270 long YES(FILE *input, vocab_t x, vocab_t y, vocab_t z)
271 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
272 * if no, print Z and return false. */
274 token_t reply, junk1, junk2, junk3;
278 GETIN(input, &reply, &junk1, &junk2, &junk3);
279 if (reply == MAKEWD(250519) || reply == MAKEWD(25)) {
283 if (reply == MAKEWD(1415) || reply == MAKEWD(14)) {
291 /* Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT, TYPE0) */
293 long GETTXT(bool skip, bool onewrd, bool upper)
294 /* Take characters from an input line and pack them into 30-bit words.
295 * Skip says to skip leading blanks. ONEWRD says stop if we come to a
296 * blank. UPPER says to map all letters to uppercase. If we reach the
297 * end of the line, the word is filled up with blanks (which encode as 0's).
298 * If we're already at end of line when TEXT is called, we return -1. */
301 static long splitting = -1;
303 if (LNPOSN != splitting)
309 if ((!skip) || INLINE[LNPOSN] != 0)
315 for (int I=1; I<=TOKLEN; I++) {
317 if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
319 char current=INLINE[LNPOSN];
320 if (current < ascii_to_advent['%']) {
322 if (upper && current >= ascii_to_advent['a'])
328 if (splitting != LNPOSN) {
329 text=text+ascii_to_advent['%'];
334 text=text+current-ascii_to_advent['%'];
342 token_t MAKEWD(long letters)
343 /* Combine TOKLEN (currently 5) uppercase letters (represented by
344 * pairs of decimal digits in lettrs) to form a 30-bit value matching
345 * the one that GETTXT would return given those characters plus
346 * trailing blanks. Caution: lettrs will overflow 31 bits if
347 * 5-letter word starts with V-Z. As a kludgey workaround, you can
348 * increment a letter by 5 by adding 50 to the next pair of
351 long i = 1, word = 0;
353 for (long k=letters; k != 0; k=k/100) {
354 word=word+i*(MOD(k,50)+10);
356 if (MOD(k,100) > 50)word=word+i*5;
358 i=64L*64L*64L*64L*64L/i;
363 void PUTTXT(token_t word, long *state, long casemake)
364 /* Unpack the 30-bit value in word to obtain up to TOKLEN (currently
365 * 5) integer-encoded chars, and store them in inline starting at
366 * LNPOSN. If LNLENG>=LNPOSN, shift existing characters to the right
367 * to make room. STATE will be zero when puttxt is called with the
368 * first of a sequence of words, but is thereafter unchanged by the
369 * caller, so PUTTXT can use it to maintain state across calls.
370 * LNPOSN and LNLENG are incremented by the number of chars stored.
371 * If CASEMAKE=1, all letters are made uppercase; if -1, lowercase; if 0,
372 * as is. any other value for case is the same as 0 but also causes
373 * trailing blanks to be included (in anticipation of subsequent
374 * additional text). */
376 long alph1, alph2, byte, div, i, w;
378 alph1=13*casemake+24;
379 alph2=26*labs(casemake)+alph1;
380 if (labs(casemake) > 1)
382 /* alph1&2 define range of wrong-case chars, 11-36 or 37-62 or empty. */
385 for (i=1; i<=TOKLEN; i++)
387 if (w <= 0 && *state == 0 && labs(casemake) <= 1)
391 if (!(*state != 0 || byte != ascii_to_advent['%'])) {
392 *state=ascii_to_advent['%'];
397 if (*state < alph2 && *state >= alph1)*state=*state-26*casemake;
398 INLINE[LNPOSN]=*state;
403 #define PUTTXT(WORD,STATE,CASE) fPUTTXT(WORD,&STATE,CASE)
405 void SHFTXT(long from, long delta)
406 /* Move INLINE(N) to INLINE(N+DELTA) for N=FROM,LNLENG. Delta can be
407 * negative. LNLENG is updated; LNPOSN is not changed. */
411 if (!(LNLENG < from || delta == 0)) {
412 for (I=from; I<=LNLENG; I++) {
424 /* Type a blank line. This procedure is provided as a convenience for callers
425 * who otherwise have no use for MAPCOM. */
436 /* Data structure routines */
438 long VOCAB(long id, long init)
439 /* Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
440 * -1 if not found. If INIT is positive, this is an initialisation call setting
441 * up a keyword variable, and not finding it constitutes a bug. It also means
442 * that only KTAB values which taken over 1000 equal INIT may be considered.
443 * (Thus "STEPS", which is a motion verb as well as an object, may be located
444 * as an object.) And it also means the KTAB value is taken modulo 1000. */
448 for (i=1; i<=TABSIZ; i++) {
455 if (init >= 0 && KTAB[i]/1000 != init)
460 lexeme=MOD(lexeme,1000);
467 void DSTROY(long object)
468 /* Permanently eliminate "object" by moving to a non-existent location. */
473 void JUGGLE(long object)
474 /* Juggle an object by picking it up and putting it down again, the purpose
475 * being to get the object to the front of the chain of things at its loc. */
479 i=game.place[object];
480 j=game.fixed[object];
482 MOVE(object+NOBJECTS,j);
485 void MOVE(long object, long where)
486 /* Place any object anywhere by picking it up and dropping it. May
487 * already be toting, in which case the carry is a no-op. Mustn't
488 * pick up objects which are not at any loc, since carry wants to
489 * remove objects from game.atloc chains. */
493 if (object > NOBJECTS)
494 from=game.fixed[object-NOBJECTS];
496 from=game.place[object];
497 if (from > 0 && from <= 300)
502 long PUT(long object, long where, long pval)
503 /* PUT is the same as MOVE, except it returns a value used to set up the
504 * negated game.prop values for the repository objects. */
510 void CARRY(long object, long where)
511 /* Start toting an object, removing it from the list of things at its former
512 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
513 * (moving "fixed" second loc), don't change game.place or game.holdng. */
517 if (object <= NOBJECTS) {
518 if (game.place[object] == -1)
520 game.place[object]= -1;
523 if (game.atloc[where] == object) {
524 game.atloc[where]=game.link[object];
527 temp=game.atloc[where];
528 while (game.link[temp] != object) {
529 temp=game.link[temp];
531 game.link[temp]=game.link[object];
534 void DROP(long object, long where)
535 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
536 * game.holdng if the object was being toted. */
538 if (object > NOBJECTS)
539 game.fixed[object-NOBJECTS] = where;
542 if (game.place[object] == -1)
544 game.place[object] = where;
548 game.link[object] = game.atloc[where];
549 game.atloc[where] = object;
552 long ATDWRF(long where)
553 /* Return the index of first dwarf at the given location, zero if no dwarf is
554 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
555 * the pirate (6th dwarf). */
563 for (i=1; i<=NDWARVES-1; i++) {
564 if (game.dloc[i] == where)
566 if (game.dloc[i] != 0)
572 /* Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
573 * randrange, RNDVOC, BUG) */
575 long SETBIT(long bit)
576 /* Returns 2**bit for use in constructing bit-masks. */
581 bool TSTBIT(long mask, int bit)
582 /* Returns true if the specified bit is set in the mask. */
584 return (mask & (1 << bit)) != 0;
587 void set_seed(long seedval)
588 /* Set the LCG seed */
590 lcgstate.x = (unsigned long) seedval % lcgstate.m;
593 unsigned long get_next_lcg_value(void)
594 /* Return the LCG's current value, and then iterate it. */
596 unsigned long old_x = lcgstate.x;
597 lcgstate.x = (lcgstate.a * lcgstate.x + lcgstate.c) % lcgstate.m;
601 long randrange(long range)
602 /* Return a random integer from [0, range). */
604 return range * get_next_lcg_value() / lcgstate.m;
607 long RNDVOC(long second, long force)
608 /* Searches the vocabulary ATAB for a word whose second character is
609 * char, and changes that word such that each of the other four
610 * characters is a random letter. If force is non-zero, it is used
611 * as the new word. Returns the new word. */
616 for (int i = 1; i <= 5; i++) {
617 long j = 11 + randrange(26);
624 long div = 64L * 64L * 64L;
625 for (int i = 1; i <= TABSIZ; i++) {
626 if (MOD(ATAB[i]/div, 64L) == second)
637 /* The following conditions are currently considered fatal bugs. Numbers < 20
638 * are detected while reading the database; the others occur at "run time".
639 * 0 Message line > 70 characters
640 * 1 Null line in message
641 * 2 Too many words of messages
642 * 3 Too many travel options
643 * 4 Too many vocabulary words
644 * 5 Required vocabulary word not found
645 * 6 Too many RTEXT messages
647 * 8 Location has cond bit being set twice
648 * 9 Invalid section number in database
649 * 10 Too many locations
650 * 11 Too many class or turn messages
651 * 20 Special travel (500>L>300) exceeds goto list
652 * 21 Ran off end of vocabulary table
653 * 22 Vocabulary type (N/1000) not between 0 and 3
654 * 23 Intransitive action verb exceeds goto list
655 * 24 Transitive action verb exceeds goto list
656 * 25 Conditional travel entry with no alternative
657 * 26 Location has no travel entries
658 * 27 Hint number exceeds goto list
659 * 28 Invalid month returned by date function
660 * 29 Too many parameters given to SETPRM */
663 printf("Fatal error %ld. See source code for interpretation.\n", num);
667 /* Machine dependent routines (MAPLIN, TYPE, SAVEIO) */
669 bool MAPLIN(FILE *fp)
674 /* Read a line of input, from the specified input source,
675 * translate the chars to integers in the range 0-126 and store
676 * them in the common array "INLINE". Integer values are as follows:
677 * 0 = space [ASCII CODE 40 octal, 32 decimal]
678 * 1-2 = !" [ASCII 41-42 octal, 33-34 decimal]
679 * 3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
680 * 11-36 = upper-case letters
681 * 37-62 = lower-case letters
682 * 63 = percent (%) [ASCII 45 octal, 37 decimal]
683 * 64-73 = digits, 0 through 9
684 * Remaining characters can be translated any way that is convenient;
685 * The "TYPE" routine below is used to map them back to characters when
686 * necessary. The above mappings are required so that certain special
687 * characters are known to fit in 6 bits and/or can be easily spotted.
688 * Array elements beyond the end of the line should be filled with 0,
689 * and LNLENG should be set to the index of the last character.
691 * If the data file uses a character other than space (e.g., tab) to
692 * separate numbers, that character should also translate to 0.
694 * This procedure may use the map1,map2 arrays to maintain static data for
695 * the mapping. MAP2(1) is set to 0 when the program starts
696 * and is not changed thereafter unless the routines on this page choose
699 if (!oldstyle && !isatty(1))
703 IGNORE(fgets(rawbuf,sizeof(rawbuf)-1,fp));
706 char *cp = linenoise("> ");
709 strncpy(rawbuf, cp, sizeof(rawbuf)-1);
710 linenoiseHistoryAdd(rawbuf);
711 strncat(rawbuf, "\n", sizeof(rawbuf)-1);
716 (!eof && rawbuf[0] == '#');
718 if (logfp && fp == stdin)
722 if (logfp && fp == stdin)
723 IGNORE(fputs(rawbuf, logfp));
725 IGNORE(fputs(rawbuf, stdout));
726 strcpy(INLINE+1, rawbuf);
728 for (i=1; i<=(long)sizeof(INLINE) && INLINE[i]!=0; i++) {
730 INLINE[i]=ascii_to_advent[val];
740 /* Type the first "LNLENG" characters stored in inline, mapping them
741 * from integers to text per the rules described above. INLINE
742 * may be changed by this routine. */
751 for (i=1; i<=LNLENG; i++) {
752 INLINE[i]=advent_to_ascii[INLINE[i]];
755 printf("%s\n", INLINE+1);
759 void DATIME(long* d, long* t)
762 gettimeofday(&tv, NULL);
763 *d = (long) tv.tv_sec;
764 *t = (long) tv.tv_usec;
767 long MOD(long n, long m)