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 /* FIXME: put a bound prefix on the %s to prevent buffer overflow */
98 sscanf(raw, "%s%s", cmd->raw1, cmd->raw2);
100 // pack the substrings
101 cmd->wd1 = token_to_packed(cmd->raw1);
102 cmd->wd2 = token_to_packed(cmd->raw2);
105 /* Hide the fact that wods are corrently packed longs */
107 bool wordeq(token_t a, token_t b)
112 bool wordempty(token_t a)
117 void wordclear(token_t *v)
122 /* I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
124 void vspeak(const char* msg, bool blank, va_list ap)
126 // Do nothing if we got a null pointer.
130 // Do nothing if we got an empty string.
131 if (strlen(msg) == 0)
137 int msglen = strlen(msg);
140 ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
141 char* rendered = xmalloc(size);
142 char* renderp = rendered;
144 // Handle format specifiers (including the custom %C, %L, %S) by
145 // adjusting the parameter accordingly, and replacing the
146 // specifier with %s.
147 long previous_arg = 0;
148 for (int i = 0; i < msglen; i++) {
153 long arg = va_arg(ap, long);
155 arg = 0; // LCOV_EXCL_LINE - don't think we can get here.
157 // Integer specifier. In order to accommodate the fact
158 // that PARMS can have both legitimate integers *and*
159 // packed tokens, stringify everything. Future work may
160 // eliminate the need for this.
162 int ret = snprintf(renderp, size, "%ld", arg);
169 // Unmodified string specifier.
171 packed_to_token(arg, renderp); /* unpack directly to destination */
172 size_t len = strlen(renderp);
177 // Singular/plural specifier.
179 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
185 /* Version specifier */
187 strcpy(renderp, VERSION);
188 size_t len = strlen(VERSION);
198 // Print the message.
199 printf("%s\n", rendered);
204 void speak(const char* msg, ...)
208 vspeak(msg, true, ap);
212 void sspeak(const long msg, ...)
217 vprintf(arbitrary_messages[msg], ap);
222 void pspeak(vocab_t msg, enum speaktype mode, int skip, bool blank, ...)
223 /* Find the skip+1st message from msg and print it. Modes are:
224 * feel = for inventory, what you can touch
225 * look = the long description for the state the object is in
226 * listen = the sound for the state the object is in
227 * study = text on the object. */
233 vspeak(objects[msg].inventory, blank, ap);
236 vspeak(objects[msg].descriptions[skip], blank, ap);
239 vspeak(objects[msg].sounds[skip], blank, ap);
242 vspeak(objects[msg].texts[skip], blank, ap);
245 vspeak(objects[msg].changes[skip], blank, ap);
251 void rspeak(vocab_t i, ...)
252 /* Print the i-th "random" message (section 6 of database). */
256 vspeak(arbitrary_messages[i], true, ap);
260 void echo_input(FILE* destination, const char* input_prompt, const char* input)
262 size_t len = strlen(input_prompt) + strlen(input) + 1;
263 char* prompt_and_input = (char*) xmalloc(len);
264 strcpy(prompt_and_input, input_prompt);
265 strcat(prompt_and_input, input);
266 fprintf(destination, "%s\n", prompt_and_input);
267 free(prompt_and_input);
270 int word_count(char* str)
272 char delims[] = " \t";
276 for (char *s = str; *s; s++)
278 if (strchr(delims, *s) == 0) {
283 if (strchr(delims, *s) != 0) {
294 char input_prompt[] = "> ";
295 if (!settings.prompt)
296 input_prompt[0] = '\0';
298 // Print a blank line
303 input = readline(input_prompt);
305 if (input == NULL) // Got EOF; return with it.
307 else if (input[0] == '#') { // Ignore comments.
310 } else // We have a 'normal' line; leave the loop.
314 // Strip trailing newlines from the input
315 input[strcspn(input, "\n")] = 0;
320 echo_input(stdout, input_prompt, input);
323 echo_input(settings.logfp, "", input);
337 // Should be unreachable. Reply should never be NULL
343 char* firstword = (char*) xmalloc(strlen(reply) + 1);
344 sscanf(reply, "%s", firstword);
348 for (int i = 0; i < (int)strlen(firstword); ++i)
349 firstword[i] = tolower(firstword[i]);
351 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
352 int y = strncmp("y", firstword, sizeof("y") - 1);
353 int no = strncmp("no", firstword, sizeof("no") - 1);
354 int n = strncmp("n", firstword, sizeof("n") - 1);
362 } else if (no == 0 ||
367 rspeak(PLEASE_ANSWER);
373 bool yes(const char* question, const char* yes_response, const char* no_response)
374 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
375 * if no, print Z and return false. */
386 // Should be unreachable. Reply should never be NULL
392 char* firstword = (char*) xmalloc(strlen(reply) + 1);
393 sscanf(reply, "%s", firstword);
397 for (int i = 0; i < (int)strlen(firstword); ++i)
398 firstword[i] = tolower(firstword[i]);
400 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
401 int y = strncmp("y", firstword, sizeof("y") - 1);
402 int no = strncmp("no", firstword, sizeof("no") - 1);
403 int n = strncmp("n", firstword, sizeof("n") - 1);
412 } else if (no == 0 ||
418 rspeak(PLEASE_ANSWER);
425 /* Data structure routines */
427 int get_motion_vocab_id(const char* word)
428 // Return the first motion number that has 'word' as one of its words.
430 for (int i = 0; i < NMOTIONS; ++i) {
431 for (int j = 0; j < motions[i].words.n; ++j) {
432 if (strcasecmp(word, motions[i].words.strs[j]) == 0 && (strlen(word) > 1 ||
433 strchr(ignore, word[0]) == NULL ||
438 // If execution reaches here, we didn't find the word.
439 return (WORD_NOT_FOUND);
442 int get_object_vocab_id(const char* word)
443 // Return the first object number that has 'word' as one of its words.
445 for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
446 for (int j = 0; j < objects[i].words.n; ++j) {
447 if (strcasecmp(word, objects[i].words.strs[j]) == 0)
451 // If execution reaches here, we didn't find the word.
452 return (WORD_NOT_FOUND);
455 int get_action_vocab_id(const char* word)
456 // Return the first motion number that has 'word' as one of its words.
458 for (int i = 0; i < NACTIONS; ++i) {
459 for (int j = 0; j < actions[i].words.n; ++j) {
460 if (strcasecmp(word, actions[i].words.strs[j]) == 0 && (strlen(word) > 1 ||
461 strchr(ignore, word[0]) == NULL ||
466 // If execution reaches here, we didn't find the word.
467 return (WORD_NOT_FOUND);
470 int get_special_vocab_id(const char* word)
471 // Return the first special number that has 'word' as one of its words.
473 for (int i = 0; i < NSPECIALS; ++i) {
474 for (int j = 0; j < specials[i].words.n; ++j) {
475 if (strcasecmp(word, specials[i].words.strs[j]) == 0)
479 // If execution reaches here, we didn't find the word.
480 return (WORD_NOT_FOUND);
483 long get_vocab_id(const char* word)
484 // Search the vocab categories in order for the supplied word.
486 /* Check for an empty string */
487 if (strncmp(word, "", sizeof("")) == 0)
492 /* FIXME: Magic numbers related to vocabulary */
493 ref_num = get_motion_vocab_id(word);
494 if (ref_num != WORD_NOT_FOUND)
495 return (ref_num + 0); // FIXME: replace with a proper hash
497 ref_num = get_object_vocab_id(word);
498 if (ref_num != WORD_NOT_FOUND)
499 return (ref_num + 1000); // FIXME: replace with a proper hash
501 ref_num = get_action_vocab_id(word);
502 if (ref_num != WORD_NOT_FOUND)
503 return (ref_num + 2000); // FIXME: replace with a proper hash
505 ref_num = get_special_vocab_id(word);
506 if (ref_num != WORD_NOT_FOUND)
507 return (ref_num + 3000); // FIXME: replace with a proper hash
509 // Check for the reservoir magic word.
510 if (strcasecmp(word, game.zzword) == 0)
511 return (PART + 2000); // FIXME: replace with a proper hash
513 return (WORD_NOT_FOUND);
516 void juggle(long object)
517 /* Juggle an object by picking it up and putting it down again, the purpose
518 * being to get the object to the front of the chain of things at its loc. */
522 i = game.place[object];
523 j = game.fixed[object];
525 move(object + NOBJECTS, j);
528 void move(long object, long where)
529 /* Place any object anywhere by picking it up and dropping it. May
530 * already be toting, in which case the carry is a no-op. Mustn't
531 * pick up objects which are not at any loc, since carry wants to
532 * remove objects from game.atloc chains. */
536 if (object > NOBJECTS)
537 from = game.fixed[object - NOBJECTS];
539 from = game.place[object];
540 if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
545 long put(long object, long where, long pval)
546 /* PUT is the same as MOVE, except it returns a value used to set up the
547 * negated game.prop values for the repository objects. */
553 void carry(long object, long where)
554 /* Start toting an object, removing it from the list of things at its former
555 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
556 * (moving "fixed" second loc), don't change game.place or game.holdng. */
560 if (object <= NOBJECTS) {
561 if (game.place[object] == CARRIED)
563 game.place[object] = CARRIED;
566 if (game.atloc[where] == object) {
567 game.atloc[where] = game.link[object];
570 temp = game.atloc[where];
571 while (game.link[temp] != object) {
572 temp = game.link[temp];
574 game.link[temp] = game.link[object];
577 void drop(long object, long where)
578 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
579 * game.holdng if the object was being toted. */
581 if (object > NOBJECTS)
582 game.fixed[object - NOBJECTS] = where;
584 if (game.place[object] == CARRIED)
586 game.place[object] = where;
590 game.link[object] = game.atloc[where];
591 game.atloc[where] = object;
594 long atdwrf(long where)
595 /* Return the index of first dwarf at the given location, zero if no dwarf is
596 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
597 * the pirate (6th dwarf). */
605 for (long i = 1; i <= NDWARVES - 1; i++) {
606 if (game.dloc[i] == where)
608 if (game.dloc[i] != 0)
614 /* Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
617 long setbit(long bit)
618 /* Returns 2**bit for use in constructing bit-masks. */
623 bool tstbit(long mask, int bit)
624 /* Returns true if the specified bit is set in the mask. */
626 return (mask & (1 << bit)) != 0;
629 void set_seed(long seedval)
630 /* Set the LCG seed */
632 game.lcg_x = (unsigned long) seedval % game.lcg_m;
634 // once seed is set, we need to generate the Z`ZZZ word
635 make_zzword(game.zzword);
638 unsigned long get_next_lcg_value(void)
639 /* Return the LCG's current value, and then iterate it. */
641 unsigned long old_x = game.lcg_x;
642 game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
646 long randrange(long range)
647 /* Return a random integer from [0, range). */
649 return range * get_next_lcg_value() / game.lcg_m;
652 void make_zzword(char zzword[TOKLEN + 1])
654 for (int i = 0; i < 5; ++i) {
655 zzword[i] = 'A' + randrange(26);
657 zzword[1] = '\''; // force second char to apostrophe
662 void bug(enum bugtype num, const char *error_string)
664 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);