10 #include "linenoise/linenoise.h"
13 char* xstrdup(const char* s)
15 char* ptr = strdup(s);
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 = xstrdup(msg);
65 // Staging area for stringified parameters.
66 char parameters[5][100]; // FIXME: to be replaced with dynamic allocation
68 // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
69 int pi = 0; // parameter index
70 for (int i = 0; i < strlen(msg); ++i)
76 // 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.
77 if (msg[i + 1] == 'd')
80 sprintf(parameters[pi], "%ld", PARMS[pi]);
83 // Unmodified string specifier.
84 if (msg[i + 1] == 's')
86 packed_to_token(PARMS[pi], parameters[pi]);
89 // Singular/plural specifier.
90 if (msg[i + 1] == 'S')
93 if (PARMS[pi - 1] > 1) // look at the *previous* parameter (which by necessity must be numeric)
95 sprintf(parameters[pi], "%s", "s");
99 sprintf(parameters[pi], "%s", "");
103 // All-lowercase specifier.
104 if (msg[i + 1] == 'L')
107 packed_to_token(PARMS[pi], parameters[pi]);
108 for (int i = 0; i < strlen(parameters[pi]); ++i)
110 parameters[pi][i] = tolower(parameters[pi][i]);
114 // First char uppercase, rest lowercase.
115 if (msg[i + 1] == 'C')
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]);
123 parameters[pi][0] = toupper(parameters[pi][0]);
128 // Render the final string.
129 char rendered[2000]; // FIXME: to be replaced with dynamic allocation
130 sprintf(rendered, copy, parameters[1], parameters[2], parameters[3], parameters[4]); // FIXME: to be replaced with vsprintf()
132 // Print the message.
133 printf("%s\n", rendered);
138 void PSPEAK(vocab_t msg,int skip)
139 /* Find the skip+1st message from msg and print it. msg should be
140 * the index of the inventory message for object. (INVEN+N+1 message
141 * is game.prop=N message). */
144 newspeak(object_descriptions[msg].longs[skip]);
146 newspeak(object_descriptions[msg].inventory);
149 void RSPEAK(vocab_t i)
150 /* Print the i-th "random" message (section 6 of database). */
152 newspeak(arbitrary_messages[i]);
155 void SETPRM(long first, long p1, long p2)
156 /* Stores parameters into the PRMCOM parms array for use by speak. P1 and P2
157 * are stored into PARMS(first) and PARMS(first+1). */
159 if (first >= MAXPARMS)
167 bool GETIN(FILE *input,
168 long *pword1, long *pword1x,
169 long *pword2, long *pword2x)
170 /* Get a command from the adventurer. Snarf out the first word, pad it with
171 * blanks, and return it in WORD1. Chars 6 thru 10 are returned in WORD1X, in
172 * case we need to print out the whole word in an error message. Any number of
173 * blanks may follow the word. If a second word appears, it is returned in
174 * WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
183 *pword1=GETTXT(true,true,true);
184 if (game.blklin && *pword1 < 0)
186 *pword1x=GETTXT(false,true,true);
188 junk=GETTXT(false,true,true);
191 *pword2=GETTXT(true,true,true);
192 *pword2x=GETTXT(false,true,true);
194 junk=GETTXT(false,true,true);
197 if (GETTXT(true,true,true) <= 0)
203 long YES(FILE *input, vocab_t x, vocab_t y, vocab_t z)
204 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
205 * if no, print Z and return false. */
207 token_t reply, junk1, junk2, junk3;
211 GETIN(input, &reply, &junk1, &junk2, &junk3);
212 if (reply == MAKEWD(250519) || reply == MAKEWD(25)) {
216 if (reply == MAKEWD(1415) || reply == MAKEWD(14)) {
224 /* Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT, TYPE0) */
226 long GETTXT(bool skip, bool onewrd, bool upper)
227 /* Take characters from an input line and pack them into 30-bit words.
228 * Skip says to skip leading blanks. ONEWRD says stop if we come to a
229 * blank. UPPER says to map all letters to uppercase. If we reach the
230 * end of the line, the word is filled up with blanks (which encode as 0's).
231 * If we're already at end of line when TEXT is called, we return -1. */
234 static long splitting = -1;
236 if (LNPOSN != splitting)
242 if ((!skip) || INLINE[LNPOSN] != 0)
248 for (int I=1; I<=TOKLEN; I++) {
250 if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
252 char current=INLINE[LNPOSN];
253 if (current < ascii_to_advent['%']) {
255 if (upper && current >= ascii_to_advent['a'])
261 if (splitting != LNPOSN) {
262 text=text+ascii_to_advent['%'];
267 text=text+current-ascii_to_advent['%'];
275 token_t MAKEWD(long letters)
276 /* Combine TOKLEN (currently 5) uppercase letters (represented by
277 * pairs of decimal digits in lettrs) to form a 30-bit value matching
278 * the one that GETTXT would return given those characters plus
279 * trailing blanks. Caution: lettrs will overflow 31 bits if
280 * 5-letter word starts with V-Z. As a kludgey workaround, you can
281 * increment a letter by 5 by adding 50 to the next pair of
284 long i = 1, word = 0;
286 for (long k=letters; k != 0; k=k/100) {
287 word=word+i*(MOD(k,50)+10);
289 if (MOD(k,100) > 50)word=word+i*5;
291 i=64L*64L*64L*64L*64L/i;
297 /* Type a blank line. This procedure is provided as a convenience for callers
298 * who otherwise have no use for MAPCOM. */
309 /* Data structure routines */
311 long VOCAB(long id, long init)
312 /* Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
313 * -1 if not found. If INIT is positive, this is an initialisation call setting
314 * up a keyword variable, and not finding it constitutes a bug. It also means
315 * that only KTAB values which taken over 1000 equal INIT may be considered.
316 * (Thus "STEPS", which is a motion verb as well as an object, may be located
317 * as an object.) And it also means the KTAB value is taken modulo 1000. */
321 for (i=1; i<=TABSIZ; i++) {
328 if (init >= 0 && KTAB[i]/1000 != init)
333 lexeme=MOD(lexeme,1000);
340 void DSTROY(long object)
341 /* Permanently eliminate "object" by moving to a non-existent location. */
346 void JUGGLE(long object)
347 /* Juggle an object by picking it up and putting it down again, the purpose
348 * being to get the object to the front of the chain of things at its loc. */
352 i=game.place[object];
353 j=game.fixed[object];
355 MOVE(object+NOBJECTS,j);
358 void MOVE(long object, long where)
359 /* Place any object anywhere by picking it up and dropping it. May
360 * already be toting, in which case the carry is a no-op. Mustn't
361 * pick up objects which are not at any loc, since carry wants to
362 * remove objects from game.atloc chains. */
366 if (object > NOBJECTS)
367 from=game.fixed[object-NOBJECTS];
369 from=game.place[object];
370 if (from > 0 && from <= 300)
375 long PUT(long object, long where, long pval)
376 /* PUT is the same as MOVE, except it returns a value used to set up the
377 * negated game.prop values for the repository objects. */
383 void CARRY(long object, long where)
384 /* Start toting an object, removing it from the list of things at its former
385 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
386 * (moving "fixed" second loc), don't change game.place or game.holdng. */
390 if (object <= NOBJECTS) {
391 if (game.place[object] == -1)
393 game.place[object]= -1;
396 if (game.atloc[where] == object) {
397 game.atloc[where]=game.link[object];
400 temp=game.atloc[where];
401 while (game.link[temp] != object) {
402 temp=game.link[temp];
404 game.link[temp]=game.link[object];
407 void DROP(long object, long where)
408 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
409 * game.holdng if the object was being toted. */
411 if (object > NOBJECTS)
412 game.fixed[object-NOBJECTS] = where;
415 if (game.place[object] == -1)
417 game.place[object] = where;
421 game.link[object] = game.atloc[where];
422 game.atloc[where] = object;
425 long ATDWRF(long where)
426 /* Return the index of first dwarf at the given location, zero if no dwarf is
427 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
428 * the pirate (6th dwarf). */
436 for (i=1; i<=NDWARVES-1; i++) {
437 if (game.dloc[i] == where)
439 if (game.dloc[i] != 0)
445 /* Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
446 * randrange, RNDVOC, BUG) */
448 long SETBIT(long bit)
449 /* Returns 2**bit for use in constructing bit-masks. */
454 bool TSTBIT(long mask, int bit)
455 /* Returns true if the specified bit is set in the mask. */
457 return (mask & (1 << bit)) != 0;
460 void set_seed(long seedval)
461 /* Set the LCG seed */
463 lcgstate.x = (unsigned long) seedval % lcgstate.m;
466 unsigned long get_next_lcg_value(void)
467 /* Return the LCG's current value, and then iterate it. */
469 unsigned long old_x = lcgstate.x;
470 lcgstate.x = (lcgstate.a * lcgstate.x + lcgstate.c) % lcgstate.m;
474 long randrange(long range)
475 /* Return a random integer from [0, range). */
477 return range * get_next_lcg_value() / lcgstate.m;
480 long RNDVOC(long second, long force)
481 /* Searches the vocabulary ATAB for a word whose second character is
482 * char, and changes that word such that each of the other four
483 * characters is a random letter. If force is non-zero, it is used
484 * as the new word. Returns the new word. */
489 for (int i = 1; i <= 5; i++) {
490 long j = 11 + randrange(26);
497 long div = 64L * 64L * 64L;
498 for (int i = 1; i <= TABSIZ; i++) {
499 if (MOD(ATAB[i]/div, 64L) == second)
510 /* The following conditions are currently considered fatal bugs. Numbers < 20
511 * are detected while reading the database; the others occur at "run time".
512 * 0 Message line > 70 characters
513 * 1 Null line in message
514 * 2 Too many words of messages
515 * 3 Too many travel options
516 * 4 Too many vocabulary words
517 * 5 Required vocabulary word not found
518 * 6 Too many RTEXT messages
520 * 8 Location has cond bit being set twice
521 * 9 Invalid section number in database
522 * 10 Too many locations
523 * 11 Too many class or turn messages
524 * 20 Special travel (500>L>300) exceeds goto list
525 * 21 Ran off end of vocabulary table
526 * 22 Vocabulary type (N/1000) not between 0 and 3
527 * 23 Intransitive action verb exceeds goto list
528 * 24 Transitive action verb exceeds goto list
529 * 25 Conditional travel entry with no alternative
530 * 26 Location has no travel entries
531 * 27 Hint number exceeds goto list
532 * 28 Invalid month returned by date function
533 * 29 Too many parameters given to SETPRM */
536 printf("Fatal error %ld. See source code for interpretation.\n", num);
540 /* Machine dependent routines (MAPLIN, TYPE, SAVEIO) */
542 bool MAPLIN(FILE *fp)
547 /* Read a line of input, from the specified input source.
548 * This logic is complicated partly because it has to serve
549 * several cases with different requirements and partly because
550 * of a quirk in linenoise().
552 * The quirk shows up when you paste a test log from the clipboard
553 * to the program's command prompt. While fgets (as expected)
554 * consumes it a line at a time, linenoise() returns the first
555 * line and discards the rest. Thus, there needs to be an
556 * editline (-s) option to fall back to fgets while still
557 * prompting. Note that linenoise does behave properly when
558 * fed redirected stdin.
560 * The logging is a bit of a mess because there are two distinct cases
561 * in which you want to echo commands. One is when shipping them to
562 * a log under the -l option, in which case you want to suppress
563 * prompt generation (so test logs are unadorned command sequences).
564 * On the other hand, if you redirected stdin and are feeding the program
565 * a logfile, you *do* want prompt generation - it makes checkfiles
566 * easier to read when the commands are marked by a preceding prompt.
572 IGNORE(fgets(rawbuf,sizeof(rawbuf)-1,fp));
575 char *cp = linenoise("> ");
578 strncpy(rawbuf, cp, sizeof(rawbuf)-1);
579 linenoiseHistoryAdd(rawbuf);
580 strncat(rawbuf, "\n", sizeof(rawbuf)-1);
585 (!eof && rawbuf[0] == '#');
587 if (logfp && fp == stdin)
592 if (logfp && fp == stdin)
598 if (prompt && efp == stdout)
600 IGNORE(fputs(rawbuf, efp));
602 strcpy(INLINE+1, rawbuf);
603 /* translate the chars to integers in the range 0-126 and store
604 * them in the common array "INLINE". Integer values are as follows:
605 * 0 = space [ASCII CODE 40 octal, 32 decimal]
606 * 1-2 = !" [ASCII 41-42 octal, 33-34 decimal]
607 * 3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
608 * 11-36 = upper-case letters
609 * 37-62 = lower-case letters
610 * 63 = percent (%) [ASCII 45 octal, 37 decimal]
611 * 64-73 = digits, 0 through 9
612 * Remaining characters can be translated any way that is convenient;
613 * The "TYPE" routine below is used to map them back to characters when
614 * necessary. The above mappings are required so that certain special
615 * characters are known to fit in 6 bits and/or can be easily spotted.
616 * Array elements beyond the end of the line should be filled with 0,
617 * and LNLENG should be set to the index of the last character.
619 * If the data file uses a character other than space (e.g., tab) to
620 * separate numbers, that character should also translate to 0.
622 * This procedure may use the map1,map2 arrays to maintain static data for
623 * the mapping. MAP2(1) is set to 0 when the program starts
624 * and is not changed thereafter unless the routines on this page choose
627 for (i=1; i<=(long)sizeof(INLINE) && INLINE[i]!=0; i++) {
629 INLINE[i]=ascii_to_advent[val];
639 /* Type the first "LNLENG" characters stored in inline, mapping them
640 * from integers to text per the rules described above. INLINE
641 * may be changed by this routine. */
650 for (i=1; i<=LNLENG; i++) {
651 INLINE[i]=advent_to_ascii[INLINE[i]];
654 printf("%s\n", INLINE+1);
658 void DATIME(long* d, long* t)
661 gettimeofday(&tv, NULL);
662 *d = (long) tv.tv_sec;
663 *t = (long) tv.tv_usec;