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 // Unpack and map back to ASCII.
27 for (int i = 0; i < 5; ++i)
29 char advent = (packed >> i * 6) & 63;
30 token[4 - i] = advent_to_ascii[advent];
33 // Ensure the last character is \0.
36 // Replace trailing whitespace with \0.
37 for (int i = 4; i >= 0; --i)
39 if (token[i] == ' ' || token[i] == '\t')
46 /* I/O routines (SPEAK, PSPEAK, RSPEAK, SETPRM, GETIN, YES) */
48 void newspeak(char* msg)
50 // Do nothing if we got a null pointer.
54 // Do nothing if we got an empty string.
58 // Print a newline if the global game.blklin says to.
59 if (game.blklin == true)
62 // Create a copy of our string, so we can edit it.
63 char* copy = (char*) xmalloc(strlen(msg) + 1);
64 strncpy(copy, msg, strlen(msg) + 1);
66 // Staging area for stringified parameters.
67 char parameters[5][100]; // FIXME: to be replaced with dynamic allocation
69 // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
70 int pi = 0; // parameter index
71 for (int i = 0; i < strlen(msg); ++i)
77 // 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.
78 if (msg[i + 1] == 'd')
81 sprintf(parameters[pi], "%d", PARMS[pi]);
84 // Unmodified string specifier.
85 if (msg[i + 1] == 's')
87 packed_to_token(PARMS[pi], parameters[pi]);
90 // Singular/plural specifier.
91 if (msg[i + 1] == 'S')
94 if (PARMS[pi - 1] > 1) // look at the *previous* parameter (which by necessity must be numeric)
96 sprintf(parameters[pi], "%s", "s");
100 sprintf(parameters[pi], "%s", "");
104 // All-lowercase specifier.
105 if (msg[i + 1] == 'L')
108 packed_to_token(PARMS[pi], parameters[pi]);
109 for (int i = 0; i < strlen(parameters[pi]); ++i)
111 parameters[pi][i] = tolower(parameters[pi][i]);
115 // First char uppercase, rest lowercase.
116 if (msg[i + 1] == 'C')
119 packed_to_token(PARMS[pi], parameters[pi]);
120 for (int i = 0; i < strlen(parameters[pi]); ++i)
122 parameters[pi][i] = tolower(parameters[pi][i]);
124 parameters[pi][0] = toupper(parameters[pi][0]);
129 // Render the final string.
130 char rendered[2000]; // FIXME: to be replaced with dynamic allocation
131 sprintf(&rendered, copy, parameters[1], parameters[2], parameters[3], parameters[4]); // FIXME: to be replaced with vsprintf()
133 // Print the message.
134 printf("%s\n", rendered);
139 void PSPEAK(vocab_t msg,int skip)
140 /* Find the skip+1st message from msg and print it. msg should be
141 * the index of the inventory message for object. (INVEN+N+1 message
142 * is game.prop=N message). */
145 newspeak(object_descriptions[msg].longs[skip]);
147 newspeak(object_descriptions[msg].inventory);
150 void RSPEAK(vocab_t i)
151 /* Print the i-th "random" message (section 6 of database). */
153 newspeak(arbitrary_messages[i]);
156 void SETPRM(long first, long p1, long p2)
157 /* Stores parameters into the PRMCOM parms array for use by speak. P1 and P2
158 * are stored into PARMS(first) and PARMS(first+1). */
160 if (first >= MAXPARMS)
168 bool GETIN(FILE *input,
169 long *pword1, long *pword1x,
170 long *pword2, long *pword2x)
171 /* Get a command from the adventurer. Snarf out the first word, pad it with
172 * blanks, and return it in WORD1. Chars 6 thru 10 are returned in WORD1X, in
173 * case we need to print out the whole word in an error message. Any number of
174 * blanks may follow the word. If a second word appears, it is returned in
175 * WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
184 *pword1=GETTXT(true,true,true);
185 if (game.blklin && *pword1 < 0)
187 *pword1x=GETTXT(false,true,true);
189 junk=GETTXT(false,true,true);
192 *pword2=GETTXT(true,true,true);
193 *pword2x=GETTXT(false,true,true);
195 junk=GETTXT(false,true,true);
198 if (GETTXT(true,true,true) <= 0)
204 long YES(FILE *input, vocab_t x, vocab_t y, vocab_t z)
205 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
206 * if no, print Z and return false. */
208 token_t reply, junk1, junk2, junk3;
212 GETIN(input, &reply, &junk1, &junk2, &junk3);
213 if (reply == MAKEWD(250519) || reply == MAKEWD(25)) {
217 if (reply == MAKEWD(1415) || reply == MAKEWD(14)) {
225 /* Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT, TYPE0) */
227 long GETTXT(bool skip, bool onewrd, bool upper)
228 /* Take characters from an input line and pack them into 30-bit words.
229 * Skip says to skip leading blanks. ONEWRD says stop if we come to a
230 * blank. UPPER says to map all letters to uppercase. If we reach the
231 * end of the line, the word is filled up with blanks (which encode as 0's).
232 * If we're already at end of line when TEXT is called, we return -1. */
235 static long splitting = -1;
237 if (LNPOSN != splitting)
243 if ((!skip) || INLINE[LNPOSN] != 0)
249 for (int I=1; I<=TOKLEN; I++) {
251 if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
253 char current=INLINE[LNPOSN];
254 if (current < ascii_to_advent['%']) {
256 if (upper && current >= ascii_to_advent['a'])
262 if (splitting != LNPOSN) {
263 text=text+ascii_to_advent['%'];
268 text=text+current-ascii_to_advent['%'];
276 token_t MAKEWD(long letters)
277 /* Combine TOKLEN (currently 5) uppercase letters (represented by
278 * pairs of decimal digits in lettrs) to form a 30-bit value matching
279 * the one that GETTXT would return given those characters plus
280 * trailing blanks. Caution: lettrs will overflow 31 bits if
281 * 5-letter word starts with V-Z. As a kludgey workaround, you can
282 * increment a letter by 5 by adding 50 to the next pair of
285 long i = 1, word = 0;
287 for (long k=letters; k != 0; k=k/100) {
288 word=word+i*(MOD(k,50)+10);
290 if (MOD(k,100) > 50)word=word+i*5;
292 i=64L*64L*64L*64L*64L/i;
297 void PUTTXT(token_t word, long *state, long casemake)
298 /* Unpack the 30-bit value in word to obtain up to TOKLEN (currently
299 * 5) integer-encoded chars, and store them in inline starting at
300 * LNPOSN. If LNLENG>=LNPOSN, shift existing characters to the right
301 * to make room. STATE will be zero when puttxt is called with the
302 * first of a sequence of words, but is thereafter unchanged by the
303 * caller, so PUTTXT can use it to maintain state across calls.
304 * LNPOSN and LNLENG are incremented by the number of chars stored.
305 * If CASEMAKE=1, all letters are made uppercase; if -1, lowercase; if 0,
306 * as is. any other value for case is the same as 0 but also causes
307 * trailing blanks to be included (in anticipation of subsequent
308 * additional text). */
310 long alph1, alph2, byte, div, i, w;
312 alph1=13*casemake+24;
313 alph2=26*labs(casemake)+alph1;
314 if (labs(casemake) > 1)
316 /* alph1&2 define range of wrong-case chars, 11-36 or 37-62 or empty. */
319 for (i=1; i<=TOKLEN; i++)
321 if (w <= 0 && *state == 0 && labs(casemake) <= 1)
325 if (!(*state != 0 || byte != ascii_to_advent['%'])) {
326 *state=ascii_to_advent['%'];
331 if (*state < alph2 && *state >= alph1)*state=*state-26*casemake;
332 INLINE[LNPOSN]=*state;
337 #define PUTTXT(WORD,STATE,CASE) fPUTTXT(WORD,&STATE,CASE)
339 void SHFTXT(long from, long delta)
340 /* Move INLINE(N) to INLINE(N+DELTA) for N=FROM,LNLENG. Delta can be
341 * negative. LNLENG is updated; LNPOSN is not changed. */
345 if (!(LNLENG < from || delta == 0)) {
346 for (I=from; I<=LNLENG; I++) {
358 /* Type a blank line. This procedure is provided as a convenience for callers
359 * who otherwise have no use for MAPCOM. */
370 /* Data structure routines */
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. */
382 for (i=1; i<=TABSIZ; i++) {
389 if (init >= 0 && KTAB[i]/1000 != init)
394 lexeme=MOD(lexeme,1000);
401 void DSTROY(long object)
402 /* Permanently eliminate "object" by moving to a non-existent location. */
407 void JUGGLE(long object)
408 /* Juggle an object by picking it up and putting it down again, the purpose
409 * being to get the object to the front of the chain of things at its loc. */
413 i=game.place[object];
414 j=game.fixed[object];
416 MOVE(object+NOBJECTS,j);
419 void MOVE(long object, long where)
420 /* Place any object anywhere by picking it up and dropping it. May
421 * already be toting, in which case the carry is a no-op. Mustn't
422 * pick up objects which are not at any loc, since carry wants to
423 * remove objects from game.atloc chains. */
427 if (object > NOBJECTS)
428 from=game.fixed[object-NOBJECTS];
430 from=game.place[object];
431 if (from > 0 && from <= 300)
436 long PUT(long object, long where, long pval)
437 /* PUT is the same as MOVE, except it returns a value used to set up the
438 * negated game.prop values for the repository objects. */
444 void CARRY(long object, long where)
445 /* Start toting an object, removing it from the list of things at its former
446 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
447 * (moving "fixed" second loc), don't change game.place or game.holdng. */
451 if (object <= NOBJECTS) {
452 if (game.place[object] == -1)
454 game.place[object]= -1;
457 if (game.atloc[where] == object) {
458 game.atloc[where]=game.link[object];
461 temp=game.atloc[where];
462 while (game.link[temp] != object) {
463 temp=game.link[temp];
465 game.link[temp]=game.link[object];
468 void DROP(long object, long where)
469 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
470 * game.holdng if the object was being toted. */
472 if (object > NOBJECTS)
473 game.fixed[object-NOBJECTS] = where;
476 if (game.place[object] == -1)
478 game.place[object] = where;
482 game.link[object] = game.atloc[where];
483 game.atloc[where] = object;
486 long ATDWRF(long where)
487 /* Return the index of first dwarf at the given location, zero if no dwarf is
488 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
489 * the pirate (6th dwarf). */
497 for (i=1; i<=NDWARVES-1; i++) {
498 if (game.dloc[i] == where)
500 if (game.dloc[i] != 0)
506 /* Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
507 * randrange, RNDVOC, BUG) */
509 long SETBIT(long bit)
510 /* Returns 2**bit for use in constructing bit-masks. */
515 bool TSTBIT(long mask, int bit)
516 /* Returns true if the specified bit is set in the mask. */
518 return (mask & (1 << bit)) != 0;
521 void set_seed(long seedval)
522 /* Set the LCG seed */
524 lcgstate.x = (unsigned long) seedval % lcgstate.m;
527 unsigned long get_next_lcg_value(void)
528 /* Return the LCG's current value, and then iterate it. */
530 unsigned long old_x = lcgstate.x;
531 lcgstate.x = (lcgstate.a * lcgstate.x + lcgstate.c) % lcgstate.m;
535 long randrange(long range)
536 /* Return a random integer from [0, range). */
538 return range * get_next_lcg_value() / lcgstate.m;
541 long RNDVOC(long second, long force)
542 /* Searches the vocabulary ATAB for a word whose second character is
543 * char, and changes that word such that each of the other four
544 * characters is a random letter. If force is non-zero, it is used
545 * as the new word. Returns the new word. */
550 for (int i = 1; i <= 5; i++) {
551 long j = 11 + randrange(26);
558 long div = 64L * 64L * 64L;
559 for (int i = 1; i <= TABSIZ; i++) {
560 if (MOD(ATAB[i]/div, 64L) == second)
571 /* The following conditions are currently considered fatal bugs. Numbers < 20
572 * are detected while reading the database; the others occur at "run time".
573 * 0 Message line > 70 characters
574 * 1 Null line in message
575 * 2 Too many words of messages
576 * 3 Too many travel options
577 * 4 Too many vocabulary words
578 * 5 Required vocabulary word not found
579 * 6 Too many RTEXT messages
581 * 8 Location has cond bit being set twice
582 * 9 Invalid section number in database
583 * 10 Too many locations
584 * 11 Too many class or turn messages
585 * 20 Special travel (500>L>300) exceeds goto list
586 * 21 Ran off end of vocabulary table
587 * 22 Vocabulary type (N/1000) not between 0 and 3
588 * 23 Intransitive action verb exceeds goto list
589 * 24 Transitive action verb exceeds goto list
590 * 25 Conditional travel entry with no alternative
591 * 26 Location has no travel entries
592 * 27 Hint number exceeds goto list
593 * 28 Invalid month returned by date function
594 * 29 Too many parameters given to SETPRM */
597 printf("Fatal error %ld. See source code for interpretation.\n", num);
601 /* Machine dependent routines (MAPLIN, TYPE, SAVEIO) */
603 bool MAPLIN(FILE *fp)
608 /* Read a line of input, from the specified input source,
609 * translate the chars to integers in the range 0-126 and store
610 * them in the common array "INLINE". Integer values are as follows:
611 * 0 = space [ASCII CODE 40 octal, 32 decimal]
612 * 1-2 = !" [ASCII 41-42 octal, 33-34 decimal]
613 * 3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
614 * 11-36 = upper-case letters
615 * 37-62 = lower-case letters
616 * 63 = percent (%) [ASCII 45 octal, 37 decimal]
617 * 64-73 = digits, 0 through 9
618 * Remaining characters can be translated any way that is convenient;
619 * The "TYPE" routine below is used to map them back to characters when
620 * necessary. The above mappings are required so that certain special
621 * characters are known to fit in 6 bits and/or can be easily spotted.
622 * Array elements beyond the end of the line should be filled with 0,
623 * and LNLENG should be set to the index of the last character.
625 * If the data file uses a character other than space (e.g., tab) to
626 * separate numbers, that character should also translate to 0.
628 * This procedure may use the map1,map2 arrays to maintain static data for
629 * the mapping. MAP2(1) is set to 0 when the program starts
630 * and is not changed thereafter unless the routines on this page choose
633 if (!oldstyle && !isatty(1))
637 IGNORE(fgets(rawbuf,sizeof(rawbuf)-1,fp));
640 char *cp = linenoise("> ");
643 strncpy(rawbuf, cp, sizeof(rawbuf)-1);
644 linenoiseHistoryAdd(rawbuf);
645 strncat(rawbuf, "\n", sizeof(rawbuf)-1);
650 (!eof && rawbuf[0] == '#');
652 if (logfp && fp == stdin)
656 if (logfp && fp == stdin)
657 IGNORE(fputs(rawbuf, logfp));
659 IGNORE(fputs(rawbuf, stdout));
660 strcpy(INLINE+1, rawbuf);
662 for (i=1; i<=(long)sizeof(INLINE) && INLINE[i]!=0; i++) {
664 INLINE[i]=ascii_to_advent[val];
674 /* Type the first "LNLENG" characters stored in inline, mapping them
675 * from integers to text per the rules described above. INLINE
676 * may be changed by this routine. */
685 for (i=1; i<=LNLENG; i++) {
686 INLINE[i]=advent_to_ascii[INLINE[i]];
689 printf("%s\n", INLINE+1);
693 void DATIME(long* d, long* t)
696 gettimeofday(&tv, NULL);
697 *d = (long) tv.tv_sec;
698 *t = (long) tv.tv_usec;
701 long MOD(long n, long m)