2 * I/O and support routines.
4 * SPDX-FileCopyrightText: (C) 1977, 2005 by Will Crowther and Don Woods
5 * SPDX-License-Identifier: BSD-2-Clause
9 #include <editline/readline.h>
21 static void *xcalloc(size_t size) {
22 void *ptr = calloc(size, 1);
25 // exclude from coverage analysis because we can't simulate an
26 // out of memory error in testing
27 fprintf(stderr, "Out of memory!\n");
34 /* I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
36 static void vspeak(const char *msg, bool blank, va_list ap) {
37 /* Engine for various speak functions */
38 // Do nothing if we got a null pointer.
43 // Do nothing if we got an empty string.
44 if (strlen(msg) == 0) {
52 int msglen = strlen(msg);
55 ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
56 char *rendered = xcalloc(size);
57 char *renderp = rendered;
59 // Handle format specifiers (including the custom %S) by
60 // adjusting the parameter accordingly, and replacing the
62 bool pluralize = false;
63 for (int i = 0; i < msglen; i++) {
65 /* Ugh. Least obtrusive way to deal with artifacts "on
66 * the floor" being dropped outside of both cave and
68 if (strncmp(msg + i, "floor", 5) == 0 &&
69 strchr(" .", msg[i + 5]) && !INSIDE(game.loc)) {
70 strcpy(renderp, "ground");
82 int32_t arg = va_arg(ap, int32_t);
84 snprintf(renderp, size, "%" PRId32, arg);
89 pluralize = (arg != 1);
92 // Unmodified string specifier.
94 char *arg = va_arg(ap, char *);
95 strncat(renderp, arg, size - 1);
96 size_t len = strlen(renderp);
101 // Singular/plural specifier.
103 // look at the *previous* numeric parameter
110 // LCOV_EXCL_START - doesn't occur in test suite.
111 /* Version specifier */
113 strcpy(renderp, VERSION);
114 size_t len = strlen(VERSION);
123 // Print the message.
124 printf("%s\n", rendered);
129 void speak(const char *msg, ...) {
130 /* speak a specified string */
133 vspeak(msg, true, ap);
137 void sspeak(const int msg, ...) {
138 /* Speak a message from the arbitrary-messages list */
142 vprintf(arbitrary_messages[msg], ap);
147 void pspeak(vocab_t msg, enum speaktype mode, bool blank, int skip, ...) {
148 /* Find the skip+1st message from msg and print it. Modes are:
149 * feel = for inventory, what you can touch
150 * look = the full description for the state the object is in
151 * listen = the sound for the state the object is in
152 * study = text on the object. */
157 vspeak(objects[msg].inventory, blank, ap);
160 vspeak(objects[msg].descriptions[skip], blank, ap);
163 vspeak(objects[msg].sounds[skip], blank, ap);
166 vspeak(objects[msg].texts[skip], blank, ap);
169 vspeak(objects[msg].changes[skip], blank, ap);
175 void rspeak(vocab_t i, ...) {
176 /* Print the i-th "random" message (section 6 of database). */
179 vspeak(arbitrary_messages[i], true, ap);
183 void echo_input(FILE *destination, const char *input_prompt,
185 size_t len = strlen(input_prompt) + strlen(input) + 1;
186 char *prompt_and_input = (char *)xcalloc(len);
187 strcpy(prompt_and_input, input_prompt);
188 strcat(prompt_and_input, input);
189 fprintf(destination, "%s\n", prompt_and_input);
190 free(prompt_and_input);
193 static int word_count(char *str) {
194 char delims[] = " \t";
198 for (char *s = str; *s; s++) {
200 if (strchr(delims, *s) == 0) {
205 if (strchr(delims, *s) != 0) {
214 static char *get_input(void) {
216 char input_prompt[] = PROMPT;
217 if (!settings.prompt) {
218 input_prompt[0] = '\0';
221 // Print a blank line
226 input = myreadline(input_prompt);
228 if (input == NULL) { // Got EOF; return with it.
231 if (input[0] == '#') { // Ignore comments.
235 // We have a 'normal' line; leave the loop.
239 // Strip trailing newlines from the input
240 input[strcspn(input, "\n")] = 0;
245 echo_input(stdout, input_prompt, input);
248 if (settings.logfp) {
249 echo_input(settings.logfp, "", input);
255 bool silent_yes_or_no(void) {
256 bool outcome = false;
259 char *reply = get_input();
262 // Should be unreachable. Reply should never be NULL
267 if (strlen(reply) == 0) {
269 rspeak(PLEASE_ANSWER);
273 char *firstword = (char *)xcalloc(strlen(reply) + 1);
274 sscanf(reply, "%s", firstword);
278 for (int i = 0; i < (int)strlen(firstword); ++i) {
279 firstword[i] = tolower(firstword[i]);
282 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
283 int y = strncmp("y", firstword, sizeof("y") - 1);
284 int no = strncmp("no", firstword, sizeof("no") - 1);
285 int n = strncmp("n", firstword, sizeof("n") - 1);
289 if (yes == 0 || y == 0) {
292 } else if (no == 0 || n == 0) {
296 rspeak(PLEASE_ANSWER);
302 bool yes_or_no(const char *question, const char *yes_response,
303 const char *no_response) {
304 /* Print message X, wait for yes/no answer. If yes, print Y and return
305 * true; if no, print Z and return false. */
306 bool outcome = false;
311 char *reply = get_input();
314 // Should be unreachable. Reply should never be NULL
320 if (strlen(reply) == 0) {
322 rspeak(PLEASE_ANSWER);
326 char *firstword = (char *)xcalloc(strlen(reply) + 1);
327 sscanf(reply, "%s", firstword);
331 for (int i = 0; i < (int)strlen(firstword); ++i) {
332 firstword[i] = tolower(firstword[i]);
335 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
336 int y = strncmp("y", firstword, sizeof("y") - 1);
337 int no = strncmp("no", firstword, sizeof("no") - 1);
338 int n = strncmp("n", firstword, sizeof("n") - 1);
342 if (yes == 0 || y == 0) {
346 } else if (no == 0 || n == 0) {
351 rspeak(PLEASE_ANSWER);
358 /* Data structure routines */
360 static int get_motion_vocab_id(const char *word) {
361 // Return the first motion number that has 'word' as one of its words.
362 for (int i = 0; i < NMOTIONS; ++i) {
363 for (int j = 0; j < motions[i].words.n; ++j) {
364 if (strncasecmp(word, motions[i].words.strs[j],
367 strchr(ignore, word[0]) == NULL ||
368 !settings.oldstyle)) {
373 // If execution reaches here, we didn't find the word.
374 return (WORD_NOT_FOUND);
377 static int get_object_vocab_id(const char *word) {
378 // Return the first object number that has 'word' as one of its words.
379 for (int i = 0; i < NOBJECTS + 1;
380 ++i) { // FIXME: the + 1 should go when 1-indexing for objects is
382 for (int j = 0; j < objects[i].words.n; ++j) {
383 if (strncasecmp(word, objects[i].words.strs[j],
389 // If execution reaches here, we didn't find the word.
390 return (WORD_NOT_FOUND);
393 static int get_action_vocab_id(const char *word) {
394 // Return the first motion number that has 'word' as one of its words.
395 for (int i = 0; i < NACTIONS; ++i) {
396 for (int j = 0; j < actions[i].words.n; ++j) {
397 if (strncasecmp(word, actions[i].words.strs[j],
400 strchr(ignore, word[0]) == NULL ||
401 !settings.oldstyle)) {
406 // If execution reaches here, we didn't find the word.
407 return (WORD_NOT_FOUND);
410 static bool is_valid_int(const char *str) {
411 /* Returns true if the string passed in is represents a valid integer,
412 * that could then be parsed by atoi() */
413 // Handle negative number
418 // Handle empty string or just "-". Should never reach this
419 // point, because this is only used with transitive verbs.
421 return false; // LCOV_EXCL_LINE
424 // Check for non-digit chars in the rest of the string.
426 if (!isdigit(*str)) {
436 static void get_vocab_metadata(const char *word, vocab_t *id,
438 /* Check for an empty string */
439 if (strncmp(word, "", sizeof("")) == 0) {
441 *type = NO_WORD_TYPE;
447 ref_num = get_motion_vocab_id(word);
448 // Second conjunct is because the magic-word placeholder is a bit
450 if (ref_num != WORD_NOT_FOUND) {
456 ref_num = get_object_vocab_id(word);
457 if (ref_num != WORD_NOT_FOUND) {
463 ref_num = get_action_vocab_id(word);
464 if (ref_num != WORD_NOT_FOUND && ref_num != PART) {
470 // Check for the reservoir magic word.
471 if (strcasecmp(word, game.zzword) == 0) {
477 // Check words that are actually numbers.
478 if (is_valid_int(word)) {
484 *id = WORD_NOT_FOUND;
485 *type = NO_WORD_TYPE;
489 static void tokenize(char *raw, command_t *cmd) {
491 * Be careful about modifying this. We do not want to nuke the
492 * the speech part or ID from the previous turn.
494 memset(&cmd->word[0].raw, '\0', sizeof(cmd->word[0].raw));
495 memset(&cmd->word[1].raw, '\0', sizeof(cmd->word[1].raw));
497 /* Bound prefix on the %s would be needed to prevent buffer
498 * overflow. but we shortstop this more simply by making each
499 * raw-input buffer as int as the entire input buffer. */
500 sscanf(raw, "%s%s", cmd->word[0].raw, cmd->word[1].raw);
502 /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
503 * effect on raw tokens of packing them into sixbit characters, 5
504 * to a 32-bit word. This is something the FORTRAN version did
505 * because archaic FORTRAN had no string types. Don Wood's
506 * mechanical translation of 2.5 to C retained the packing and
507 * thus this misfeature.
509 * It's philosophically questionable whether this is the right
510 * thing to do even in oldstyle mode. On one hand, the text
511 * mangling was not authorial intent, but a result of limitations
512 * in their tools. On the other, not simulating this misbehavior
513 * goes against the goal of making oldstyle as accurate as
514 * possible an emulation of the original UI.
516 if (settings.oldstyle) {
517 cmd->word[0].raw[TOKLEN + TOKLEN] =
518 cmd->word[1].raw[TOKLEN + TOKLEN] = '\0';
519 for (size_t i = 0; i < strlen(cmd->word[0].raw); i++) {
520 cmd->word[0].raw[i] = toupper(cmd->word[0].raw[i]);
522 for (size_t i = 0; i < strlen(cmd->word[1].raw); i++) {
523 cmd->word[1].raw[i] = toupper(cmd->word[1].raw[i]);
527 /* populate command with parsed vocabulary metadata */
528 get_vocab_metadata(cmd->word[0].raw, &(cmd->word[0].id),
529 &(cmd->word[0].type));
530 get_vocab_metadata(cmd->word[1].raw, &(cmd->word[1].id),
531 &(cmd->word[1].type));
532 cmd->state = TOKENIZED;
535 bool get_command_input(command_t *command) {
536 /* Get user input on stdin, parse and map to command */
537 char inputbuf[LINESIZE];
545 if (word_count(input) > 2) {
550 if (strcmp(input, "") != 0) {
556 strncpy(inputbuf, input, LINESIZE - 1);
559 tokenize(inputbuf, command);
562 /* Needs to stay synced with enum word_type_t */
563 const char *types[] = {"NO_WORD_TYPE", "MOTION", "OBJECT", "ACTION",
565 /* needs to stay synced with enum speechpart */
566 const char *roles[] = {"unknown", "intransitive", "transitive"};
568 "Command: role = %s type1 = %s, id1 = %d, type2 = %s, id2 = %d\n",
569 roles[command->part], types[command->word[0].type],
570 command->word[0].id, types[command->word[1].type],
571 command->word[1].id);
574 command->state = GIVEN;
578 void clear_command(command_t *cmd) {
579 /* Resets the state of the command to empty */
580 cmd->verb = ACT_NULL;
582 game.oldobj = cmd->obj;
583 cmd->obj = NO_OBJECT;
587 void juggle(obj_t object) {
588 /* Juggle an object by picking it up and putting it down again, the
589 * purpose being to get the object to the front of the chain of things
593 i = game.objects[object].place;
594 j = game.objects[object].fixed;
596 move(object + NOBJECTS, j);
599 void move(obj_t object, loc_t where) {
600 /* Place any object anywhere by picking it up and dropping it. May
601 * already be toting, in which case the carry is a no-op. Mustn't
602 * pick up objects which are not at any loc, since carry wants to
603 * remove objects from game atloc chains. */
606 if (object > NOBJECTS) {
607 from = game.objects[object - NOBJECTS].fixed;
609 from = game.objects[object].place;
611 /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong...
613 if (from != LOC_NOWHERE && from != CARRIED) {
619 void put(obj_t object, loc_t where, int pval) {
620 /* put() is the same as move(), except it returns a value used to set
621 * up the negated game.prop values for the repository objects. */
623 /* (ESR) Read this in combination with the macro defintions in advebt.h.
625 game.objects[object].prop = PROP_STASHIFY(pval);
627 PROP_SET_SEEN(object);
631 void carry(obj_t object, loc_t where) {
632 /* Start toting an object, removing it from the list of things at its
633 * former location. Incr holdng unless it was already being toted. If
634 * object>NOBJECTS (moving "fixed" second loc), don't change game.place
638 if (object <= NOBJECTS) {
639 if (game.objects[object].place == CARRIED) {
642 game.objects[object].place = CARRIED;
645 * Without this conditional your inventory is overcounted
646 * when you pick up the bird while it's caged. This fixes
647 * a cosmetic bug in the original.
649 * Possibly this check should be skipped whwn oldstyle is on.
651 if (object != BIRD) {
655 if (game.locs[where].atloc == object) {
656 game.locs[where].atloc = game.link[object];
659 temp = game.locs[where].atloc;
660 while (game.link[temp] != object) {
661 temp = game.link[temp];
663 game.link[temp] = game.link[object];
666 void drop(obj_t object, loc_t where) {
667 /* Place an object at a given loc, prefixing it onto the game atloc
668 * list. Decr game.holdng if the object was being toted. No state
669 * change on the object. */
670 if (object > NOBJECTS) {
671 game.objects[object - NOBJECTS].fixed = where;
673 if (game.objects[object].place == CARRIED) {
674 if (object != BIRD) {
675 /* The bird has to be weightless. This ugly
676 * hack (and the corresponding code in the carry
677 * function) brought to you by the fact that
678 * when the bird is caged, we need to be able to
679 * either 'take bird' or 'take cage' and have
680 * the right thing happen.
685 game.objects[object].place = where;
687 if (where == LOC_NOWHERE || where == CARRIED) {
690 game.link[object] = game.locs[where].atloc;
691 game.locs[where].atloc = object;
694 int atdwrf(loc_t where) {
695 /* Return the index of first dwarf at the given location, zero if no
696 * dwarf is there (or if dwarves not active yet), -1 if all dwarves are
697 * dead. Ignore the pirate (6th dwarf). */
701 if (game.dflag < 2) {
705 for (int i = 1; i <= NDWARVES - 1; i++) {
706 if (game.dwarves[i].loc == where) {
709 if (game.dwarves[i].loc != 0) {
716 /* Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
719 int setbit(int bit) {
720 /* Returns 2**bit for use in constructing bit-masks. */
724 bool tstbit(int mask, int bit) {
725 /* Returns true if the specified bit is set in the mask. */
726 return (mask & (1 << bit)) != 0;
729 void set_seed(int32_t seedval) {
730 /* Set the LCG1 seed */
731 game.lcg_x = seedval % LCG_M;
732 if (game.lcg_x < 0) {
733 game.lcg_x = LCG_M + game.lcg_x;
735 // once seed is set, we need to generate the Z`ZZZ word
736 for (int i = 0; i < 5; ++i) {
737 game.zzword[i] = 'A' + randrange(26);
739 game.zzword[1] = '\''; // force second char to apostrophe
740 game.zzword[5] = '\0';
743 static int32_t get_next_lcg_value(void) {
744 /* Return the LCG's current value, and then iterate it. */
745 int32_t old_x = game.lcg_x;
746 game.lcg_x = (LCG_A * game.lcg_x + LCG_C) % LCG_M;
747 if (settings.debug) {
748 printf("# random %d\n", old_x); // LCOV_EXCL_LINE
753 int32_t randrange(int32_t range) {
754 /* Return a random integer from [0, range). */
755 return range * get_next_lcg_value() / LCG_M;
759 void bug(enum bugtype num, const char *error_string) {
760 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
765 void state_change(obj_t obj, int state) {
766 /* Object must have a change-message list for this to be useful; only
768 game.objects[obj].prop = state;
769 pspeak(obj, change, true, state);