10 #include "linenoise/linenoise.h"
13 void* xmalloc(size_t size)
15 void* ptr = malloc(size);
17 fprintf(stderr, "Out of memory!\n");
23 char* xstrdup(const char* s)
25 char* ptr = strdup(s);
27 fprintf(stderr, "Out of memory!\n");
33 void packed_to_token(long packed, char token[6])
35 // Unpack and map back to ASCII.
36 for (int i = 0; i < 5; ++i) {
37 char advent = (packed >> i * 6) & 63;
38 token[4 - i] = advent_to_ascii[(int) advent];
41 // Ensure the last character is \0.
44 // Replace trailing whitespace with \0.
45 for (int i = 4; i >= 0; --i) {
46 if (token[i] == ' ' || token[i] == '\t')
53 /* I/O routines (SPEAK, PSPEAK, RSPEAK, SETPRM, GETIN, YES) */
55 void speak(const char* msg)
57 // Do nothing if we got a null pointer.
61 // Do nothing if we got an empty string.
65 // Print a newline if the global game.blklin says to.
66 if (game.blklin == true)
69 // Create a copy of our string, so we can edit it.
70 char* copy = xstrdup(msg);
72 // Staging area for stringified parameters.
73 char parameters[5][100]; // FIXME: to be replaced with dynamic allocation
75 // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
76 int pi = 0; // parameter index
77 for (int i = 0; i < (int)strlen(msg); ++i) {
81 // 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.
82 if (msg[i + 1] == 'd') {
84 sprintf(parameters[pi], "%ld", PARMS[pi]);
87 // Unmodified string specifier.
88 if (msg[i + 1] == 's') {
89 packed_to_token(PARMS[pi], parameters[pi]);
92 // Singular/plural specifier.
93 if (msg[i + 1] == 'S') {
95 if (PARMS[pi - 1] > 1) { // look at the *previous* parameter (which by necessity must be numeric)
96 sprintf(parameters[pi], "%s", "s");
98 sprintf(parameters[pi], "%s", "");
102 // All-lowercase specifier.
103 if (msg[i + 1] == 'L') {
105 packed_to_token(PARMS[pi], parameters[pi]);
106 for (int j = 0; j < (int)strlen(parameters[pi]); ++j) {
107 parameters[pi][j] = tolower(parameters[pi][j]);
111 // First char uppercase, rest lowercase.
112 if (msg[i + 1] == 'C') {
114 packed_to_token(PARMS[pi], parameters[pi]);
115 for (int j = 0; j < (int)strlen(parameters[pi]); ++j) {
116 parameters[pi][j] = tolower(parameters[pi][j]);
118 parameters[pi][0] = toupper(parameters[pi][0]);
123 // Render the final string.
124 char rendered[2000]; // FIXME: to be replaced with dynamic allocation
125 sprintf(rendered, copy, parameters[1], parameters[2], parameters[3], parameters[4]); // FIXME: to be replaced with vsprintf()
127 // Print the message.
128 printf("%s\n", rendered);
133 void PSPEAK(vocab_t msg, int skip)
134 /* Find the skip+1st message from msg and print it. msg should be
135 * the index of the inventory message for object. (INVEN+N+1 message
136 * is game.prop=N message). */
139 speak(object_descriptions[msg].longs[skip]);
141 speak(object_descriptions[msg].inventory);
144 void RSPEAK(vocab_t i)
145 /* Print the i-th "random" message (section 6 of database). */
147 speak(arbitrary_messages[i]);
150 void SETPRM(long first, long p1, long p2)
151 /* Stores parameters into the PRMCOM parms array for use by speak. P1 and P2
152 * are stored into PARMS(first) and PARMS(first+1). */
154 if (first >= MAXPARMS)
155 BUG(TOO_MANY_PARAMETERS_GIVEN_TO_SETPRM);
158 PARMS[first + 1] = p2;
162 bool GETIN(FILE *input,
163 long *pword1, long *pword1x,
164 long *pword2, long *pword2x)
165 /* Get a command from the adventurer. Snarf out the first word, pad it with
166 * blanks, and return it in WORD1. Chars 6 thru 10 are returned in WORD1X, in
167 * case we need to print out the whole word in an error message. Any number of
168 * blanks may follow the word. If a second word appears, it is returned in
169 * WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
175 fputc('\n', stdout);;
178 *pword1 = GETTXT(true, true, true);
179 if (game.blklin && *pword1 < 0)
181 *pword1x = GETTXT(false, true, true);
183 junk = GETTXT(false, true, true);
186 *pword2 = GETTXT(true, true, true);
187 *pword2x = GETTXT(false, true, true);
189 junk = GETTXT(false, true, true);
192 if (GETTXT(true, true, true) <= 0)
198 void echo_input(FILE* destination, char* input_prompt, char* input)
200 size_t len = strlen(input_prompt) + strlen(input) + 1;
201 char* prompt_and_input = (char*) xmalloc(len);
202 strcpy(prompt_and_input, input_prompt);
203 strcat(prompt_and_input, input);
204 fprintf(destination, "%s\n", prompt_and_input);
205 free(prompt_and_input);
211 char input_prompt[] = "> ";
213 input_prompt[0] = '\0';
215 // Print a blank line if game.blklin tells us to.
216 if (game.blklin == true)
222 input = linenoise(input_prompt);
227 printf("%s", input_prompt);
228 IGNORE(getline(&input, &n, stdin));
231 if (input == NULL) // Got EOF; quit.
233 else if (input[0] == '#') // Ignore comments.
235 else // We have a 'normal' line; leave the loop.
239 // Strip trailing newlines from the input
240 input[strcspn(input, "\n")] = 0;
242 linenoiseHistoryAdd(input);
245 echo_input(stdout, input_prompt, input);
248 echo_input(logfp, input_prompt, input);
253 bool YES(vocab_t question, vocab_t yes_response, vocab_t no_response)
254 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
255 * if no, print Z and return false. */
265 char* firstword = (char*) xmalloc(strlen(reply));
266 sscanf(reply, "%s", firstword);
268 for (int i = 0; i < (int)strlen(firstword); ++i)
269 firstword[i] = tolower(firstword[i]);
271 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
272 int y = strncmp("y", firstword, sizeof("y") - 1);
273 int no = strncmp("no", firstword, sizeof("no") - 1);
274 int n = strncmp("n", firstword, sizeof("n") - 1);
278 if (yes == 0 || y == 0) {
279 RSPEAK(yes_response);
282 } else if (no == 0 || n == 0) {
287 RSPEAK(PLEASE_ANSWER);
289 linenoiseFree(reply);
293 /* Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT) */
295 long GETTXT(bool skip, bool onewrd, bool upper)
296 /* Take characters from an input line and pack them into 30-bit words.
297 * Skip says to skip leading blanks. ONEWRD says stop if we come to a
298 * blank. UPPER says to map all letters to uppercase. If we reach the
299 * end of the line, the word is filled up with blanks (which encode as 0's).
300 * If we're already at end of line when TEXT is called, we return -1. */
303 static long splitting = -1;
305 if (LNPOSN != splitting)
311 if ((!skip) || INLINE[LNPOSN] != 0)
317 for (int I = 1; I <= TOKLEN; I++) {
319 if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
321 char current = INLINE[LNPOSN];
322 if (current < ascii_to_advent['%']) {
324 if (upper && current >= ascii_to_advent['a'])
325 current = current - 26;
326 text = text + current;
330 if (splitting != LNPOSN) {
331 text = text + ascii_to_advent['%'];
336 text = text + current - ascii_to_advent['%'];
344 token_t MAKEWD(long letters)
345 /* Combine TOKLEN (currently 5) uppercase letters (represented by
346 * pairs of decimal digits in lettrs) to form a 30-bit value matching
347 * the one that GETTXT would return given those characters plus
348 * trailing blanks. Caution: lettrs will overflow 31 bits if
349 * 5-letter word starts with V-Z. As a kludgey workaround, you can
350 * increment a letter by 5 by adding 50 to the next pair of
353 long i = 1, word = 0;
355 for (long k = letters; k != 0; k = k / 100) {
356 word = word + i * (MOD(k, 50) + 10);
358 if (MOD(k, 100) > 50)word = word + i * 5;
360 i = 64L * 64L * 64L * 64L * 64L / i;
365 /* Data structure routines */
367 long VOCAB(long id, long init)
368 /* Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
369 * -1 if not found. If INIT is positive, this is an initialisation call setting
370 * up a keyword variable, and not finding it constitutes a bug. It also means
371 * that only KTAB values which taken over 1000 equal INIT may be considered.
372 * (Thus "STEPS", which is a motion verb as well as an object, may be located
373 * as an object.) And it also means the KTAB value is taken modulo 1000. */
377 for (long i = 1; i <= TABSIZ; i++) {
382 BUG(REQUIRED_VOCABULARY_WORD_NOT_FOUND);
384 if (init >= 0 && KTAB[i] / 1000 != init)
389 lexeme = MOD(lexeme, 1000);
393 BUG(RAN_OFF_END_OF_VOCABULARY_TABLE);
396 void JUGGLE(long object)
397 /* Juggle an object by picking it up and putting it down again, the purpose
398 * being to get the object to the front of the chain of things at its loc. */
402 i = game.place[object];
403 j = game.fixed[object];
405 MOVE(object + NOBJECTS, j);
408 void MOVE(long object, long where)
409 /* Place any object anywhere by picking it up and dropping it. May
410 * already be toting, in which case the carry is a no-op. Mustn't
411 * pick up objects which are not at any loc, since carry wants to
412 * remove objects from game.atloc chains. */
416 if (object > NOBJECTS)
417 from = game.fixed[object - NOBJECTS];
419 from = game.place[object];
420 if (from != NOWHERE && from != CARRIED && !SPECIAL(from))
425 long PUT(long object, long where, long pval)
426 /* PUT is the same as MOVE, except it returns a value used to set up the
427 * negated game.prop values for the repository objects. */
433 void CARRY(long object, long where)
434 /* Start toting an object, removing it from the list of things at its former
435 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
436 * (moving "fixed" second loc), don't change game.place or game.holdng. */
440 if (object <= NOBJECTS) {
441 if (game.place[object] == CARRIED)
443 game.place[object] = CARRIED;
446 if (game.atloc[where] == object) {
447 game.atloc[where] = game.link[object];
450 temp = game.atloc[where];
451 while (game.link[temp] != object) {
452 temp = game.link[temp];
454 game.link[temp] = game.link[object];
457 void DROP(long object, long where)
458 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
459 * game.holdng if the object was being toted. */
461 if (object > NOBJECTS)
462 game.fixed[object - NOBJECTS] = where;
464 if (game.place[object] == CARRIED)
466 game.place[object] = where;
470 game.link[object] = game.atloc[where];
471 game.atloc[where] = object;
474 long ATDWRF(long where)
475 /* Return the index of first dwarf at the given location, zero if no dwarf is
476 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
477 * the pirate (6th dwarf). */
485 for (long i = 1; i <= NDWARVES - 1; i++) {
486 if (game.dloc[i] == where)
488 if (game.dloc[i] != 0)
494 /* Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
495 * randrange, RNDVOC) */
497 long SETBIT(long bit)
498 /* Returns 2**bit for use in constructing bit-masks. */
503 bool TSTBIT(long mask, int bit)
504 /* Returns true if the specified bit is set in the mask. */
506 return (mask & (1 << bit)) != 0;
509 void set_seed(long seedval)
510 /* Set the LCG seed */
512 game.lcg_x = (unsigned long) seedval % game.lcg_m;
515 unsigned long get_next_lcg_value(void)
516 /* Return the LCG's current value, and then iterate it. */
518 unsigned long old_x = game.lcg_x;
519 game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
523 long randrange(long range)
524 /* Return a random integer from [0, range). */
526 return range * get_next_lcg_value() / game.lcg_m;
529 long RNDVOC(long second, long force)
530 /* Searches the vocabulary ATAB for a word whose second character is
531 * char, and changes that word such that each of the other four
532 * characters is a random letter. If force is non-zero, it is used
533 * as the new word. Returns the new word. */
538 for (int i = 1; i <= 5; i++) {
539 long j = 11 + randrange(26);
546 long div = 64L * 64L * 64L;
547 for (int i = 1; i <= TABSIZ; i++) {
548 if (MOD(ATAB[i] / div, 64L) == second) {
558 /* Machine dependent routines (MAPLIN, SAVEIO) */
560 bool MAPLIN(FILE *fp)
564 /* Read a line of input, from the specified input source.
565 * This logic is complicated partly because it has to serve
566 * several cases with different requirements and partly because
567 * of a quirk in linenoise().
569 * The quirk shows up when you paste a test log from the clipboard
570 * to the program's command prompt. While fgets (as expected)
571 * consumes it a line at a time, linenoise() returns the first
572 * line and discards the rest. Thus, there needs to be an
573 * editline (-s) option to fall back to fgets while still
574 * prompting. Note that linenoise does behave properly when
575 * fed redirected stdin.
577 * The logging is a bit of a mess because there are two distinct cases
578 * in which you want to echo commands. One is when shipping them to
579 * a log under the -l option, in which case you want to suppress
580 * prompt generation (so test logs are unadorned command sequences).
581 * On the other hand, if you redirected stdin and are feeding the program
582 * a logfile, you *do* want prompt generation - it makes checkfiles
583 * easier to read when the commands are marked by a preceding prompt.
589 IGNORE(fgets(rawbuf, sizeof(rawbuf) - 1, fp));
592 char *cp = linenoise("> ");
595 strncpy(rawbuf, cp, sizeof(rawbuf) - 1);
596 linenoiseHistoryAdd(rawbuf);
597 strncat(rawbuf, "\n", sizeof(rawbuf) - strlen(rawbuf) - 1);
602 (!eof && rawbuf[0] == '#');
604 if (logfp && fp == stdin)
609 if (logfp && fp == stdin)
614 if (prompt && efp == stdout)
616 IGNORE(fputs(rawbuf, efp));
618 strcpy(INLINE + 1, rawbuf);
619 /* translate the chars to integers in the range 0-126 and store
620 * them in the common array "INLINE". Integer values are as follows:
621 * 0 = space [ASCII CODE 40 octal, 32 decimal]
622 * 1-2 = !" [ASCII 41-42 octal, 33-34 decimal]
623 * 3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
624 * 11-36 = upper-case letters
625 * 37-62 = lower-case letters
626 * 63 = percent (%) [ASCII 45 octal, 37 decimal]
627 * 64-73 = digits, 0 through 9
628 * Remaining characters can be translated any way that is convenient;
629 * The above mappings are required so that certain special
630 * characters are known to fit in 6 bits and/or can be easily spotted.
631 * Array elements beyond the end of the line should be filled with 0,
632 * and LNLENG should be set to the index of the last character.
634 * If the data file uses a character other than space (e.g., tab) to
635 * separate numbers, that character should also translate to 0.
637 * This procedure may use the map1,map2 arrays to maintain static data for
638 * the mapping. MAP2(1) is set to 0 when the program starts
639 * and is not changed thereafter unless the routines on this page choose
642 for (long i = 1; i <= (long)sizeof(INLINE) && INLINE[i] != 0; i++) {
643 long val = INLINE[i];
644 INLINE[i] = ascii_to_advent[val];
653 void DATIME(long* d, long* t)
656 gettimeofday(&tv, NULL);
657 *d = (long) tv.tv_sec;
658 *t = (long) tv.tv_usec;
661 void bug(enum bugtype num, const char *error_string)
663 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);