10 #include "linenoise/linenoise.h"
13 char* xstrdup(const char* s)
15 char* ptr = strdup(s);
17 fprintf(stderr, "Out of memory!\n");
23 void packed_to_token(long packed, char token[6])
25 // Unpack and map back to ASCII.
26 for (int i = 0; i < 5; ++i) {
27 char advent = (packed >> i * 6) & 63;
28 token[4 - i] = advent_to_ascii[(int) advent];
31 // Ensure the last character is \0.
34 // Replace trailing whitespace with \0.
35 for (int i = 4; i >= 0; --i) {
36 if (token[i] == ' ' || token[i] == '\t')
43 /* I/O routines (SPEAK, PSPEAK, RSPEAK, SETPRM, GETIN, YES) */
45 void newspeak(const char* msg)
47 // Do nothing if we got a null pointer.
51 // Do nothing if we got an empty string.
55 // Print a newline if the global game.blklin says to.
56 if (game.blklin == true)
59 // Create a copy of our string, so we can edit it.
60 char* copy = xstrdup(msg);
62 // Staging area for stringified parameters.
63 char parameters[5][100]; // FIXME: to be replaced with dynamic allocation
65 // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
66 int pi = 0; // parameter index
67 for (int i = 0; i < (int)strlen(msg); ++i) {
71 // 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.
72 if (msg[i + 1] == 'd') {
74 sprintf(parameters[pi], "%ld", PARMS[pi]);
77 // Unmodified string specifier.
78 if (msg[i + 1] == 's') {
79 packed_to_token(PARMS[pi], parameters[pi]);
82 // Singular/plural specifier.
83 if (msg[i + 1] == 'S') {
85 if (PARMS[pi - 1] > 1) { // look at the *previous* parameter (which by necessity must be numeric)
86 sprintf(parameters[pi], "%s", "s");
88 sprintf(parameters[pi], "%s", "");
92 // All-lowercase specifier.
93 if (msg[i + 1] == 'L') {
95 packed_to_token(PARMS[pi], parameters[pi]);
96 for (int j = 0; j < (int)strlen(parameters[pi]); ++j) {
97 parameters[pi][j] = tolower(parameters[pi][j]);
101 // First char uppercase, rest lowercase.
102 if (msg[i + 1] == 'C') {
104 packed_to_token(PARMS[pi], parameters[pi]);
105 for (int j = 0; j < (int)strlen(parameters[pi]); ++j) {
106 parameters[pi][j] = tolower(parameters[pi][j]);
108 parameters[pi][0] = toupper(parameters[pi][0]);
113 // Render the final string.
114 char rendered[2000]; // FIXME: to be replaced with dynamic allocation
115 sprintf(rendered, copy, parameters[1], parameters[2], parameters[3], parameters[4]); // FIXME: to be replaced with vsprintf()
117 // Print the message.
118 printf("%s\n", rendered);
123 void PSPEAK(vocab_t msg, int skip)
124 /* Find the skip+1st message from msg and print it. msg should be
125 * the index of the inventory message for object. (INVEN+N+1 message
126 * is game.prop=N message). */
129 newspeak(object_descriptions[msg].longs[skip]);
131 newspeak(object_descriptions[msg].inventory);
134 void RSPEAK(vocab_t i)
135 /* Print the i-th "random" message (section 6 of database). */
137 newspeak(arbitrary_messages[i]);
140 void SETPRM(long first, long p1, long p2)
141 /* Stores parameters into the PRMCOM parms array for use by speak. P1 and P2
142 * are stored into PARMS(first) and PARMS(first+1). */
144 if (first >= MAXPARMS)
148 PARMS[first + 1] = p2;
152 bool GETIN(FILE *input,
153 long *pword1, long *pword1x,
154 long *pword2, long *pword2x)
155 /* Get a command from the adventurer. Snarf out the first word, pad it with
156 * blanks, and return it in WORD1. Chars 6 thru 10 are returned in WORD1X, in
157 * case we need to print out the whole word in an error message. Any number of
158 * blanks may follow the word. If a second word appears, it is returned in
159 * WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
168 *pword1 = GETTXT(true, true, true);
169 if (game.blklin && *pword1 < 0)
171 *pword1x = GETTXT(false, true, true);
173 junk = GETTXT(false, true, true);
176 *pword2 = GETTXT(true, true, true);
177 *pword2x = GETTXT(false, true, true);
179 junk = GETTXT(false, true, true);
182 if (GETTXT(true, true, true) <= 0)
188 long YES(FILE *input, vocab_t x, vocab_t y, vocab_t z)
189 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
190 * if no, print Z and return false. */
192 token_t reply, junk1, junk2, junk3;
196 GETIN(input, &reply, &junk1, &junk2, &junk3);
197 if (reply == MAKEWD(250519) || reply == MAKEWD(25)) {
201 if (reply == MAKEWD(1415) || reply == MAKEWD(14)) {
205 RSPEAK(PLEASE_ANSWER);
209 /* Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT, TYPE0) */
211 long GETTXT(bool skip, bool onewrd, bool upper)
212 /* Take characters from an input line and pack them into 30-bit words.
213 * Skip says to skip leading blanks. ONEWRD says stop if we come to a
214 * blank. UPPER says to map all letters to uppercase. If we reach the
215 * end of the line, the word is filled up with blanks (which encode as 0's).
216 * If we're already at end of line when TEXT is called, we return -1. */
219 static long splitting = -1;
221 if (LNPOSN != splitting)
227 if ((!skip) || INLINE[LNPOSN] != 0)
233 for (int I = 1; I <= TOKLEN; I++) {
235 if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
237 char current = INLINE[LNPOSN];
238 if (current < ascii_to_advent['%']) {
240 if (upper && current >= ascii_to_advent['a'])
241 current = current - 26;
242 text = text + current;
246 if (splitting != LNPOSN) {
247 text = text + ascii_to_advent['%'];
252 text = text + current - ascii_to_advent['%'];
260 token_t MAKEWD(long letters)
261 /* Combine TOKLEN (currently 5) uppercase letters (represented by
262 * pairs of decimal digits in lettrs) to form a 30-bit value matching
263 * the one that GETTXT would return given those characters plus
264 * trailing blanks. Caution: lettrs will overflow 31 bits if
265 * 5-letter word starts with V-Z. As a kludgey workaround, you can
266 * increment a letter by 5 by adding 50 to the next pair of
269 long i = 1, word = 0;
271 for (long k = letters; k != 0; k = k / 100) {
272 word = word + i * (MOD(k, 50) + 10);
274 if (MOD(k, 100) > 50)word = word + i * 5;
276 i = 64L * 64L * 64L * 64L * 64L / i;
282 /* Type a blank line. This procedure is provided as a convenience for callers
283 * who otherwise have no use for MAPCOM. */
294 /* Data structure routines */
296 long VOCAB(long id, long init)
297 /* Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
298 * -1 if not found. If INIT is positive, this is an initialisation call setting
299 * up a keyword variable, and not finding it constitutes a bug. It also means
300 * that only KTAB values which taken over 1000 equal INIT may be considered.
301 * (Thus "STEPS", which is a motion verb as well as an object, may be located
302 * as an object.) And it also means the KTAB value is taken modulo 1000. */
306 for (long i = 1; i <= TABSIZ; i++) {
313 if (init >= 0 && KTAB[i] / 1000 != init)
318 lexeme = MOD(lexeme, 1000);
325 void JUGGLE(long object)
326 /* Juggle an object by picking it up and putting it down again, the purpose
327 * being to get the object to the front of the chain of things at its loc. */
331 i = game.place[object];
332 j = game.fixed[object];
334 MOVE(object + NOBJECTS, j);
337 void MOVE(long object, long where)
338 /* Place any object anywhere by picking it up and dropping it. May
339 * already be toting, in which case the carry is a no-op. Mustn't
340 * pick up objects which are not at any loc, since carry wants to
341 * remove objects from game.atloc chains. */
345 if (object > NOBJECTS)
346 from = game.fixed[object - NOBJECTS];
348 from = game.place[object];
349 if (from != NOWHERE && from != CARRIED && !SPECIAL(from))
354 long PUT(long object, long where, long pval)
355 /* PUT is the same as MOVE, except it returns a value used to set up the
356 * negated game.prop values for the repository objects. */
362 void CARRY(long object, long where)
363 /* Start toting an object, removing it from the list of things at its former
364 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
365 * (moving "fixed" second loc), don't change game.place or game.holdng. */
369 if (object <= NOBJECTS) {
370 if (game.place[object] == CARRIED)
372 game.place[object] = CARRIED;
375 if (game.atloc[where] == object) {
376 game.atloc[where] = game.link[object];
379 temp = game.atloc[where];
380 while (game.link[temp] != object) {
381 temp = game.link[temp];
383 game.link[temp] = game.link[object];
386 void DROP(long object, long where)
387 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
388 * game.holdng if the object was being toted. */
390 if (object > NOBJECTS)
391 game.fixed[object - NOBJECTS] = where;
393 if (game.place[object] == CARRIED)
395 game.place[object] = where;
399 game.link[object] = game.atloc[where];
400 game.atloc[where] = object;
403 long ATDWRF(long where)
404 /* Return the index of first dwarf at the given location, zero if no dwarf is
405 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
406 * the pirate (6th dwarf). */
414 for (long i = 1; i <= NDWARVES - 1; i++) {
415 if (game.dloc[i] == where)
417 if (game.dloc[i] != 0)
423 /* Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
424 * randrange, RNDVOC, BUG) */
426 long SETBIT(long bit)
427 /* Returns 2**bit for use in constructing bit-masks. */
432 bool TSTBIT(long mask, int bit)
433 /* Returns true if the specified bit is set in the mask. */
435 return (mask & (1 << bit)) != 0;
438 void set_seed(long seedval)
439 /* Set the LCG seed */
441 game.lcg_x = (unsigned long) seedval % game.lcg_m;
444 unsigned long get_next_lcg_value(void)
445 /* Return the LCG's current value, and then iterate it. */
447 unsigned long old_x = game.lcg_x;
448 game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
452 long randrange(long range)
453 /* Return a random integer from [0, range). */
455 return range * get_next_lcg_value() / game.lcg_m;
458 long RNDVOC(long second, long force)
459 /* Searches the vocabulary ATAB for a word whose second character is
460 * char, and changes that word such that each of the other four
461 * characters is a random letter. If force is non-zero, it is used
462 * as the new word. Returns the new word. */
467 for (int i = 1; i <= 5; i++) {
468 long j = 11 + randrange(26);
475 long div = 64L * 64L * 64L;
476 for (int i = 1; i <= TABSIZ; i++) {
477 if (MOD(ATAB[i] / div, 64L) == second) {
487 /* The following conditions are currently considered fatal bugs. Numbers < 20
488 * are detected while reading the database; the others occur at "run time".
489 * 0 Message line > 70 characters
490 * 1 Null line in message
491 * 2 Too many words of messages
492 * 3 Too many travel options
493 * 4 Too many vocabulary words
494 * 5 Required vocabulary word not found
495 * 6 Too many RTEXT messages
497 * 8 Location has cond bit being set twice
498 * 9 Invalid section number in database
499 * 10 Too many locations
500 * 11 Too many class or turn messages
501 * 20 Special travel (500>L>300) exceeds goto list
502 * 21 Ran off end of vocabulary table
503 * 22 Vocabulary type (N/1000) not between 0 and 3
504 * 23 Intransitive action verb exceeds goto list
505 * 24 Transitive action verb exceeds goto list
506 * 25 Conditional travel entry with no alternative
507 * 26 Location has no travel entries
508 * 27 Hint number exceeds goto list
509 * 28 Invalid month returned by date function
510 * 29 Too many parameters given to SETPRM */
513 printf("Fatal error %ld. See source code for interpretation.\n", num);
517 /* Machine dependent routines (MAPLIN, TYPE, SAVEIO) */
519 bool MAPLIN(FILE *fp)
523 /* Read a line of input, from the specified input source.
524 * This logic is complicated partly because it has to serve
525 * several cases with different requirements and partly because
526 * of a quirk in linenoise().
528 * The quirk shows up when you paste a test log from the clipboard
529 * to the program's command prompt. While fgets (as expected)
530 * consumes it a line at a time, linenoise() returns the first
531 * line and discards the rest. Thus, there needs to be an
532 * editline (-s) option to fall back to fgets while still
533 * prompting. Note that linenoise does behave properly when
534 * fed redirected stdin.
536 * The logging is a bit of a mess because there are two distinct cases
537 * in which you want to echo commands. One is when shipping them to
538 * a log under the -l option, in which case you want to suppress
539 * prompt generation (so test logs are unadorned command sequences).
540 * On the other hand, if you redirected stdin and are feeding the program
541 * a logfile, you *do* want prompt generation - it makes checkfiles
542 * easier to read when the commands are marked by a preceding prompt.
548 IGNORE(fgets(rawbuf, sizeof(rawbuf) - 1, fp));
551 char *cp = linenoise("> ");
554 strncpy(rawbuf, cp, sizeof(rawbuf) - 1);
555 linenoiseHistoryAdd(rawbuf);
556 strncat(rawbuf, "\n", sizeof(rawbuf) - strlen(rawbuf) - 1);
561 (!eof && rawbuf[0] == '#');
563 if (logfp && fp == stdin)
568 if (logfp && fp == stdin)
573 if (prompt && efp == stdout)
575 IGNORE(fputs(rawbuf, efp));
577 strcpy(INLINE + 1, rawbuf);
578 /* translate the chars to integers in the range 0-126 and store
579 * them in the common array "INLINE". Integer values are as follows:
580 * 0 = space [ASCII CODE 40 octal, 32 decimal]
581 * 1-2 = !" [ASCII 41-42 octal, 33-34 decimal]
582 * 3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
583 * 11-36 = upper-case letters
584 * 37-62 = lower-case letters
585 * 63 = percent (%) [ASCII 45 octal, 37 decimal]
586 * 64-73 = digits, 0 through 9
587 * Remaining characters can be translated any way that is convenient;
588 * The "TYPE" routine below is used to map them back to characters when
589 * necessary. The above mappings are required so that certain special
590 * characters are known to fit in 6 bits and/or can be easily spotted.
591 * Array elements beyond the end of the line should be filled with 0,
592 * and LNLENG should be set to the index of the last character.
594 * If the data file uses a character other than space (e.g., tab) to
595 * separate numbers, that character should also translate to 0.
597 * This procedure may use the map1,map2 arrays to maintain static data for
598 * the mapping. MAP2(1) is set to 0 when the program starts
599 * and is not changed thereafter unless the routines on this page choose
602 for (long i = 1; i <= (long)sizeof(INLINE) && INLINE[i] != 0; i++) {
603 long val = INLINE[i];
604 INLINE[i] = ascii_to_advent[val];
614 /* Type the first "LNLENG" characters stored in inline, mapping them
615 * from integers to text per the rules described above. INLINE
616 * may be changed by this routine. */
625 for (i = 1; i <= LNLENG; i++) {
626 INLINE[i] = advent_to_ascii[(int) INLINE[i]];
628 INLINE[LNLENG + 1] = 0;
629 printf("%s\n", INLINE + 1);
633 void DATIME(long* d, long* t)
636 gettimeofday(&tv, NULL);
637 *d = (long) tv.tv_sec;
638 *t = (long) tv.tv_usec;