10 #include "linenoise/linenoise.h"
13 char* xstrdup(const char* s)
15 char* ptr = strdup(s);
18 // exclude from coverage analysis because we can't simulate an out of memory error in testing
19 fprintf(stderr, "Out of memory!\n");
25 void* xmalloc(size_t size)
27 void* ptr = malloc(size);
30 // exclude from coverage analysis because we can't simulate an out of memory error in testing
31 fprintf(stderr, "Out of memory!\n");
38 void packed_to_token(long packed, char token[6])
40 // The advent->ascii mapping.
41 const char advent_to_ascii[] = {
42 ' ', '!', '"', '#', '$', '%', '&', '\'',
43 '(', ')', '*', '+', ',', '-', '.', '/',
44 '0', '1', '2', '3', '4', '5', '6', '7',
45 '8', '9', ':', ';', '<', '=', '>', '?',
46 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
47 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
48 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
49 'X', 'Y', 'Z', '\0', '\0', '\0', '\0', '\0',
52 // Unpack and map back to ASCII.
53 for (int i = 0; i < 5; ++i) {
54 char advent = (packed >> i * 6) & 63;
55 token[i] = advent_to_ascii[(int) advent];
58 // Ensure the last character is \0.
61 // Replace trailing whitespace with \0.
62 for (int i = 4; i >= 0; --i) {
63 if (token[i] == ' ' || token[i] == '\t')
70 long token_to_packed(const char token[6])
72 const char ascii_to_advent[] = {
73 63, 63, 63, 63, 63, 63, 63, 63,
74 63, 63, 63, 63, 63, 63, 63, 63,
75 63, 63, 63, 63, 63, 63, 63, 63,
76 63, 63, 63, 63, 63, 63, 63, 63,
78 0, 1, 2, 3, 4, 5, 6, 7,
79 8, 9, 10, 11, 12, 13, 14, 15,
80 16, 17, 18, 19, 20, 21, 22, 23,
81 24, 25, 26, 27, 28, 29, 30, 31,
82 32, 33, 34, 35, 36, 37, 38, 39,
83 40, 41, 42, 43, 44, 45, 46, 47,
84 48, 49, 50, 51, 52, 53, 54, 55,
85 56, 57, 58, 59, 60, 61, 62, 63,
87 63, 63, 63, 63, 63, 63, 63, 63,
88 63, 63, 63, 63, 63, 63, 63, 63,
89 63, 63, 63, 63, 63, 63, 63, 63,
90 63, 63, 63, 63, 63, 63, 63, 63,
93 size_t t_len = strlen(token);
95 for (size_t i = 0; i < t_len; ++i) {
96 char mapped = ascii_to_advent[(int) token[i]];
97 packed |= (mapped << (6 * i));
102 void tokenize(char* raw, long tokens[4])
104 // set each token to 0
105 for (int i = 0; i < 4; ++i)
108 // grab the first two words
110 words[0] = (char*) xmalloc(strlen(raw) + 1);
111 words[1] = (char*) xmalloc(strlen(raw) + 1);
112 int word_count = sscanf(raw, "%s%s", words[0], words[1]);
114 // make space for substrings and zero it out
115 char chunk_data[][6] = {
122 // break the words into up to 4 5-char substrings
123 sscanf(words[0], "%5s%5s", chunk_data[0], chunk_data[1]);
125 sscanf(words[1], "%5s%5s", chunk_data[2], chunk_data[3]);
129 // uppercase all the substrings
130 for (int i = 0; i < 4; ++i)
131 for (unsigned int j = 0; j < strlen(chunk_data[i]); ++j)
132 chunk_data[i][j] = (char) toupper(chunk_data[i][j]);
134 // pack the substrings
135 for (int i = 0; i < 4; ++i)
136 tokens[i] = token_to_packed(chunk_data[i]);
139 /* Hide the fact that wods are corrently packed longs */
141 bool wordeq(token_t a, token_t b)
146 bool wordempty(token_t a)
151 void wordclear(token_t *v)
156 /* I/O routines (speak, pspeak, rspeak, get_input, yes) */
158 void vspeak(const char* msg, va_list ap)
160 // Do nothing if we got a null pointer.
164 // Do nothing if we got an empty string.
165 if (strlen(msg) == 0)
168 // Print a newline if the global game.blklin says to.
169 if (game.blklin == true)
172 int msglen = strlen(msg);
175 ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
176 char* rendered = xmalloc(size);
177 char* renderp = rendered;
179 // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
180 long previous_arg = 0;
181 for (int i = 0; i < msglen; i++) {
186 long arg = va_arg(ap, long);
190 // 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.
192 int ret = snprintf(renderp, size, "%ld", arg);
199 // Unmodified string specifier.
201 packed_to_token(arg, renderp); /* unpack directly to destination */
202 size_t len = strlen(renderp);
207 // Singular/plural specifier.
209 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
215 // All-lowercase specifier.
216 if (msg[i] == 'L' || msg[i] == 'C') {
217 packed_to_token(arg, renderp); /* unpack directly to destination */
218 int len = strlen(renderp);
219 for (int j = 0; j < len; ++j) {
220 renderp[j] = tolower(renderp[j]);
222 if (msg[i] == 'C') // First char uppercase, rest lowercase.
223 renderp[0] = toupper(renderp[0]);
233 // Print the message.
234 printf("%s\n", rendered);
239 void speak(const char* msg, ...)
247 void pspeak(vocab_t msg, enum speaktype mode, int skip, ...)
248 /* Find the skip+1st message from msg and print it. Modes are:
249 * feel = for inventory, what you can touch
250 * look = the long description for the state the object is in
251 * listen = the sound for the state the object is in
252 * study = text on the object. */
258 vspeak(objects[msg].inventory, ap);
261 vspeak(objects[msg].descriptions[skip], ap);
264 vspeak(objects[msg].sounds[skip], ap);
267 vspeak(objects[msg].texts[skip], ap);
270 vspeak(objects[msg].changes[skip], ap);
276 void rspeak(vocab_t i, ...)
277 /* Print the i-th "random" message (section 6 of database). */
281 vspeak(arbitrary_messages[i], ap);
285 void echo_input(FILE* destination, char* input_prompt, char* input)
287 size_t len = strlen(input_prompt) + strlen(input) + 1;
288 char* prompt_and_input = (char*) xmalloc(len);
289 strcpy(prompt_and_input, input_prompt);
290 strcat(prompt_and_input, input);
291 fprintf(destination, "%s\n", prompt_and_input);
292 free(prompt_and_input);
295 int word_count(char* s)
297 char* copy = xstrdup(s);
298 char delims[] = " \t";
302 word = strtok(copy, delims);
303 while (word != NULL) {
304 word = strtok(NULL, delims);
314 char input_prompt[] = "> ";
316 input_prompt[0] = '\0';
318 // Print a blank line if game.blklin tells us to.
319 if (game.blklin == true)
325 input = linenoise(input_prompt);
331 // Should be unreachable in tests, as they will use a non-interactive shell.
332 printf("%s", input_prompt);
334 ssize_t numread = getline(&input, &n, stdin);
335 if (numread == -1) // Got EOF; return with it.
339 if (input == NULL) // Got EOF; return with it.
341 else if (input[0] == '#') // Ignore comments.
343 else // We have a 'normal' line; leave the loop.
347 // Strip trailing newlines from the input
348 input[strcspn(input, "\n")] = 0;
350 linenoiseHistoryAdd(input);
353 echo_input(stdout, input_prompt, input);
356 echo_input(logfp, input_prompt, input);
370 // Should be unreachable. Reply should never be NULL
371 linenoiseFree(reply);
376 char* firstword = (char*) xmalloc(strlen(reply) + 1);
377 sscanf(reply, "%s", firstword);
379 for (int i = 0; i < (int)strlen(firstword); ++i)
380 firstword[i] = tolower(firstword[i]);
382 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
383 int y = strncmp("y", firstword, sizeof("y") - 1);
384 int no = strncmp("no", firstword, sizeof("no") - 1);
385 int n = strncmp("n", firstword, sizeof("n") - 1);
389 if (yes == 0 || y == 0) {
392 } else if (no == 0 || n == 0) {
396 rspeak(PLEASE_ANSWER);
398 linenoiseFree(reply);
403 bool yes(const char* question, const char* yes_response, const char* no_response)
404 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
405 * if no, print Z and return false. */
416 // Should be unreachable. Reply should never be NULL
417 linenoiseFree(reply);
422 char* firstword = (char*) xmalloc(strlen(reply) + 1);
423 sscanf(reply, "%s", firstword);
425 for (int i = 0; i < (int)strlen(firstword); ++i)
426 firstword[i] = tolower(firstword[i]);
428 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
429 int y = strncmp("y", firstword, sizeof("y") - 1);
430 int no = strncmp("no", firstword, sizeof("no") - 1);
431 int n = strncmp("n", firstword, sizeof("n") - 1);
435 if (yes == 0 || y == 0) {
439 } else if (no == 0 || n == 0) {
444 rspeak(PLEASE_ANSWER);
446 linenoiseFree(reply);
450 /* Data structure routines */
452 int get_motion_vocab_id(const char* word)
453 // Return the first motion number that has 'word' as one of its words.
455 for (int i = 0; i < NMOTIONS; ++i) {
456 for (int j = 0; j < motions[i].words.n; ++j) {
457 if (strcasecmp(word, motions[i].words.strs[j]) == 0)
461 // If execution reaches here, we didn't find the word.
462 return (WORD_NOT_FOUND);
465 int get_object_vocab_id(const char* word)
466 // Return the first object number that has 'word' as one of its words.
468 for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
469 for (int j = 0; j < objects[i].words.n; ++j) {
470 if (strcasecmp(word, objects[i].words.strs[j]) == 0)
474 // If execution reaches here, we didn't find the word.
475 return (WORD_NOT_FOUND);
478 int get_action_vocab_id(const char* word)
479 // Return the first motion number that has 'word' as one of its words.
481 for (int i = 0; i < NACTIONS; ++i) {
482 for (int j = 0; j < actions[i].words.n; ++j) {
483 if (strcasecmp(word, actions[i].words.strs[j]) == 0)
487 // If execution reaches here, we didn't find the word.
488 return (WORD_NOT_FOUND);
491 int get_special_vocab_id(const char* word)
492 // Return the first special number that has 'word' as one of its words.
494 for (int i = 0; i < NSPECIALS; ++i) {
495 for (int j = 0; j < specials[i].words.n; ++j) {
496 if (strcasecmp(word, specials[i].words.strs[j]) == 0)
500 // If execution reaches here, we didn't find the word.
501 return (WORD_NOT_FOUND);
504 long get_vocab_id(const char* word)
505 // Search the vocab categories in order for the supplied word.
509 ref_num = get_motion_vocab_id(word);
510 if (ref_num != WORD_NOT_FOUND)
511 return (ref_num + 0); // FIXME: replace with a proper hash
513 ref_num = get_object_vocab_id(word);
514 if (ref_num != WORD_NOT_FOUND)
515 return (ref_num + 1000); // FIXME: replace with a proper hash
517 ref_num = get_action_vocab_id(word);
518 if (ref_num != WORD_NOT_FOUND)
519 return (ref_num + 2000); // FIXME: replace with a proper hash
521 ref_num = get_special_vocab_id(word);
522 if (ref_num != WORD_NOT_FOUND)
523 return (ref_num + 3000); // FIXME: replace with a proper hash
525 // Check for the reservoir magic word.
526 if (strcasecmp(word, game.zzword) == 0)
527 return (PART + 2000); // FIXME: replace with a proper hash
529 return (WORD_NOT_FOUND);
532 void juggle(long object)
533 /* Juggle an object by picking it up and putting it down again, the purpose
534 * being to get the object to the front of the chain of things at its loc. */
538 i = game.place[object];
539 j = game.fixed[object];
541 move(object + NOBJECTS, j);
544 void move(long object, long where)
545 /* Place any object anywhere by picking it up and dropping it. May
546 * already be toting, in which case the carry is a no-op. Mustn't
547 * pick up objects which are not at any loc, since carry wants to
548 * remove objects from game.atloc chains. */
552 if (object > NOBJECTS)
553 from = game.fixed[object - NOBJECTS];
555 from = game.place[object];
556 if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
561 long put(long object, long where, long pval)
562 /* PUT is the same as MOVE, except it returns a value used to set up the
563 * negated game.prop values for the repository objects. */
569 void carry(long object, long where)
570 /* Start toting an object, removing it from the list of things at its former
571 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
572 * (moving "fixed" second loc), don't change game.place or game.holdng. */
576 if (object <= NOBJECTS) {
577 if (game.place[object] == CARRIED)
579 game.place[object] = CARRIED;
582 if (game.atloc[where] == object) {
583 game.atloc[where] = game.link[object];
586 temp = game.atloc[where];
587 while (game.link[temp] != object) {
588 temp = game.link[temp];
590 game.link[temp] = game.link[object];
593 void drop(long object, long where)
594 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
595 * game.holdng if the object was being toted. */
597 if (object > NOBJECTS)
598 game.fixed[object - NOBJECTS] = where;
600 if (game.place[object] == CARRIED)
602 game.place[object] = where;
606 game.link[object] = game.atloc[where];
607 game.atloc[where] = object;
610 long atdwrf(long where)
611 /* Return the index of first dwarf at the given location, zero if no dwarf is
612 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
613 * the pirate (6th dwarf). */
621 for (long i = 1; i <= NDWARVES - 1; i++) {
622 if (game.dloc[i] == where)
624 if (game.dloc[i] != 0)
630 /* Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
631 * randrange, RNDVOC) */
633 long setbit(long bit)
634 /* Returns 2**bit for use in constructing bit-masks. */
639 bool tstbit(long mask, int bit)
640 /* Returns true if the specified bit is set in the mask. */
642 return (mask & (1 << bit)) != 0;
645 void set_seed(long seedval)
646 /* Set the LCG seed */
648 game.lcg_x = (unsigned long) seedval % game.lcg_m;
651 unsigned long get_next_lcg_value(void)
652 /* Return the LCG's current value, and then iterate it. */
654 unsigned long old_x = game.lcg_x;
655 game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
659 long randrange(long range)
660 /* Return a random integer from [0, range). */
662 return range * get_next_lcg_value() / game.lcg_m;
665 void make_zzword(char zzword[6])
667 for (int i = 0; i < 5; ++i) {
668 zzword[i] = 'A' + randrange(26);
670 zzword[1] = '\''; // force second char to apostrophe
674 void datime(long* d, long* t)
677 gettimeofday(&tv, NULL);
678 *d = (long) tv.tv_sec;
679 *t = (long) tv.tv_usec;
683 void bug(enum bugtype num, const char *error_string)
685 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);