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);
28 fprintf(stderr, "Out of memory!\n");
34 void packed_to_token(long packed, char token[6])
36 // Unpack and map back to ASCII.
37 for (int i = 0; i < 5; ++i) {
38 char advent = (packed >> i * 6) & 63;
39 token[4 - i] = advent_to_ascii[(int) advent];
42 // Ensure the last character is \0.
45 // Replace trailing whitespace with \0.
46 for (int i = 4; i >= 0; --i) {
47 if (token[i] == ' ' || token[i] == '\t')
54 /* I/O routines (SPEAK, PSPEAK, RSPEAK, SETPRM, GETIN, YES) */
56 void speak(const char* msg)
58 // Do nothing if we got a null pointer.
62 // Do nothing if we got an empty string.
66 // Print a newline if the global game.blklin says to.
67 if (game.blklin == true)
70 // Create a copy of our string, so we can edit it.
71 char* copy = xstrdup(msg);
73 // Staging area for stringified parameters.
74 char parameters[5][100]; // FIXME: to be replaced with dynamic allocation
76 // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
77 int pi = 0; // parameter index
78 for (int i = 0; i < (int)strlen(msg); ++i) {
82 // 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.
83 if (msg[i + 1] == 'd') {
85 sprintf(parameters[pi], "%ld", PARMS[pi]);
88 // Unmodified string specifier.
89 if (msg[i + 1] == 's') {
90 packed_to_token(PARMS[pi], parameters[pi]);
93 // Singular/plural specifier.
94 if (msg[i + 1] == 'S') {
96 if (PARMS[pi - 1] > 1) { // look at the *previous* parameter (which by necessity must be numeric)
97 sprintf(parameters[pi], "%s", "s");
99 sprintf(parameters[pi], "%s", "");
103 // All-lowercase specifier.
104 if (msg[i + 1] == 'L') {
106 packed_to_token(PARMS[pi], parameters[pi]);
107 for (int j = 0; j < (int)strlen(parameters[pi]); ++j) {
108 parameters[pi][j] = tolower(parameters[pi][j]);
112 // First char uppercase, rest lowercase.
113 if (msg[i + 1] == 'C') {
115 packed_to_token(PARMS[pi], parameters[pi]);
116 for (int j = 0; j < (int)strlen(parameters[pi]); ++j) {
117 parameters[pi][j] = tolower(parameters[pi][j]);
119 parameters[pi][0] = toupper(parameters[pi][0]);
124 // Render the final string.
125 char rendered[2000]; // FIXME: to be replaced with dynamic allocation
126 sprintf(rendered, copy, parameters[1], parameters[2], parameters[3], parameters[4]); // FIXME: to be replaced with vsprintf()
128 // Print the message.
129 printf("%s\n", rendered);
134 void PSPEAK(vocab_t msg, int skip)
135 /* Find the skip+1st message from msg and print it. msg should be
136 * the index of the inventory message for object. (INVEN+N+1 message
137 * is game.prop=N message). */
140 speak(object_descriptions[msg].longs[skip]);
142 speak(object_descriptions[msg].inventory);
145 void RSPEAK(vocab_t i)
146 /* Print the i-th "random" message (section 6 of database). */
148 speak(arbitrary_messages[i]);
151 void SETPRM(long first, long p1, long p2)
152 /* Stores parameters into the PRMCOM parms array for use by speak. P1 and P2
153 * are stored into PARMS(first) and PARMS(first+1). */
155 if (first >= MAXPARMS)
156 BUG(TOO_MANY_PARAMETERS_GIVEN_TO_SETPRM);
159 PARMS[first + 1] = p2;
163 bool GETIN(FILE *input,
164 long *pword1, long *pword1x,
165 long *pword2, long *pword2x)
166 /* Get a command from the adventurer. Snarf out the first word, pad it with
167 * blanks, and return it in WORD1. Chars 6 thru 10 are returned in WORD1X, in
168 * case we need to print out the whole word in an error message. Any number of
169 * blanks may follow the word. If a second word appears, it is returned in
170 * WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
176 fputc('\n', stdout);;
179 *pword1 = GETTXT(true, true, true);
180 if (game.blklin && *pword1 < 0)
182 *pword1x = GETTXT(false, true, true);
184 junk = GETTXT(false, true, true);
187 *pword2 = GETTXT(true, true, true);
188 *pword2x = GETTXT(false, true, true);
190 junk = GETTXT(false, true, true);
193 if (GETTXT(true, true, true) <= 0)
199 void echo_input(FILE* destination, char* input_prompt, char* input)
201 size_t len = strlen(input_prompt) + strlen(input) + 1;
202 char* prompt_and_input = (char*) xmalloc(len);
203 strcpy(prompt_and_input, input_prompt);
204 strcat(prompt_and_input, input);
205 fprintf(destination, "%s\n", prompt_and_input);
206 free(prompt_and_input);
212 char input_prompt[] = "> ";
214 input_prompt[0] = '\0';
216 // Print a blank line if game.blklin tells us to.
217 if (game.blklin == true)
224 input = linenoise(input_prompt);
230 printf("%s", input_prompt);
231 IGNORE(getline(&input, &n, stdin));
234 if (input == NULL) // Got EOF; quit.
236 else if (input[0] == '#') // Ignore comments.
238 else // We have a 'normal' line; leave the loop.
242 // Strip trailing newlines from the input
243 input[strcspn(input, "\n")] = 0;
245 linenoiseHistoryAdd(input);
248 echo_input(stdout, input_prompt, input);
251 echo_input(logfp, input_prompt, input);
256 bool YES(vocab_t question, vocab_t yes_response, vocab_t no_response)
257 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
258 * if no, print Z and return false. */
268 char* firstword = (char*) xmalloc(strlen(reply));
269 sscanf(reply, "%s", firstword);
271 for (int i = 0; i < (int)strlen(firstword); ++i)
272 firstword[i] = tolower(firstword[i]);
274 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
275 int y = strncmp("y", firstword, sizeof("y") - 1);
276 int no = strncmp("no", firstword, sizeof("no") - 1);
277 int n = strncmp("n", firstword, sizeof("n") - 1);
281 if (yes == 0 || y == 0) {
282 RSPEAK(yes_response);
286 else if (no == 0 || n == 0) {
292 RSPEAK(PLEASE_ANSWER);
294 linenoiseFree(reply);
298 /* Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT) */
300 long GETTXT(bool skip, bool onewrd, bool upper)
301 /* Take characters from an input line and pack them into 30-bit words.
302 * Skip says to skip leading blanks. ONEWRD says stop if we come to a
303 * blank. UPPER says to map all letters to uppercase. If we reach the
304 * end of the line, the word is filled up with blanks (which encode as 0's).
305 * If we're already at end of line when TEXT is called, we return -1. */
308 static long splitting = -1;
310 if (LNPOSN != splitting)
316 if ((!skip) || INLINE[LNPOSN] != 0)
322 for (int I = 1; I <= TOKLEN; I++) {
324 if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
326 char current = INLINE[LNPOSN];
327 if (current < ascii_to_advent['%']) {
329 if (upper && current >= ascii_to_advent['a'])
330 current = current - 26;
331 text = text + current;
335 if (splitting != LNPOSN) {
336 text = text + ascii_to_advent['%'];
341 text = text + current - ascii_to_advent['%'];
349 token_t MAKEWD(long letters)
350 /* Combine TOKLEN (currently 5) uppercase letters (represented by
351 * pairs of decimal digits in lettrs) to form a 30-bit value matching
352 * the one that GETTXT would return given those characters plus
353 * trailing blanks. Caution: lettrs will overflow 31 bits if
354 * 5-letter word starts with V-Z. As a kludgey workaround, you can
355 * increment a letter by 5 by adding 50 to the next pair of
358 long i = 1, word = 0;
360 for (long k = letters; k != 0; k = k / 100) {
361 word = word + i * (MOD(k, 50) + 10);
363 if (MOD(k, 100) > 50)word = word + i * 5;
365 i = 64L * 64L * 64L * 64L * 64L / i;
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 (long i = 1; i <= TABSIZ; i++) {
387 BUG(REQUIRED_VOCABULARY_WORD_NOT_FOUND);
389 if (init >= 0 && KTAB[i] / 1000 != init)
394 lexeme = MOD(lexeme, 1000);
398 BUG(RAN_OFF_END_OF_VOCABULARY_TABLE);
401 void JUGGLE(long object)
402 /* Juggle an object by picking it up and putting it down again, the purpose
403 * being to get the object to the front of the chain of things at its loc. */
407 i = game.place[object];
408 j = game.fixed[object];
410 MOVE(object + NOBJECTS, j);
413 void MOVE(long object, long where)
414 /* Place any object anywhere by picking it up and dropping it. May
415 * already be toting, in which case the carry is a no-op. Mustn't
416 * pick up objects which are not at any loc, since carry wants to
417 * remove objects from game.atloc chains. */
421 if (object > NOBJECTS)
422 from = game.fixed[object - NOBJECTS];
424 from = game.place[object];
425 if (from != NOWHERE && from != CARRIED && !SPECIAL(from))
430 long PUT(long object, long where, long pval)
431 /* PUT is the same as MOVE, except it returns a value used to set up the
432 * negated game.prop values for the repository objects. */
438 void CARRY(long object, long where)
439 /* Start toting an object, removing it from the list of things at its former
440 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
441 * (moving "fixed" second loc), don't change game.place or game.holdng. */
445 if (object <= NOBJECTS) {
446 if (game.place[object] == CARRIED)
448 game.place[object] = CARRIED;
451 if (game.atloc[where] == object) {
452 game.atloc[where] = game.link[object];
455 temp = game.atloc[where];
456 while (game.link[temp] != object) {
457 temp = game.link[temp];
459 game.link[temp] = game.link[object];
462 void DROP(long object, long where)
463 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
464 * game.holdng if the object was being toted. */
466 if (object > NOBJECTS)
467 game.fixed[object - NOBJECTS] = where;
469 if (game.place[object] == CARRIED)
471 game.place[object] = where;
475 game.link[object] = game.atloc[where];
476 game.atloc[where] = object;
479 long ATDWRF(long where)
480 /* Return the index of first dwarf at the given location, zero if no dwarf is
481 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
482 * the pirate (6th dwarf). */
490 for (long i = 1; i <= NDWARVES - 1; i++) {
491 if (game.dloc[i] == where)
493 if (game.dloc[i] != 0)
499 /* Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
500 * randrange, RNDVOC) */
502 long SETBIT(long bit)
503 /* Returns 2**bit for use in constructing bit-masks. */
508 bool TSTBIT(long mask, int bit)
509 /* Returns true if the specified bit is set in the mask. */
511 return (mask & (1 << bit)) != 0;
514 void set_seed(long seedval)
515 /* Set the LCG seed */
517 game.lcg_x = (unsigned long) seedval % game.lcg_m;
520 unsigned long get_next_lcg_value(void)
521 /* Return the LCG's current value, and then iterate it. */
523 unsigned long old_x = game.lcg_x;
524 game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
528 long randrange(long range)
529 /* Return a random integer from [0, range). */
531 return range * get_next_lcg_value() / game.lcg_m;
534 long RNDVOC(long second, long force)
535 /* Searches the vocabulary ATAB for a word whose second character is
536 * char, and changes that word such that each of the other four
537 * characters is a random letter. If force is non-zero, it is used
538 * as the new word. Returns the new word. */
543 for (int i = 1; i <= 5; i++) {
544 long j = 11 + randrange(26);
551 long div = 64L * 64L * 64L;
552 for (int i = 1; i <= TABSIZ; i++) {
553 if (MOD(ATAB[i] / div, 64L) == second) {
563 /* Machine dependent routines (MAPLIN, SAVEIO) */
565 bool MAPLIN(FILE *fp)
569 /* Read a line of input, from the specified input source.
570 * This logic is complicated partly because it has to serve
571 * several cases with different requirements and partly because
572 * of a quirk in linenoise().
574 * The quirk shows up when you paste a test log from the clipboard
575 * to the program's command prompt. While fgets (as expected)
576 * consumes it a line at a time, linenoise() returns the first
577 * line and discards the rest. Thus, there needs to be an
578 * editline (-s) option to fall back to fgets while still
579 * prompting. Note that linenoise does behave properly when
580 * fed redirected stdin.
582 * The logging is a bit of a mess because there are two distinct cases
583 * in which you want to echo commands. One is when shipping them to
584 * a log under the -l option, in which case you want to suppress
585 * prompt generation (so test logs are unadorned command sequences).
586 * On the other hand, if you redirected stdin and are feeding the program
587 * a logfile, you *do* want prompt generation - it makes checkfiles
588 * easier to read when the commands are marked by a preceding prompt.
594 IGNORE(fgets(rawbuf, sizeof(rawbuf) - 1, fp));
597 char *cp = linenoise("> ");
600 strncpy(rawbuf, cp, sizeof(rawbuf) - 1);
601 linenoiseHistoryAdd(rawbuf);
602 strncat(rawbuf, "\n", sizeof(rawbuf) - strlen(rawbuf) - 1);
607 (!eof && rawbuf[0] == '#');
609 if (logfp && fp == stdin)
614 if (logfp && fp == stdin)
619 if (prompt && efp == stdout)
621 IGNORE(fputs(rawbuf, efp));
623 strcpy(INLINE + 1, rawbuf);
624 /* translate the chars to integers in the range 0-126 and store
625 * them in the common array "INLINE". Integer values are as follows:
626 * 0 = space [ASCII CODE 40 octal, 32 decimal]
627 * 1-2 = !" [ASCII 41-42 octal, 33-34 decimal]
628 * 3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
629 * 11-36 = upper-case letters
630 * 37-62 = lower-case letters
631 * 63 = percent (%) [ASCII 45 octal, 37 decimal]
632 * 64-73 = digits, 0 through 9
633 * Remaining characters can be translated any way that is convenient;
634 * The above mappings are required so that certain special
635 * characters are known to fit in 6 bits and/or can be easily spotted.
636 * Array elements beyond the end of the line should be filled with 0,
637 * and LNLENG should be set to the index of the last character.
639 * If the data file uses a character other than space (e.g., tab) to
640 * separate numbers, that character should also translate to 0.
642 * This procedure may use the map1,map2 arrays to maintain static data for
643 * the mapping. MAP2(1) is set to 0 when the program starts
644 * and is not changed thereafter unless the routines on this page choose
647 for (long i = 1; i <= (long)sizeof(INLINE) && INLINE[i] != 0; i++) {
648 long val = INLINE[i];
649 INLINE[i] = ascii_to_advent[val];
658 void DATIME(long* d, long* t)
661 gettimeofday(&tv, NULL);
662 *d = (long) tv.tv_sec;
663 *t = (long) tv.tv_usec;