10 #include "linenoise/linenoise.h"
13 void* xmalloc(size_t size)
15 void* ptr = malloc(size);
18 fprintf(stderr, "Out of memory!\n");
24 char* xstrdup(const char* s)
26 char* ptr = strdup(s);
29 fprintf(stderr, "Out of memory!\n");
35 void packed_to_token(long packed, char token[6])
37 // Unpack and map back to ASCII.
38 for (int i = 0; i < 5; ++i)
40 char advent = (packed >> i * 6) & 63;
41 token[4 - i] = advent_to_ascii[advent];
44 // Ensure the last character is \0.
47 // Replace trailing whitespace with \0.
48 for (int i = 4; i >= 0; --i)
50 if (token[i] == ' ' || token[i] == '\t')
57 /* I/O routines (SPEAK, PSPEAK, RSPEAK, SETPRM, GETIN, YES) */
59 void newspeak(char* msg)
61 // Do nothing if we got a null pointer.
65 // Do nothing if we got an empty string.
69 // Print a newline if the global game.blklin says to.
70 if (game.blklin == true)
73 // Create a copy of our string, so we can edit it.
74 char* copy = xstrdup(msg);
76 // Staging area for stringified parameters.
77 char parameters[5][100]; // FIXME: to be replaced with dynamic allocation
79 // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
80 int pi = 0; // parameter index
81 for (int i = 0; i < strlen(msg); ++i)
87 // 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.
88 if (msg[i + 1] == 'd')
91 sprintf(parameters[pi], "%ld", PARMS[pi]);
94 // Unmodified string specifier.
95 if (msg[i + 1] == 's')
97 packed_to_token(PARMS[pi], parameters[pi]);
100 // Singular/plural specifier.
101 if (msg[i + 1] == 'S')
104 if (PARMS[pi - 1] > 1) // look at the *previous* parameter (which by necessity must be numeric)
106 sprintf(parameters[pi], "%s", "s");
110 sprintf(parameters[pi], "%s", "");
114 // All-lowercase specifier.
115 if (msg[i + 1] == 'L')
118 packed_to_token(PARMS[pi], parameters[pi]);
119 for (int i = 0; i < strlen(parameters[pi]); ++i)
121 parameters[pi][i] = tolower(parameters[pi][i]);
125 // First char uppercase, rest lowercase.
126 if (msg[i + 1] == 'C')
129 packed_to_token(PARMS[pi], parameters[pi]);
130 for (int i = 0; i < strlen(parameters[pi]); ++i)
132 parameters[pi][i] = tolower(parameters[pi][i]);
134 parameters[pi][0] = toupper(parameters[pi][0]);
139 // Render the final string.
140 char rendered[2000]; // FIXME: to be replaced with dynamic allocation
141 sprintf((char *)&rendered, copy, parameters[1], parameters[2], parameters[3], parameters[4]); // FIXME: to be replaced with vsprintf()
143 // Print the message.
144 printf("%s\n", rendered);
149 void PSPEAK(vocab_t msg,int skip)
150 /* Find the skip+1st message from msg and print it. msg should be
151 * the index of the inventory message for object. (INVEN+N+1 message
152 * is game.prop=N message). */
155 newspeak(object_descriptions[msg].longs[skip]);
157 newspeak(object_descriptions[msg].inventory);
160 void RSPEAK(vocab_t i)
161 /* Print the i-th "random" message (section 6 of database). */
163 newspeak(arbitrary_messages[i]);
166 void SETPRM(long first, long p1, long p2)
167 /* Stores parameters into the PRMCOM parms array for use by speak. P1 and P2
168 * are stored into PARMS(first) and PARMS(first+1). */
170 if (first >= MAXPARMS)
178 bool GETIN(FILE *input,
179 long *pword1, long *pword1x,
180 long *pword2, long *pword2x)
181 /* Get a command from the adventurer. Snarf out the first word, pad it with
182 * blanks, and return it in WORD1. Chars 6 thru 10 are returned in WORD1X, in
183 * case we need to print out the whole word in an error message. Any number of
184 * blanks may follow the word. If a second word appears, it is returned in
185 * WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
194 *pword1=GETTXT(true,true,true);
195 if (game.blklin && *pword1 < 0)
197 *pword1x=GETTXT(false,true,true);
199 junk=GETTXT(false,true,true);
202 *pword2=GETTXT(true,true,true);
203 *pword2x=GETTXT(false,true,true);
205 junk=GETTXT(false,true,true);
208 if (GETTXT(true,true,true) <= 0)
214 long YES(FILE *input, vocab_t x, vocab_t y, vocab_t z)
215 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
216 * if no, print Z and return false. */
218 token_t reply, junk1, junk2, junk3;
222 GETIN(input, &reply, &junk1, &junk2, &junk3);
223 if (reply == MAKEWD(250519) || reply == MAKEWD(25)) {
227 if (reply == MAKEWD(1415) || reply == MAKEWD(14)) {
235 /* Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT, TYPE0) */
237 long GETTXT(bool skip, bool onewrd, bool upper)
238 /* Take characters from an input line and pack them into 30-bit words.
239 * Skip says to skip leading blanks. ONEWRD says stop if we come to a
240 * blank. UPPER says to map all letters to uppercase. If we reach the
241 * end of the line, the word is filled up with blanks (which encode as 0's).
242 * If we're already at end of line when TEXT is called, we return -1. */
245 static long splitting = -1;
247 if (LNPOSN != splitting)
253 if ((!skip) || INLINE[LNPOSN] != 0)
259 for (int I=1; I<=TOKLEN; I++) {
261 if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
263 char current=INLINE[LNPOSN];
264 if (current < ascii_to_advent['%']) {
266 if (upper && current >= ascii_to_advent['a'])
272 if (splitting != LNPOSN) {
273 text=text+ascii_to_advent['%'];
278 text=text+current-ascii_to_advent['%'];
286 token_t MAKEWD(long letters)
287 /* Combine TOKLEN (currently 5) uppercase letters (represented by
288 * pairs of decimal digits in lettrs) to form a 30-bit value matching
289 * the one that GETTXT would return given those characters plus
290 * trailing blanks. Caution: lettrs will overflow 31 bits if
291 * 5-letter word starts with V-Z. As a kludgey workaround, you can
292 * increment a letter by 5 by adding 50 to the next pair of
295 long i = 1, word = 0;
297 for (long k=letters; k != 0; k=k/100) {
298 word=word+i*(MOD(k,50)+10);
300 if (MOD(k,100) > 50)word=word+i*5;
302 i=64L*64L*64L*64L*64L/i;
307 void PUTTXT(token_t word, long *state, long casemake)
308 /* Unpack the 30-bit value in word to obtain up to TOKLEN (currently
309 * 5) integer-encoded chars, and store them in inline starting at
310 * LNPOSN. If LNLENG>=LNPOSN, shift existing characters to the right
311 * to make room. STATE will be zero when puttxt is called with the
312 * first of a sequence of words, but is thereafter unchanged by the
313 * caller, so PUTTXT can use it to maintain state across calls.
314 * LNPOSN and LNLENG are incremented by the number of chars stored.
315 * If CASEMAKE=1, all letters are made uppercase; if -1, lowercase; if 0,
316 * as is. any other value for case is the same as 0 but also causes
317 * trailing blanks to be included (in anticipation of subsequent
318 * additional text). */
320 long alph1, alph2, byte, div, i, w;
322 alph1=13*casemake+24;
323 alph2=26*labs(casemake)+alph1;
324 if (labs(casemake) > 1)
326 /* alph1&2 define range of wrong-case chars, 11-36 or 37-62 or empty. */
329 for (i=1; i<=TOKLEN; i++)
331 if (w <= 0 && *state == 0 && labs(casemake) <= 1)
335 if (!(*state != 0 || byte != ascii_to_advent['%'])) {
336 *state=ascii_to_advent['%'];
341 if (*state < alph2 && *state >= alph1)*state=*state-26*casemake;
342 INLINE[LNPOSN]=*state;
347 #define PUTTXT(WORD,STATE,CASE) fPUTTXT(WORD,&STATE,CASE)
349 void SHFTXT(long from, long delta)
350 /* Move INLINE(N) to INLINE(N+DELTA) for N=FROM,LNLENG. Delta can be
351 * negative. LNLENG is updated; LNPOSN is not changed. */
355 if (!(LNLENG < from || delta == 0)) {
356 for (I=from; I<=LNLENG; I++) {
368 /* Type a blank line. This procedure is provided as a convenience for callers
369 * who otherwise have no use for MAPCOM. */
380 /* Data structure routines */
382 long VOCAB(long id, long init)
383 /* Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
384 * -1 if not found. If INIT is positive, this is an initialisation call setting
385 * up a keyword variable, and not finding it constitutes a bug. It also means
386 * that only KTAB values which taken over 1000 equal INIT may be considered.
387 * (Thus "STEPS", which is a motion verb as well as an object, may be located
388 * as an object.) And it also means the KTAB value is taken modulo 1000. */
392 for (i=1; i<=TABSIZ; i++) {
399 if (init >= 0 && KTAB[i]/1000 != init)
404 lexeme=MOD(lexeme,1000);
411 void DSTROY(long object)
412 /* Permanently eliminate "object" by moving to a non-existent location. */
417 void JUGGLE(long object)
418 /* Juggle an object by picking it up and putting it down again, the purpose
419 * being to get the object to the front of the chain of things at its loc. */
423 i=game.place[object];
424 j=game.fixed[object];
426 MOVE(object+NOBJECTS,j);
429 void MOVE(long object, long where)
430 /* Place any object anywhere by picking it up and dropping it. May
431 * already be toting, in which case the carry is a no-op. Mustn't
432 * pick up objects which are not at any loc, since carry wants to
433 * remove objects from game.atloc chains. */
437 if (object > NOBJECTS)
438 from=game.fixed[object-NOBJECTS];
440 from=game.place[object];
441 if (from > 0 && from <= 300)
446 long PUT(long object, long where, long pval)
447 /* PUT is the same as MOVE, except it returns a value used to set up the
448 * negated game.prop values for the repository objects. */
454 void CARRY(long object, long where)
455 /* Start toting an object, removing it from the list of things at its former
456 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
457 * (moving "fixed" second loc), don't change game.place or game.holdng. */
461 if (object <= NOBJECTS) {
462 if (game.place[object] == -1)
464 game.place[object]= -1;
467 if (game.atloc[where] == object) {
468 game.atloc[where]=game.link[object];
471 temp=game.atloc[where];
472 while (game.link[temp] != object) {
473 temp=game.link[temp];
475 game.link[temp]=game.link[object];
478 void DROP(long object, long where)
479 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
480 * game.holdng if the object was being toted. */
482 if (object > NOBJECTS)
483 game.fixed[object-NOBJECTS] = where;
486 if (game.place[object] == -1)
488 game.place[object] = where;
492 game.link[object] = game.atloc[where];
493 game.atloc[where] = object;
496 long ATDWRF(long where)
497 /* Return the index of first dwarf at the given location, zero if no dwarf is
498 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
499 * the pirate (6th dwarf). */
507 for (i=1; i<=NDWARVES-1; i++) {
508 if (game.dloc[i] == where)
510 if (game.dloc[i] != 0)
516 /* Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
517 * randrange, RNDVOC, BUG) */
519 long SETBIT(long bit)
520 /* Returns 2**bit for use in constructing bit-masks. */
525 bool TSTBIT(long mask, int bit)
526 /* Returns true if the specified bit is set in the mask. */
528 return (mask & (1 << bit)) != 0;
531 void set_seed(long seedval)
532 /* Set the LCG seed */
534 lcgstate.x = (unsigned long) seedval % lcgstate.m;
537 unsigned long get_next_lcg_value(void)
538 /* Return the LCG's current value, and then iterate it. */
540 unsigned long old_x = lcgstate.x;
541 lcgstate.x = (lcgstate.a * lcgstate.x + lcgstate.c) % lcgstate.m;
545 long randrange(long range)
546 /* Return a random integer from [0, range). */
548 return range * get_next_lcg_value() / lcgstate.m;
551 long RNDVOC(long second, long force)
552 /* Searches the vocabulary ATAB for a word whose second character is
553 * char, and changes that word such that each of the other four
554 * characters is a random letter. If force is non-zero, it is used
555 * as the new word. Returns the new word. */
560 for (int i = 1; i <= 5; i++) {
561 long j = 11 + randrange(26);
568 long div = 64L * 64L * 64L;
569 for (int i = 1; i <= TABSIZ; i++) {
570 if (MOD(ATAB[i]/div, 64L) == second)
581 /* The following conditions are currently considered fatal bugs. Numbers < 20
582 * are detected while reading the database; the others occur at "run time".
583 * 0 Message line > 70 characters
584 * 1 Null line in message
585 * 2 Too many words of messages
586 * 3 Too many travel options
587 * 4 Too many vocabulary words
588 * 5 Required vocabulary word not found
589 * 6 Too many RTEXT messages
591 * 8 Location has cond bit being set twice
592 * 9 Invalid section number in database
593 * 10 Too many locations
594 * 11 Too many class or turn messages
595 * 20 Special travel (500>L>300) exceeds goto list
596 * 21 Ran off end of vocabulary table
597 * 22 Vocabulary type (N/1000) not between 0 and 3
598 * 23 Intransitive action verb exceeds goto list
599 * 24 Transitive action verb exceeds goto list
600 * 25 Conditional travel entry with no alternative
601 * 26 Location has no travel entries
602 * 27 Hint number exceeds goto list
603 * 28 Invalid month returned by date function
604 * 29 Too many parameters given to SETPRM */
607 printf("Fatal error %ld. See source code for interpretation.\n", num);
611 /* Machine dependent routines (MAPLIN, TYPE, SAVEIO) */
613 bool MAPLIN(FILE *fp)
618 /* Read a line of input, from the specified input source,
619 * translate the chars to integers in the range 0-126 and store
620 * them in the common array "INLINE". Integer values are as follows:
621 * 0 = space [ASCII CODE 40 octal, 32 decimal]
622 * 1-2 = !" [ASCII 41-42 octal, 33-34 decimal]
623 * 3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
624 * 11-36 = upper-case letters
625 * 37-62 = lower-case letters
626 * 63 = percent (%) [ASCII 45 octal, 37 decimal]
627 * 64-73 = digits, 0 through 9
628 * Remaining characters can be translated any way that is convenient;
629 * The "TYPE" routine below is used to map them back to characters when
630 * necessary. The above mappings are required so that certain special
631 * characters are known to fit in 6 bits and/or can be easily spotted.
632 * Array elements beyond the end of the line should be filled with 0,
633 * and LNLENG should be set to the index of the last character.
635 * If the data file uses a character other than space (e.g., tab) to
636 * separate numbers, that character should also translate to 0.
638 * This procedure may use the map1,map2 arrays to maintain static data for
639 * the mapping. MAP2(1) is set to 0 when the program starts
640 * and is not changed thereafter unless the routines on this page choose
647 IGNORE(fgets(rawbuf,sizeof(rawbuf)-1,fp));
650 char *cp = linenoise(prompt ? "> ": "");
653 strncpy(rawbuf, cp, sizeof(rawbuf)-1);
654 linenoiseHistoryAdd(rawbuf);
655 strncat(rawbuf, "\n", sizeof(rawbuf)-1);
660 (!eof && rawbuf[0] == '#');
662 if (logfp && fp == stdin)
666 if (logfp && fp == stdin)
667 IGNORE(fputs(rawbuf, logfp));
669 IGNORE(fputs(rawbuf, stdout));
670 strcpy(INLINE+1, rawbuf);
672 for (i=1; i<=(long)sizeof(INLINE) && INLINE[i]!=0; i++) {
674 INLINE[i]=ascii_to_advent[val];
684 /* Type the first "LNLENG" characters stored in inline, mapping them
685 * from integers to text per the rules described above. INLINE
686 * may be changed by this routine. */
695 for (i=1; i<=LNLENG; i++) {
696 INLINE[i]=advent_to_ascii[INLINE[i]];
699 printf("%s\n", INLINE+1);
703 void DATIME(long* d, long* t)
706 gettimeofday(&tv, NULL);
707 *d = (long) tv.tv_sec;
708 *t = (long) tv.tv_usec;