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 /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
103 * effect on raw tokens of packing them into sixbit characters, 5
104 * to a 32-bit word. This is something the FORTRAN version did
105 * becuse archaic FORTRAN had no string types. Don Wood's
106 * mechanical translation of 2.5 to C retained the packing and
107 * thus this misfeature.
109 * It's philosophically questionable whether this is the right
110 * thing to do even in oldstyle mode. On one hand, the text
111 * mangling was not authorial intent, but a result of limitations
112 * in their tools. On the other, not simulating this misbehavior
113 * goes against the goal of making oldstyle as accurate as
114 * possible an emulation of the original UI.
116 if (settings.oldstyle) {
117 cmd->raw1[TOKLEN + TOKLEN] = cmd->raw2[TOKLEN + TOKLEN] = '\0';
118 for (size_t i = 0; i < strlen(cmd->raw1); i++)
119 cmd->raw1[i] = toupper(cmd->raw1[i]);
120 for (size_t i = 0; i < strlen(cmd->raw2); i++)
121 cmd->raw2[i] = toupper(cmd->raw2[i]);
125 /* Hide the fact that wods are corrently packed longs */
127 void wordclear(token_t *v)
132 /* I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
134 static void vspeak(const char* msg, bool blank, va_list ap)
136 // Do nothing if we got a null pointer.
140 // Do nothing if we got an empty string.
141 if (strlen(msg) == 0)
147 int msglen = strlen(msg);
150 ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
151 char* rendered = xmalloc(size);
152 char* renderp = rendered;
154 // Handle format specifiers (including the custom %C, %L, %S) by
155 // adjusting the parameter accordingly, and replacing the
156 // specifier with %s.
157 long previous_arg = 0;
158 for (int i = 0; i < msglen; i++) {
160 /* Ugh. Least obtrusive way to deal with artifacts "on the floor"
161 * being dropped outside of both cave and building. */
162 if (strncmp(msg + i, "floor", 5) == 0 && strchr(" .", msg[i + 5]) && !INSIDE(game.loc)) {
163 strcpy(renderp, "ground");
172 long arg = va_arg(ap, long);
174 arg = 0; // LCOV_EXCL_LINE - don't think we can get here.
176 // Integer specifier. In order to accommodate the fact
177 // that PARMS can have both legitimate integers *and*
178 // packed tokens, stringify everything. Future work may
179 // eliminate the need for this.
181 int ret = snprintf(renderp, size, "%ld", arg);
188 // Unmodified string specifier.
190 packed_to_token(arg, renderp); /* unpack directly to destination */
191 size_t len = strlen(renderp);
196 // Singular/plural specifier.
198 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
204 /* Version specifier */
206 strcpy(renderp, VERSION);
207 size_t len = strlen(VERSION);
217 // Print the message.
218 printf("%s\n", rendered);
223 void speak(const char* msg, ...)
227 vspeak(msg, true, ap);
231 void sspeak(const long msg, ...)
236 vprintf(arbitrary_messages[msg], ap);
241 void pspeak(vocab_t msg, enum speaktype mode, int skip, bool blank, ...)
242 /* Find the skip+1st message from msg and print it. Modes are:
243 * feel = for inventory, what you can touch
244 * look = the long description for the state the object is in
245 * listen = the sound for the state the object is in
246 * study = text on the object. */
252 vspeak(objects[msg].inventory, blank, ap);
255 vspeak(objects[msg].descriptions[skip], blank, ap);
258 vspeak(objects[msg].sounds[skip], blank, ap);
261 vspeak(objects[msg].texts[skip], blank, ap);
264 vspeak(objects[msg].changes[skip], blank, ap);
270 void rspeak(vocab_t i, ...)
271 /* Print the i-th "random" message (section 6 of database). */
275 vspeak(arbitrary_messages[i], true, ap);
279 void echo_input(FILE* destination, const char* input_prompt, const char* input)
281 size_t len = strlen(input_prompt) + strlen(input) + 1;
282 char* prompt_and_input = (char*) xmalloc(len);
283 strcpy(prompt_and_input, input_prompt);
284 strcat(prompt_and_input, input);
285 fprintf(destination, "%s\n", prompt_and_input);
286 free(prompt_and_input);
289 int word_count(char* str)
291 char delims[] = " \t";
295 for (char *s = str; *s; s++)
297 if (strchr(delims, *s) == 0) {
302 if (strchr(delims, *s) != 0) {
313 char input_prompt[] = "> ";
314 if (!settings.prompt)
315 input_prompt[0] = '\0';
317 // Print a blank line
322 input = readline(input_prompt);
324 if (input == NULL) // Got EOF; return with it.
326 if (input[0] == '#') { // Ignore comments.
330 // We have a 'normal' line; leave the loop.
334 // Strip trailing newlines from the input
335 input[strcspn(input, "\n")] = 0;
340 echo_input(stdout, input_prompt, input);
343 echo_input(settings.logfp, "", input);
350 bool outcome = false;
353 char* reply = get_input();
356 // Should be unreachable. Reply should never be NULL
361 if (strlen(reply) == 0) {
363 rspeak(PLEASE_ANSWER);
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. */
401 bool outcome = false;
406 char* reply = get_input();
409 // Should be unreachable. Reply should never be NULL
415 if (strlen(reply) == 0) {
417 rspeak(PLEASE_ANSWER);
421 char* firstword = (char*) xmalloc(strlen(reply) + 1);
422 sscanf(reply, "%s", firstword);
426 for (int i = 0; i < (int)strlen(firstword); ++i)
427 firstword[i] = tolower(firstword[i]);
429 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
430 int y = strncmp("y", firstword, sizeof("y") - 1);
431 int no = strncmp("no", firstword, sizeof("no") - 1);
432 int n = strncmp("n", firstword, sizeof("n") - 1);
441 } else if (no == 0 ||
447 rspeak(PLEASE_ANSWER);
454 /* Data structure routines */
456 int get_motion_vocab_id(const char* word)
457 // Return the first motion number that has 'word' as one of its words.
459 for (int i = 0; i < NMOTIONS; ++i) {
460 for (int j = 0; j < motions[i].words.n; ++j) {
461 if (strncasecmp(word, motions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
462 strchr(ignore, word[0]) == NULL ||
467 // If execution reaches here, we didn't find the word.
468 return (WORD_NOT_FOUND);
471 int get_object_vocab_id(const char* word)
472 // Return the first object number that has 'word' as one of its words.
474 for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
475 for (int j = 0; j < objects[i].words.n; ++j) {
476 if (strncasecmp(word, objects[i].words.strs[j], TOKLEN) == 0)
480 // If execution reaches here, we didn't find the word.
481 return (WORD_NOT_FOUND);
484 int get_action_vocab_id(const char* word)
485 // Return the first motion number that has 'word' as one of its words.
487 for (int i = 0; i < NACTIONS; ++i) {
488 for (int j = 0; j < actions[i].words.n; ++j) {
489 if (strncasecmp(word, actions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
490 strchr(ignore, word[0]) == NULL ||
495 // If execution reaches here, we didn't find the word.
496 return (WORD_NOT_FOUND);
499 int get_special_vocab_id(const char* word)
500 // Return the first special number that has 'word' as one of its words.
502 for (int i = 0; i < NSPECIALS; ++i) {
503 for (int j = 0; j < specials[i].words.n; ++j) {
504 if (strncasecmp(word, specials[i].words.strs[j], TOKLEN) == 0)
508 // If execution reaches here, we didn't find the word.
509 return (WORD_NOT_FOUND);
512 void get_vocab_metadata(const char* word, long* id, enum wordtype* type)
514 /* Check for an empty string */
515 if (strncmp(word, "", sizeof("")) == 0) {
517 *type = NO_WORD_TYPE;
523 ref_num = get_motion_vocab_id(word);
524 if (ref_num != WORD_NOT_FOUND) {
530 ref_num = get_object_vocab_id(word);
531 if (ref_num != WORD_NOT_FOUND) {
537 ref_num = get_action_vocab_id(word);
538 if (ref_num != WORD_NOT_FOUND) {
544 ref_num = get_special_vocab_id(word);
545 if (ref_num != WORD_NOT_FOUND) {
551 // Check for the reservoir magic word.
552 if (strcasecmp(word, game.zzword) == 0) {
558 *id = WORD_NOT_FOUND;
559 *type = NO_WORD_TYPE;
563 void juggle(obj_t object)
564 /* Juggle an object by picking it up and putting it down again, the purpose
565 * being to get the object to the front of the chain of things at its loc. */
569 i = game.place[object];
570 j = game.fixed[object];
572 move(object + NOBJECTS, j);
575 void move(obj_t object, loc_t where)
576 /* Place any object anywhere by picking it up and dropping it. May
577 * already be toting, in which case the carry is a no-op. Mustn't
578 * pick up objects which are not at any loc, since carry wants to
579 * remove objects from game.atloc chains. */
583 if (object > NOBJECTS)
584 from = game.fixed[object - NOBJECTS];
586 from = game.place[object];
587 /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong... */
588 if (from != LOC_NOWHERE && from != CARRIED)
593 long put(obj_t object, loc_t where, long pval)
594 /* put() is the same as move(), except it returns a value used to set up the
595 * negated game.prop values for the repository objects. */
598 return STASHED(pval);
601 void carry(obj_t object, loc_t where)
602 /* Start toting an object, removing it from the list of things at its former
603 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
604 * (moving "fixed" second loc), don't change game.place or game.holdng. */
608 if (object <= NOBJECTS) {
609 if (game.place[object] == CARRIED)
611 game.place[object] = CARRIED;
614 if (game.atloc[where] == object) {
615 game.atloc[where] = game.link[object];
618 temp = game.atloc[where];
619 while (game.link[temp] != object) {
620 temp = game.link[temp];
622 game.link[temp] = game.link[object];
625 void drop(obj_t object, loc_t where)
626 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
627 * game.holdng if the object was being toted. */
629 if (object > NOBJECTS)
630 game.fixed[object - NOBJECTS] = where;
632 if (game.place[object] == CARRIED)
634 game.place[object] = where;
636 if (where == LOC_NOWHERE ||
639 game.link[object] = game.atloc[where];
640 game.atloc[where] = object;
643 long atdwrf(loc_t where)
644 /* Return the index of first dwarf at the given location, zero if no dwarf is
645 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
646 * the pirate (6th dwarf). */
654 for (long i = 1; i <= NDWARVES - 1; i++) {
655 if (game.dloc[i] == where)
657 if (game.dloc[i] != 0)
663 /* Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
666 long setbit(long bit)
667 /* Returns 2**bit for use in constructing bit-masks. */
672 bool tstbit(long mask, int bit)
673 /* Returns true if the specified bit is set in the mask. */
675 return (mask & (1 << bit)) != 0;
678 void set_seed(long seedval)
679 /* Set the LCG seed */
681 game.lcg_x = (unsigned long) seedval % game.lcg_m;
683 // once seed is set, we need to generate the Z`ZZZ word
684 make_zzword(game.zzword);
687 unsigned long get_next_lcg_value(void)
688 /* Return the LCG's current value, and then iterate it. */
690 unsigned long old_x = game.lcg_x;
691 game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
695 long randrange(long range)
696 /* Return a random integer from [0, range). */
698 return range * get_next_lcg_value() / game.lcg_m;
701 void make_zzword(char zzword[TOKLEN + 1])
703 for (int i = 0; i < 5; ++i) {
704 zzword[i] = 'A' + randrange(26);
706 zzword[1] = '\''; // force second char to apostrophe
711 void bug(enum bugtype num, const char *error_string)
713 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
720 void state_change(obj_t obj, long state)
721 /* Object must have a change-message list for this to be useful; only some do */
723 game.prop[obj] = state;
724 pspeak(obj, change, state, true);