11 #include "linenoise/linenoise.h"
14 void* xmalloc(size_t size)
16 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) {
28 char advent = (packed >> i * 6) & 63;
29 token[4 - i] = advent_to_ascii[(int) advent];
32 // Ensure the last character is \0.
35 // Replace trailing whitespace with \0.
36 for (int i = 4; i >= 0; --i) {
37 if (token[i] == ' ' || token[i] == '\t')
44 void token_to_packed(char token[6], long* packed)
47 for (size_t i = 0; i < 5; ++i)
49 if (token[4 - i] == '\0')
51 char mapped = ascii_to_advent[(int) token[4 - i]];
52 *packed |= (mapped << (6 * i));
56 /* Hide the fact that wods are corrently packed longs */
58 bool wordeq(token_t a, token_t b)
63 bool wordempty(token_t a)
68 void wordclear(token_t *v)
73 /* I/O routines (speak, pspeak, rspeak, GETIN, YES) */
75 void vspeak(const char* msg, va_list ap)
77 // Do nothing if we got a null pointer.
81 // Do nothing if we got an empty string.
85 // Print a newline if the global game.blklin says to.
86 if (game.blklin == true)
89 int msglen = strlen(msg);
92 ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
93 char* rendered = xmalloc(size);
94 char* renderp = rendered;
96 // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
97 long previous_arg = 0;
98 for (int i = 0; i < msglen; i++) {
103 long arg = va_arg(ap, long);
107 // 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.
109 int ret = snprintf(renderp, size, "%ld", arg);
116 // Unmodified string specifier.
118 packed_to_token(arg, renderp); /* unpack directly to destination */
119 size_t len = strlen(renderp);
124 // Singular/plural specifier.
126 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
132 // All-lowercase specifier.
133 if (msg[i] == 'L' || msg[i] == 'C') {
134 packed_to_token(arg, renderp); /* unpack directly to destination */
135 int len = strlen(renderp);
136 for (int j = 0; j < len; ++j) {
137 renderp[j] = tolower(renderp[j]);
139 if (msg[i] == 'C') // First char uppercase, rest lowercase.
140 renderp[0] = toupper(renderp[0]);
150 // Print the message.
151 printf("%s\n", rendered);
156 void speak(const char* msg, ...)
164 void pspeak(vocab_t msg, enum speaktype mode, int skip, ...)
165 /* Find the skip+1st message from msg and print it. Modes are:
166 * feel = for inventory, what you can touch
167 * look = the long description for the state the object is in
168 * listen = the sound for the state the object is in
169 * study = text on the object. */
175 vspeak(object_descriptions[msg].inventory, ap);
178 vspeak(object_descriptions[msg].longs[skip], ap);
181 vspeak(object_descriptions[msg].sounds[skip], ap);
184 vspeak(object_descriptions[msg].texts[skip], ap);
190 void rspeak(vocab_t i, ...)
191 /* Print the i-th "random" message (section 6 of database). */
195 vspeak(arbitrary_messages[i], ap);
199 bool GETIN(FILE *input,
200 long *pword1, long *pword1x,
201 long *pword2, long *pword2x)
202 /* Get a command from the adventurer. Snarf out the first word, pad it with
203 * blanks, and return it in WORD1. Chars 6 thru 10 are returned in WORD1X, in
204 * case we need to print out the whole word in an error message. Any number of
205 * blanks may follow the word. If a second word appears, it is returned in
206 * WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
212 fputc('\n', stdout);;
215 *pword1 = GETTXT(true, true, true);
216 if (game.blklin && *pword1 < 0)
218 *pword1x = GETTXT(false, true, true);
220 junk = GETTXT(false, true, true);
223 *pword2 = GETTXT(true, true, true);
224 *pword2x = GETTXT(false, true, true);
226 junk = GETTXT(false, true, true);
229 if (GETTXT(true, true, true) <= 0)
235 void echo_input(FILE* destination, char* input_prompt, char* input)
237 size_t len = strlen(input_prompt) + strlen(input) + 1;
238 char* prompt_and_input = (char*) xmalloc(len);
239 strcpy(prompt_and_input, input_prompt);
240 strcat(prompt_and_input, input);
241 fprintf(destination, "%s\n", prompt_and_input);
242 free(prompt_and_input);
248 char input_prompt[] = "> ";
250 input_prompt[0] = '\0';
252 // Print a blank line if game.blklin tells us to.
253 if (game.blklin == true)
259 input = linenoise(input_prompt);
264 printf("%s", input_prompt);
265 IGNORE(getline(&input, &n, stdin));
268 if (input == NULL) // Got EOF; return with it.
270 else if (input[0] == '#') // Ignore comments.
272 else // We have a 'normal' line; leave the loop.
276 // Strip trailing newlines from the input
277 input[strcspn(input, "\n")] = 0;
279 linenoiseHistoryAdd(input);
282 echo_input(stdout, input_prompt, input);
285 echo_input(logfp, input_prompt, input);
290 bool YES(const char* question, const char* yes_response, const char* no_response)
291 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
292 * if no, print Z and return false. */
302 linenoiseFree(reply);
306 char* firstword = (char*) xmalloc(strlen(reply)+1);
307 sscanf(reply, "%s", firstword);
309 for (int i = 0; i < (int)strlen(firstword); ++i)
310 firstword[i] = tolower(firstword[i]);
312 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
313 int y = strncmp("y", firstword, sizeof("y") - 1);
314 int no = strncmp("no", firstword, sizeof("no") - 1);
315 int n = strncmp("n", firstword, sizeof("n") - 1);
319 if (yes == 0 || y == 0) {
323 } else if (no == 0 || n == 0) {
328 rspeak(PLEASE_ANSWER);
330 linenoiseFree(reply);
334 /* Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT) */
336 long GETTXT(bool skip, bool onewrd, bool upper)
337 /* Take characters from an input line and pack them into 30-bit words.
338 * Skip says to skip leading blanks. ONEWRD says stop if we come to a
339 * blank. UPPER says to map all letters to uppercase. If we reach the
340 * end of the line, the word is filled up with blanks (which encode as 0's).
341 * If we're already at end of line when TEXT is called, we return -1. */
344 static long splitting = -1;
346 if (LNPOSN != splitting)
352 if ((!skip) || INLINE[LNPOSN] != 0)
358 for (int I = 1; I <= TOKLEN; I++) {
360 if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
362 char current = INLINE[LNPOSN];
363 if (current < ascii_to_advent['%']) {
365 if (upper && current >= ascii_to_advent['a'])
366 current = current - 26;
367 text = text + current;
371 if (splitting != LNPOSN) {
372 text = text + ascii_to_advent['%'];
377 text = text + current - ascii_to_advent['%'];
385 token_t MAKEWD(long letters)
386 /* Combine TOKLEN (currently 5) uppercase letters (represented by
387 * pairs of decimal digits in lettrs) to form a 30-bit value matching
388 * the one that GETTXT would return given those characters plus
389 * trailing blanks. Caution: lettrs will overflow 31 bits if
390 * 5-letter word starts with V-Z. As a kludgey workaround, you can
391 * increment a letter by 5 by adding 50 to the next pair of
394 long i = 1, word = 0;
396 for (long k = letters; k != 0; k = k / 100) {
397 word = word + i * (MOD(k, 50) + 10);
399 if (MOD(k, 100) > 50)word = word + i * 5;
401 i = 64L * 64L * 64L * 64L * 64L / i;
406 /* Data structure routines */
408 long VOCAB(long id, long init)
409 /* Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
410 * -1 if not found. If INIT is positive, this is an initialisation call setting
411 * up a keyword variable, and not finding it constitutes a bug. It also means
412 * that only KTAB values which taken over 1000 equal INIT may be considered.
413 * (Thus "STEPS", which is a motion verb as well as an object, may be located
414 * as an object.) And it also means the KTAB value is taken modulo 1000. */
418 for (long i = 1; i <= TABSIZ; i++) {
423 BUG(REQUIRED_VOCABULARY_WORD_NOT_FOUND);
425 if (init >= 0 && KTAB[i] / 1000 != init)
430 lexeme = MOD(lexeme, 1000);
434 BUG(RAN_OFF_END_OF_VOCABULARY_TABLE);
437 void JUGGLE(long object)
438 /* Juggle an object by picking it up and putting it down again, the purpose
439 * being to get the object to the front of the chain of things at its loc. */
443 i = game.place[object];
444 j = game.fixed[object];
446 MOVE(object + NOBJECTS, j);
449 void MOVE(long object, long where)
450 /* Place any object anywhere by picking it up and dropping it. May
451 * already be toting, in which case the carry is a no-op. Mustn't
452 * pick up objects which are not at any loc, since carry wants to
453 * remove objects from game.atloc chains. */
457 if (object > NOBJECTS)
458 from = game.fixed[object - NOBJECTS];
460 from = game.place[object];
461 if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
466 long PUT(long object, long where, long pval)
467 /* PUT is the same as MOVE, except it returns a value used to set up the
468 * negated game.prop values for the repository objects. */
474 void CARRY(long object, long where)
475 /* Start toting an object, removing it from the list of things at its former
476 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
477 * (moving "fixed" second loc), don't change game.place or game.holdng. */
481 if (object <= NOBJECTS) {
482 if (game.place[object] == CARRIED)
484 game.place[object] = CARRIED;
487 if (game.atloc[where] == object) {
488 game.atloc[where] = game.link[object];
491 temp = game.atloc[where];
492 while (game.link[temp] != object) {
493 temp = game.link[temp];
495 game.link[temp] = game.link[object];
498 void DROP(long object, long where)
499 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
500 * game.holdng if the object was being toted. */
502 if (object > NOBJECTS)
503 game.fixed[object - NOBJECTS] = where;
505 if (game.place[object] == CARRIED)
507 game.place[object] = where;
511 game.link[object] = game.atloc[where];
512 game.atloc[where] = object;
515 long ATDWRF(long where)
516 /* Return the index of first dwarf at the given location, zero if no dwarf is
517 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
518 * the pirate (6th dwarf). */
526 for (long i = 1; i <= NDWARVES - 1; i++) {
527 if (game.dloc[i] == where)
529 if (game.dloc[i] != 0)
535 /* Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
536 * randrange, RNDVOC) */
538 long SETBIT(long bit)
539 /* Returns 2**bit for use in constructing bit-masks. */
544 bool TSTBIT(long mask, int bit)
545 /* Returns true if the specified bit is set in the mask. */
547 return (mask & (1 << bit)) != 0;
550 void set_seed(long seedval)
551 /* Set the LCG seed */
553 game.lcg_x = (unsigned long) seedval % game.lcg_m;
556 unsigned long get_next_lcg_value(void)
557 /* Return the LCG's current value, and then iterate it. */
559 unsigned long old_x = game.lcg_x;
560 game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
564 long randrange(long range)
565 /* Return a random integer from [0, range). */
567 return range * get_next_lcg_value() / game.lcg_m;
570 long RNDVOC(long second, long force)
571 /* Searches the vocabulary ATAB for a word whose second character is
572 * char, and changes that word such that each of the other four
573 * characters is a random letter. If force is non-zero, it is used
574 * as the new word. Returns the new word. */
579 for (int i = 1; i <= 5; i++) {
580 long j = 11 + randrange(26);
587 long div = 64L * 64L * 64L;
588 for (int i = 1; i <= TABSIZ; i++) {
589 if (MOD(ATAB[i] / div, 64L) == second) {
599 /* Machine dependent routines (MAPLIN, SAVEIO) */
601 bool MAPLIN(FILE *fp)
605 /* Read a line of input, from the specified input source.
606 * This logic is complicated partly because it has to serve
607 * several cases with different requirements and partly because
608 * of a quirk in linenoise().
610 * The quirk shows up when you paste a test log from the clipboard
611 * to the program's command prompt. While fgets (as expected)
612 * consumes it a line at a time, linenoise() returns the first
613 * line and discards the rest. Thus, there needs to be an
614 * editline (-s) option to fall back to fgets while still
615 * prompting. Note that linenoise does behave properly when
616 * fed redirected stdin.
618 * The logging is a bit of a mess because there are two distinct cases
619 * in which you want to echo commands. One is when shipping them to
620 * a log under the -l option, in which case you want to suppress
621 * prompt generation (so test logs are unadorned command sequences).
622 * On the other hand, if you redirected stdin and are feeding the program
623 * a logfile, you *do* want prompt generation - it makes checkfiles
624 * easier to read when the commands are marked by a preceding prompt.
630 IGNORE(fgets(rawbuf, sizeof(rawbuf) - 1, fp));
633 char *cp = linenoise("> ");
636 strncpy(rawbuf, cp, sizeof(rawbuf) - 1);
637 linenoiseHistoryAdd(rawbuf);
638 strncat(rawbuf, "\n", sizeof(rawbuf) - strlen(rawbuf) - 1);
643 (!eof && rawbuf[0] == '#');
645 if (logfp && fp == stdin)
650 if (logfp && fp == stdin)
655 if (prompt && efp == stdout)
657 IGNORE(fputs(rawbuf, efp));
659 strcpy(INLINE + 1, rawbuf);
660 /* translate the chars to integers in the range 0-126 and store
661 * them in the common array "INLINE". Integer values are as follows:
662 * 0 = space [ASCII CODE 40 octal, 32 decimal]
663 * 1-2 = !" [ASCII 41-42 octal, 33-34 decimal]
664 * 3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
665 * 11-36 = upper-case letters
666 * 37-62 = lower-case letters
667 * 63 = percent (%) [ASCII 45 octal, 37 decimal]
668 * 64-73 = digits, 0 through 9
669 * Remaining characters can be translated any way that is convenient;
670 * The above mappings are required so that certain special
671 * characters are known to fit in 6 bits and/or can be easily spotted.
672 * Array elements beyond the end of the line should be filled with 0,
673 * and LNLENG should be set to the index of the last character.
675 * If the data file uses a character other than space (e.g., tab) to
676 * separate numbers, that character should also translate to 0.
678 * This procedure may use the map1,map2 arrays to maintain
679 * static data for he mapping. MAP2(1) is set to 0 when the
680 * program starts and is not changed thereafter unless the
681 * routines in this module choose to do so. */
683 for (long i = 1; i <= (long)sizeof(INLINE) && INLINE[i] != 0; i++) {
684 long val = INLINE[i];
685 INLINE[i] = ascii_to_advent[val];
694 void DATIME(long* d, long* t)
697 gettimeofday(&tv, NULL);
698 *d = (long) tv.tv_sec;
699 *t = (long) tv.tv_usec;
702 void bug(enum bugtype num, const char *error_string)
704 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);