8 #include <editline/readline.h>
13 static void* xmalloc(size_t size)
15 void* ptr = malloc(size);
18 // exclude from coverage analysis because we can't simulate an out of memory error in testing
19 fprintf(stderr, "Out of memory!\n");
26 void packed_to_token(long packed, char token[TOKLEN + 1])
28 // The advent->ascii mapping.
29 const char advent_to_ascii[] = {
30 ' ', '!', '"', '#', '$', '%', '&', '\'',
31 '(', ')', '*', '+', ',', '-', '.', '/',
32 '0', '1', '2', '3', '4', '5', '6', '7',
33 '8', '9', ':', ';', '<', '=', '>', '?',
34 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
35 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
36 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
37 'X', 'Y', 'Z', '\0', '\0', '\0', '\0', '\0',
40 // Unpack and map back to ASCII.
41 for (int i = 0; i < 5; ++i) {
42 char advent = (packed >> i * 6) & 63;
43 token[i] = advent_to_ascii[(int) advent];
46 // Ensure the last character is \0.
49 // Replace trailing whitespace with \0.
50 for (int i = 4; i >= 0; --i) {
51 if (token[i] == ' ' ||
59 long token_to_packed(const char token[])
61 const char ascii_to_advent[] = {
62 63, 63, 63, 63, 63, 63, 63, 63,
63 63, 63, 63, 63, 63, 63, 63, 63,
64 63, 63, 63, 63, 63, 63, 63, 63,
65 63, 63, 63, 63, 63, 63, 63, 63,
67 0, 1, 2, 3, 4, 5, 6, 7,
68 8, 9, 10, 11, 12, 13, 14, 15,
69 16, 17, 18, 19, 20, 21, 22, 23,
70 24, 25, 26, 27, 28, 29, 30, 31,
71 32, 33, 34, 35, 36, 37, 38, 39,
72 40, 41, 42, 43, 44, 45, 46, 47,
73 48, 49, 50, 51, 52, 53, 54, 55,
74 56, 57, 58, 59, 60, 61, 62, 63,
76 63, 63, 63, 63, 63, 63, 63, 63,
77 63, 63, 63, 63, 63, 63, 63, 63,
78 63, 63, 63, 63, 63, 63, 63, 63,
79 63, 63, 63, 63, 63, 63, 63, 63,
82 size_t t_len = strlen(token);
86 for (size_t i = 0; i < t_len; ++i) {
87 char mapped = ascii_to_advent[(int) toupper(token[i])];
88 packed |= (mapped << (6 * i));
93 void tokenize(char* raw, struct command_t *cmd)
95 memset(cmd, '\0', sizeof(struct command_t));
97 /* Bound prefix on the %s would be needed to prevent buffer
98 * overflow. but we shortstop this more simply by making each
99 * raw-input buffer as long as the enrire inout buffer. */
100 sscanf(raw, "%s%s", cmd->raw1, cmd->raw2);
102 // pack the substrings
103 cmd->wd1 = token_to_packed(cmd->raw1);
104 cmd->wd2 = token_to_packed(cmd->raw2);
106 /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
107 * effect on raw tokens of packing them into sixbit characters, 5
108 * to a 32-bit word. This is something the FORTRAN version did
109 * becuse archaic FORTRAN had no string types. Don Wood's
110 * mechanical translation of 2.5 to C retained the packing and
111 * thus this misfeature.
113 * It's philosophically questionable whether this is the right
114 * thing to do even in oldstyle mode. On one hand, the text
115 * mangling was not authorial intent, but a result of limitations
116 * in their tools. On the other, not simulating this misbehavior
117 * goes against the goal of making oldstyle as accurate as
118 * possible an emulation of the original UI.
120 if (settings.oldstyle) {
121 cmd->raw1[TOKLEN+TOKLEN] = cmd->raw1[TOKLEN+TOKLEN] = '\0';
122 for (int i = 0; i < strlen(cmd->raw1); i++)
123 cmd->raw1[i] = toupper(cmd->raw1[i]);
124 for (int i = 0; i < strlen(cmd->raw2); i++)
125 cmd->raw2[i] = toupper(cmd->raw2[i]);
129 /* Hide the fact that wods are corrently packed longs */
131 bool wordeq(token_t a, token_t b)
136 bool wordempty(token_t a)
141 void wordclear(token_t *v)
146 /* I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
148 void vspeak(const char* msg, bool blank, va_list ap)
150 // Do nothing if we got a null pointer.
154 // Do nothing if we got an empty string.
155 if (strlen(msg) == 0)
161 int msglen = strlen(msg);
164 ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
165 char* rendered = xmalloc(size);
166 char* renderp = rendered;
168 // Handle format specifiers (including the custom %C, %L, %S) by
169 // adjusting the parameter accordingly, and replacing the
170 // specifier with %s.
171 long previous_arg = 0;
172 for (int i = 0; i < msglen; i++) {
177 long arg = va_arg(ap, long);
179 arg = 0; // LCOV_EXCL_LINE - don't think we can get here.
181 // Integer specifier. In order to accommodate the fact
182 // that PARMS can have both legitimate integers *and*
183 // packed tokens, stringify everything. Future work may
184 // eliminate the need for this.
186 int ret = snprintf(renderp, size, "%ld", arg);
193 // Unmodified string specifier.
195 packed_to_token(arg, renderp); /* unpack directly to destination */
196 size_t len = strlen(renderp);
201 // Singular/plural specifier.
203 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
209 /* Version specifier */
211 strcpy(renderp, VERSION);
212 size_t len = strlen(VERSION);
222 // Print the message.
223 printf("%s\n", rendered);
228 void speak(const char* msg, ...)
232 vspeak(msg, true, ap);
236 void sspeak(const long msg, ...)
241 vprintf(arbitrary_messages[msg], ap);
246 void pspeak(vocab_t msg, enum speaktype mode, int skip, bool blank, ...)
247 /* Find the skip+1st message from msg and print it. Modes are:
248 * feel = for inventory, what you can touch
249 * look = the long description for the state the object is in
250 * listen = the sound for the state the object is in
251 * study = text on the object. */
257 vspeak(objects[msg].inventory, blank, ap);
260 vspeak(objects[msg].descriptions[skip], blank, ap);
263 vspeak(objects[msg].sounds[skip], blank, ap);
266 vspeak(objects[msg].texts[skip], blank, ap);
269 vspeak(objects[msg].changes[skip], blank, ap);
275 void rspeak(vocab_t i, ...)
276 /* Print the i-th "random" message (section 6 of database). */
280 vspeak(arbitrary_messages[i], true, ap);
284 void echo_input(FILE* destination, const char* input_prompt, const char* input)
286 size_t len = strlen(input_prompt) + strlen(input) + 1;
287 char* prompt_and_input = (char*) xmalloc(len);
288 strcpy(prompt_and_input, input_prompt);
289 strcat(prompt_and_input, input);
290 fprintf(destination, "%s\n", prompt_and_input);
291 free(prompt_and_input);
294 int word_count(char* str)
296 char delims[] = " \t";
300 for (char *s = str; *s; s++)
302 if (strchr(delims, *s) == 0) {
307 if (strchr(delims, *s) != 0) {
318 char input_prompt[] = "> ";
319 if (!settings.prompt)
320 input_prompt[0] = '\0';
322 // Print a blank line
327 input = readline(input_prompt);
329 if (input == NULL) // Got EOF; return with it.
331 else if (input[0] == '#') { // Ignore comments.
334 } else // We have a 'normal' line; leave the loop.
338 // Strip trailing newlines from the input
339 input[strcspn(input, "\n")] = 0;
344 echo_input(stdout, input_prompt, input);
347 echo_input(settings.logfp, "", input);
361 // Should be unreachable. Reply should never be NULL
367 char* firstword = (char*) xmalloc(strlen(reply) + 1);
368 sscanf(reply, "%s", firstword);
372 for (int i = 0; i < (int)strlen(firstword); ++i)
373 firstword[i] = tolower(firstword[i]);
375 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
376 int y = strncmp("y", firstword, sizeof("y") - 1);
377 int no = strncmp("no", firstword, sizeof("no") - 1);
378 int n = strncmp("n", firstword, sizeof("n") - 1);
386 } else if (no == 0 ||
391 rspeak(PLEASE_ANSWER);
397 bool yes(const char* question, const char* yes_response, const char* no_response)
398 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
399 * if no, print Z and return false. */
410 // Should be unreachable. Reply should never be NULL
416 char* firstword = (char*) xmalloc(strlen(reply) + 1);
417 sscanf(reply, "%s", firstword);
421 for (int i = 0; i < (int)strlen(firstword); ++i)
422 firstword[i] = tolower(firstword[i]);
424 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
425 int y = strncmp("y", firstword, sizeof("y") - 1);
426 int no = strncmp("no", firstword, sizeof("no") - 1);
427 int n = strncmp("n", firstword, sizeof("n") - 1);
436 } else if (no == 0 ||
442 rspeak(PLEASE_ANSWER);
449 /* Data structure routines */
451 int get_motion_vocab_id(const char* word)
452 // Return the first motion number that has 'word' as one of its words.
454 for (int i = 0; i < NMOTIONS; ++i) {
455 for (int j = 0; j < motions[i].words.n; ++j) {
456 if (strcasecmp(word, motions[i].words.strs[j]) == 0 && (strlen(word) > 1 ||
457 strchr(ignore, word[0]) == NULL ||
462 // If execution reaches here, we didn't find the word.
463 return (WORD_NOT_FOUND);
466 int get_object_vocab_id(const char* word)
467 // Return the first object number that has 'word' as one of its words.
469 for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
470 for (int j = 0; j < objects[i].words.n; ++j) {
471 if (strcasecmp(word, objects[i].words.strs[j]) == 0)
475 // If execution reaches here, we didn't find the word.
476 return (WORD_NOT_FOUND);
479 int get_action_vocab_id(const char* word)
480 // Return the first motion number that has 'word' as one of its words.
482 for (int i = 0; i < NACTIONS; ++i) {
483 for (int j = 0; j < actions[i].words.n; ++j) {
484 if (strcasecmp(word, actions[i].words.strs[j]) == 0 && (strlen(word) > 1 ||
485 strchr(ignore, word[0]) == NULL ||
490 // If execution reaches here, we didn't find the word.
491 return (WORD_NOT_FOUND);
494 int get_special_vocab_id(const char* word)
495 // Return the first special number that has 'word' as one of its words.
497 for (int i = 0; i < NSPECIALS; ++i) {
498 for (int j = 0; j < specials[i].words.n; ++j) {
499 if (strcasecmp(word, specials[i].words.strs[j]) == 0)
503 // If execution reaches here, we didn't find the word.
504 return (WORD_NOT_FOUND);
507 long get_vocab_id(const char* word)
508 // Search the vocab categories in order for the supplied word.
510 /* Check for an empty string */
511 if (strncmp(word, "", sizeof("")) == 0)
516 /* FIXME: Magic numbers related to vocabulary */
517 ref_num = get_motion_vocab_id(word);
518 if (ref_num != WORD_NOT_FOUND)
519 return MOTION_WORD(ref_num);
521 ref_num = get_object_vocab_id(word);
522 if (ref_num != WORD_NOT_FOUND)
523 return OBJECT_WORD(ref_num);
525 ref_num = get_action_vocab_id(word);
526 if (ref_num != WORD_NOT_FOUND)
527 return ACTION_WORD(ref_num);
529 ref_num = get_special_vocab_id(word);
530 if (ref_num != WORD_NOT_FOUND)
531 return SPECIAL_WORD(ref_num);
533 // Check for the reservoir magic word.
534 if (strcasecmp(word, game.zzword) == 0)
535 return ACTION_WORD(PART);
537 return (WORD_NOT_FOUND);
540 void juggle(long object)
541 /* Juggle an object by picking it up and putting it down again, the purpose
542 * being to get the object to the front of the chain of things at its loc. */
546 i = game.place[object];
547 j = game.fixed[object];
549 move(object + NOBJECTS, j);
552 void move(long object, long where)
553 /* Place any object anywhere by picking it up and dropping it. May
554 * already be toting, in which case the carry is a no-op. Mustn't
555 * pick up objects which are not at any loc, since carry wants to
556 * remove objects from game.atloc chains. */
560 if (object > NOBJECTS)
561 from = game.fixed[object - NOBJECTS];
563 from = game.place[object];
564 if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
569 long put(long object, long where, long pval)
570 /* PUT is the same as MOVE, except it returns a value used to set up the
571 * negated game.prop values for the repository objects. */
577 void carry(long object, long where)
578 /* Start toting an object, removing it from the list of things at its former
579 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
580 * (moving "fixed" second loc), don't change game.place or game.holdng. */
584 if (object <= NOBJECTS) {
585 if (game.place[object] == CARRIED)
587 game.place[object] = CARRIED;
590 if (game.atloc[where] == object) {
591 game.atloc[where] = game.link[object];
594 temp = game.atloc[where];
595 while (game.link[temp] != object) {
596 temp = game.link[temp];
598 game.link[temp] = game.link[object];
601 void drop(long object, long where)
602 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
603 * game.holdng if the object was being toted. */
605 if (object > NOBJECTS)
606 game.fixed[object - NOBJECTS] = where;
608 if (game.place[object] == CARRIED)
610 game.place[object] = where;
614 game.link[object] = game.atloc[where];
615 game.atloc[where] = object;
618 long atdwrf(long where)
619 /* Return the index of first dwarf at the given location, zero if no dwarf is
620 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
621 * the pirate (6th dwarf). */
629 for (long i = 1; i <= NDWARVES - 1; i++) {
630 if (game.dloc[i] == where)
632 if (game.dloc[i] != 0)
638 /* Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
641 long setbit(long bit)
642 /* Returns 2**bit for use in constructing bit-masks. */
647 bool tstbit(long mask, int bit)
648 /* Returns true if the specified bit is set in the mask. */
650 return (mask & (1 << bit)) != 0;
653 void set_seed(long seedval)
654 /* Set the LCG seed */
656 game.lcg_x = (unsigned long) seedval % game.lcg_m;
658 // once seed is set, we need to generate the Z`ZZZ word
659 make_zzword(game.zzword);
662 unsigned long get_next_lcg_value(void)
663 /* Return the LCG's current value, and then iterate it. */
665 unsigned long old_x = game.lcg_x;
666 game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
670 long randrange(long range)
671 /* Return a random integer from [0, range). */
673 return range * get_next_lcg_value() / game.lcg_m;
676 void make_zzword(char zzword[TOKLEN + 1])
678 for (int i = 0; i < 5; ++i) {
679 zzword[i] = 'A' + randrange(26);
681 zzword[1] = '\''; // force second char to apostrophe
686 void bug(enum bugtype num, const char *error_string)
688 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);