8 #include <editline/readline.h>
14 static void* xcalloc(size_t size)
16 void* ptr = calloc(size, 1);
19 // exclude from coverage analysis because we can't simulate an out of memory error in testing
20 fprintf(stderr, "Out of memory!\n");
27 /* I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
29 static void vspeak(const char* msg, bool blank, va_list ap)
31 // Do nothing if we got a null pointer.
35 // Do nothing if we got an empty string.
42 int msglen = strlen(msg);
45 ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
46 char* rendered = xcalloc(size);
47 char* renderp = rendered;
49 // Handle format specifiers (including the custom %S) by
50 // adjusting the parameter accordingly, and replacing the
52 bool pluralize = false;
53 for (int i = 0; i < msglen; i++) {
55 /* Ugh. Least obtrusive way to deal with artifacts "on the floor"
56 * being dropped outside of both cave and building. */
57 if (strncmp(msg + i, "floor", 5) == 0 && strchr(" .", msg[i + 5]) && !INSIDE(game.loc)) {
58 strcpy(renderp, "ground");
70 int32_t arg = va_arg(ap, int32_t);
71 int ret = snprintf(renderp, size, "%" PRId32, arg);
76 pluralize = (arg != 1);
79 // Unmodified string specifier.
81 char *arg = va_arg(ap, char *);
82 strncat(renderp, arg, size - 1);
83 size_t len = strlen(renderp);
88 // Singular/plural specifier.
90 // look at the *previous* numeric parameter
97 // LCOV_EXCL_START - doesn't occur in test suite.
98 /* Version specifier */
100 strcpy(renderp, VERSION);
101 size_t len = strlen(VERSION);
110 // Print the message.
111 printf("%s\n", rendered);
116 void speak(const char* msg, ...)
120 vspeak(msg, true, ap);
124 void sspeak(const int msg, ...)
129 vprintf(arbitrary_messages[msg], ap);
134 void pspeak(vocab_t msg, enum speaktype mode, int skip, bool blank, ...)
135 /* Find the skip+1st message from msg and print it. Modes are:
136 * feel = for inventory, what you can touch
137 * look = the full description for the state the object is in
138 * listen = the sound for the state the object is in
139 * study = text on the object. */
145 vspeak(objects[msg].inventory, blank, ap);
148 vspeak(objects[msg].descriptions[skip], blank, ap);
151 vspeak(objects[msg].sounds[skip], blank, ap);
154 vspeak(objects[msg].texts[skip], blank, ap);
157 vspeak(objects[msg].changes[skip], blank, ap);
163 void rspeak(vocab_t i, ...)
164 /* Print the i-th "random" message (section 6 of database). */
168 vspeak(arbitrary_messages[i], true, ap);
172 void echo_input(FILE* destination, const char* input_prompt, const char* input)
174 size_t len = strlen(input_prompt) + strlen(input) + 1;
175 char* prompt_and_input = (char*) xcalloc(len);
176 strcpy(prompt_and_input, input_prompt);
177 strcat(prompt_and_input, input);
178 fprintf(destination, "%s\n", prompt_and_input);
179 free(prompt_and_input);
182 static int word_count(char* str)
184 char delims[] = " \t";
188 for (char *s = str; *s; s++)
190 if (strchr(delims, *s) == 0) {
195 if (strchr(delims, *s) != 0) {
203 static char* get_input(void)
206 char input_prompt[] = "> ";
207 if (!settings.prompt)
208 input_prompt[0] = '\0';
210 // Print a blank line
215 input = readline(input_prompt);
217 if (input == NULL) // Got EOF; return with it.
219 if (input[0] == '#') { // Ignore comments.
223 // We have a 'normal' line; leave the loop.
227 // Strip trailing newlines from the input
228 input[strcspn(input, "\n")] = 0;
233 echo_input(stdout, input_prompt, input);
236 echo_input(settings.logfp, "", input);
241 bool silent_yes(void)
243 bool outcome = false;
246 char* reply = get_input();
249 // Should be unreachable. Reply should never be NULL
254 if (strlen(reply) == 0) {
256 rspeak(PLEASE_ANSWER);
260 char* firstword = (char*) xcalloc(strlen(reply) + 1);
261 sscanf(reply, "%s", firstword);
265 for (int i = 0; i < (int)strlen(firstword); ++i)
266 firstword[i] = tolower(firstword[i]);
268 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
269 int y = strncmp("y", firstword, sizeof("y") - 1);
270 int no = strncmp("no", firstword, sizeof("no") - 1);
271 int n = strncmp("n", firstword, sizeof("n") - 1);
279 } else if (no == 0 ||
284 rspeak(PLEASE_ANSWER);
290 bool yes(const char* question, const char* yes_response, const char* no_response)
291 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
292 * if no, print Z and return false. */
294 bool outcome = false;
299 char* reply = get_input();
302 // Should be unreachable. Reply should never be NULL
308 if (strlen(reply) == 0) {
310 rspeak(PLEASE_ANSWER);
314 char* firstword = (char*) xcalloc(strlen(reply) + 1);
315 sscanf(reply, "%s", firstword);
319 for (int i = 0; i < (int)strlen(firstword); ++i)
320 firstword[i] = tolower(firstword[i]);
322 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
323 int y = strncmp("y", firstword, sizeof("y") - 1);
324 int no = strncmp("no", firstword, sizeof("no") - 1);
325 int n = strncmp("n", firstword, sizeof("n") - 1);
334 } else if (no == 0 ||
340 rspeak(PLEASE_ANSWER);
347 /* Data structure routines */
349 static int get_motion_vocab_id(const char* word)
350 // Return the first motion number that has 'word' as one of its words.
352 for (int i = 0; i < NMOTIONS; ++i) {
353 for (int j = 0; j < motions[i].words.n; ++j) {
354 if (strncasecmp(word, motions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
355 strchr(ignore, word[0]) == NULL ||
360 // If execution reaches here, we didn't find the word.
361 return (WORD_NOT_FOUND);
364 static int get_object_vocab_id(const char* word)
365 // Return the first object number that has 'word' as one of its words.
367 for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
368 for (int j = 0; j < objects[i].words.n; ++j) {
369 if (strncasecmp(word, objects[i].words.strs[j], TOKLEN) == 0)
373 // If execution reaches here, we didn't find the word.
374 return (WORD_NOT_FOUND);
377 static int get_action_vocab_id(const char* word)
378 // Return the first motion number that has 'word' as one of its words.
380 for (int i = 0; i < NACTIONS; ++i) {
381 for (int j = 0; j < actions[i].words.n; ++j) {
382 if (strncasecmp(word, actions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
383 strchr(ignore, word[0]) == NULL ||
388 // If execution reaches here, we didn't find the word.
389 return (WORD_NOT_FOUND);
392 static bool is_valid_int(const char *str)
393 /* Returns true if the string passed in is represents a valid integer,
394 * that could then be parsed by atoi() */
396 // Handle negative number
400 // Handle empty string or just "-". Should never reach this
401 // point, because this is only used with transitive verbs.
403 return false; // LCOV_EXCL_LINE
405 // Check for non-digit chars in the rest of the stirng.
416 static void get_vocab_metadata(command_word_t* word)
418 /* Check for an empty string */
419 if (strncmp(word->raw, "", sizeof("")) == 0) {
420 word->id = WORD_EMPTY;
421 word->type = NO_WORD_TYPE;
427 ref_num = get_motion_vocab_id(word->raw);
428 if (ref_num != WORD_NOT_FOUND) {
434 ref_num = get_object_vocab_id(word->raw);
435 if (ref_num != WORD_NOT_FOUND) {
441 ref_num = get_action_vocab_id(word->raw);
442 if (ref_num != WORD_NOT_FOUND) {
448 // Check for the reservoir magic word.
449 if (strcasecmp(word->raw, game.zzword) == 0) {
455 // Check words that are actually numbers.
456 if (is_valid_int(word->raw)) {
457 word->id = WORD_EMPTY;
458 word->type = NUMERIC;
462 word->id = WORD_NOT_FOUND;
463 word->type = NO_WORD_TYPE;
467 static void tokenize(char* raw, command_t *cmd)
469 memset(cmd, '\0', sizeof(command_t));
471 /* Bound prefix on the %s would be needed to prevent buffer
472 * overflow. but we shortstop this more simply by making each
473 * raw-input buffer as long as the entire input buffer. */
474 sscanf(raw, "%s%s", cmd->word[0].raw, cmd->word[1].raw);
476 /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
477 * effect on raw tokens of packing them into sixbit characters, 5
478 * to a 32-bit word. This is something the FORTRAN version did
479 * becuse archaic FORTRAN had no string types. Don Wood's
480 * mechanical translation of 2.5 to C retained the packing and
481 * thus this misfeature.
483 * It's philosophically questionable whether this is the right
484 * thing to do even in oldstyle mode. On one hand, the text
485 * mangling was not authorial intent, but a result of limitations
486 * in their tools. On the other, not simulating this misbehavior
487 * goes against the goal of making oldstyle as accurate as
488 * possible an emulation of the original UI.
490 if (settings.oldstyle) {
491 cmd->word[0].raw[TOKLEN + TOKLEN] = cmd->word[1].raw[TOKLEN + TOKLEN] = '\0';
492 for (size_t i = 0; i < strlen(cmd->word[0].raw); i++)
493 cmd->word[0].raw[i] = toupper(cmd->word[0].raw[i]);
494 for (size_t i = 0; i < strlen(cmd->word[1].raw); i++)
495 cmd->word[1].raw[i] = toupper(cmd->word[1].raw[i]);
498 /* populate command with parsed vocabulary metadata */
499 get_vocab_metadata(&(cmd->word[0]));
500 get_vocab_metadata(&(cmd->word[1]));
503 bool get_command_input(command_t *command)
504 /* Get user input on stdin, parse and map to command */
506 char inputbuf[LINESIZE];
513 if (word_count(input) > 2) {
518 if (strcmp(input, "") != 0)
523 strncpy(inputbuf, input, LINESIZE - 1);
526 tokenize(inputbuf, command);
531 void juggle(obj_t object)
532 /* Juggle an object by picking it up and putting it down again, the purpose
533 * being to get the object to the front of the chain of things at its loc. */
537 i = game.place[object];
538 j = game.fixed[object];
540 move(object + NOBJECTS, j);
543 void move(obj_t object, loc_t where)
544 /* Place any object anywhere by picking it up and dropping it. May
545 * already be toting, in which case the carry is a no-op. Mustn't
546 * pick up objects which are not at any loc, since carry wants to
547 * remove objects from game.atloc chains. */
551 if (object > NOBJECTS)
552 from = game.fixed[object - NOBJECTS];
554 from = game.place[object];
555 /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong... */
556 if (from != LOC_NOWHERE && from != CARRIED)
561 loc_t put(obj_t object, loc_t 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. */
566 return STASHED(pval);
569 void carry(obj_t object, loc_t 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(obj_t object, loc_t 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;
604 if (where == LOC_NOWHERE ||
607 game.link[object] = game.atloc[where];
608 game.atloc[where] = object;
611 int atdwrf(loc_t where)
612 /* Return the index of first dwarf at the given location, zero if no dwarf is
613 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
614 * the pirate (6th dwarf). */
622 for (long i = 1; i <= NDWARVES - 1; i++) {
623 if (game.dloc[i] == where)
625 if (game.dloc[i] != 0)
631 /* Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
635 /* Returns 2**bit for use in constructing bit-masks. */
640 bool tstbit(long mask, int bit)
641 /* Returns true if the specified bit is set in the mask. */
643 return (mask & (1 << bit)) != 0;
646 void set_seed(int32_t seedval)
647 /* Set the LCG seed */
649 game.lcg_x = seedval % LCG_M;
650 if (game.lcg_x < 0) {
651 game.lcg_x = LCG_M + game.lcg_x;
653 // once seed is set, we need to generate the Z`ZZZ word
654 for (int i = 0; i < 5; ++i) {
655 game.zzword[i] = 'A' + randrange(26);
657 game.zzword[1] = '\''; // force second char to apostrophe
658 game.zzword[5] = '\0';
661 static int32_t get_next_lcg_value(void)
662 /* Return the LCG's current value, and then iterate it. */
664 int32_t old_x = game.lcg_x;
665 game.lcg_x = (LCG_A * game.lcg_x + LCG_C) % LCG_M;
669 int32_t randrange(int32_t range)
670 /* Return a random integer from [0, range). */
672 return range * get_next_lcg_value() / LCG_M;
676 void bug(enum bugtype num, const char *error_string)
678 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
685 void state_change(obj_t obj, int state)
686 /* Object must have a change-message list for this to be useful; only some do */
688 game.prop[obj] = state;
689 pspeak(obj, change, state, true);