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(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;
308 /* Type a blank line. This procedure is provided as a convenience for callers
309 * who otherwise have no use for MAPCOM. */
320 /* Data structure routines */
322 long VOCAB(long id, long init)
323 /* Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
324 * -1 if not found. If INIT is positive, this is an initialisation call setting
325 * up a keyword variable, and not finding it constitutes a bug. It also means
326 * that only KTAB values which taken over 1000 equal INIT may be considered.
327 * (Thus "STEPS", which is a motion verb as well as an object, may be located
328 * as an object.) And it also means the KTAB value is taken modulo 1000. */
332 for (i=1; i<=TABSIZ; i++) {
339 if (init >= 0 && KTAB[i]/1000 != init)
344 lexeme=MOD(lexeme,1000);
351 void DSTROY(long object)
352 /* Permanently eliminate "object" by moving to a non-existent location. */
357 void JUGGLE(long object)
358 /* Juggle an object by picking it up and putting it down again, the purpose
359 * being to get the object to the front of the chain of things at its loc. */
363 i=game.place[object];
364 j=game.fixed[object];
366 MOVE(object+NOBJECTS,j);
369 void MOVE(long object, long where)
370 /* Place any object anywhere by picking it up and dropping it. May
371 * already be toting, in which case the carry is a no-op. Mustn't
372 * pick up objects which are not at any loc, since carry wants to
373 * remove objects from game.atloc chains. */
377 if (object > NOBJECTS)
378 from=game.fixed[object-NOBJECTS];
380 from=game.place[object];
381 if (from > 0 && from <= 300)
386 long PUT(long object, long where, long pval)
387 /* PUT is the same as MOVE, except it returns a value used to set up the
388 * negated game.prop values for the repository objects. */
394 void CARRY(long object, long where)
395 /* Start toting an object, removing it from the list of things at its former
396 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
397 * (moving "fixed" second loc), don't change game.place or game.holdng. */
401 if (object <= NOBJECTS) {
402 if (game.place[object] == -1)
404 game.place[object]= -1;
407 if (game.atloc[where] == object) {
408 game.atloc[where]=game.link[object];
411 temp=game.atloc[where];
412 while (game.link[temp] != object) {
413 temp=game.link[temp];
415 game.link[temp]=game.link[object];
418 void DROP(long object, long where)
419 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
420 * game.holdng if the object was being toted. */
422 if (object > NOBJECTS)
423 game.fixed[object-NOBJECTS] = where;
426 if (game.place[object] == -1)
428 game.place[object] = where;
432 game.link[object] = game.atloc[where];
433 game.atloc[where] = object;
436 long ATDWRF(long where)
437 /* Return the index of first dwarf at the given location, zero if no dwarf is
438 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
439 * the pirate (6th dwarf). */
447 for (i=1; i<=NDWARVES-1; i++) {
448 if (game.dloc[i] == where)
450 if (game.dloc[i] != 0)
456 /* Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
457 * randrange, RNDVOC, BUG) */
459 long SETBIT(long bit)
460 /* Returns 2**bit for use in constructing bit-masks. */
465 bool TSTBIT(long mask, int bit)
466 /* Returns true if the specified bit is set in the mask. */
468 return (mask & (1 << bit)) != 0;
471 void set_seed(long seedval)
472 /* Set the LCG seed */
474 lcgstate.x = (unsigned long) seedval % lcgstate.m;
477 unsigned long get_next_lcg_value(void)
478 /* Return the LCG's current value, and then iterate it. */
480 unsigned long old_x = lcgstate.x;
481 lcgstate.x = (lcgstate.a * lcgstate.x + lcgstate.c) % lcgstate.m;
485 long randrange(long range)
486 /* Return a random integer from [0, range). */
488 return range * get_next_lcg_value() / lcgstate.m;
491 long RNDVOC(long second, long force)
492 /* Searches the vocabulary ATAB for a word whose second character is
493 * char, and changes that word such that each of the other four
494 * characters is a random letter. If force is non-zero, it is used
495 * as the new word. Returns the new word. */
500 for (int i = 1; i <= 5; i++) {
501 long j = 11 + randrange(26);
508 long div = 64L * 64L * 64L;
509 for (int i = 1; i <= TABSIZ; i++) {
510 if (MOD(ATAB[i]/div, 64L) == second)
521 /* The following conditions are currently considered fatal bugs. Numbers < 20
522 * are detected while reading the database; the others occur at "run time".
523 * 0 Message line > 70 characters
524 * 1 Null line in message
525 * 2 Too many words of messages
526 * 3 Too many travel options
527 * 4 Too many vocabulary words
528 * 5 Required vocabulary word not found
529 * 6 Too many RTEXT messages
531 * 8 Location has cond bit being set twice
532 * 9 Invalid section number in database
533 * 10 Too many locations
534 * 11 Too many class or turn messages
535 * 20 Special travel (500>L>300) exceeds goto list
536 * 21 Ran off end of vocabulary table
537 * 22 Vocabulary type (N/1000) not between 0 and 3
538 * 23 Intransitive action verb exceeds goto list
539 * 24 Transitive action verb exceeds goto list
540 * 25 Conditional travel entry with no alternative
541 * 26 Location has no travel entries
542 * 27 Hint number exceeds goto list
543 * 28 Invalid month returned by date function
544 * 29 Too many parameters given to SETPRM */
547 printf("Fatal error %ld. See source code for interpretation.\n", num);
551 /* Machine dependent routines (MAPLIN, TYPE, SAVEIO) */
553 bool MAPLIN(FILE *fp)
558 /* Read a line of input, from the specified input source,
559 * translate the chars to integers in the range 0-126 and store
560 * them in the common array "INLINE". Integer values are as follows:
561 * 0 = space [ASCII CODE 40 octal, 32 decimal]
562 * 1-2 = !" [ASCII 41-42 octal, 33-34 decimal]
563 * 3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
564 * 11-36 = upper-case letters
565 * 37-62 = lower-case letters
566 * 63 = percent (%) [ASCII 45 octal, 37 decimal]
567 * 64-73 = digits, 0 through 9
568 * Remaining characters can be translated any way that is convenient;
569 * The "TYPE" routine below is used to map them back to characters when
570 * necessary. The above mappings are required so that certain special
571 * characters are known to fit in 6 bits and/or can be easily spotted.
572 * Array elements beyond the end of the line should be filled with 0,
573 * and LNLENG should be set to the index of the last character.
575 * If the data file uses a character other than space (e.g., tab) to
576 * separate numbers, that character should also translate to 0.
578 * This procedure may use the map1,map2 arrays to maintain static data for
579 * the mapping. MAP2(1) is set to 0 when the program starts
580 * and is not changed thereafter unless the routines on this page choose
587 IGNORE(fgets(rawbuf,sizeof(rawbuf)-1,fp));
590 char *cp = linenoise("> ");
593 strncpy(rawbuf, cp, sizeof(rawbuf)-1);
594 linenoiseHistoryAdd(rawbuf);
595 strncat(rawbuf, "\n", sizeof(rawbuf)-1);
600 (!eof && rawbuf[0] == '#');
602 if (logfp && fp == stdin)
607 if (logfp && fp == stdin)
615 IGNORE(fputs(rawbuf, efp));
617 strcpy(INLINE+1, rawbuf);
619 for (i=1; i<=(long)sizeof(INLINE) && INLINE[i]!=0; i++) {
621 INLINE[i]=ascii_to_advent[val];
631 /* Type the first "LNLENG" characters stored in inline, mapping them
632 * from integers to text per the rules described above. INLINE
633 * may be changed by this routine. */
642 for (i=1; i<=LNLENG; i++) {
643 INLINE[i]=advent_to_ascii[INLINE[i]];
646 printf("%s\n", INLINE+1);
650 void DATIME(long* d, long* t)
653 gettimeofday(&tv, NULL);
654 *d = (long) tv.tv_sec;
655 *t = (long) tv.tv_usec;