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) {
213 static char *get_input(void) {
215 char input_prompt[] = PROMPT;
216 if (!settings.prompt)
217 input_prompt[0] = '\0';
219 // Print a blank line
224 input = myreadline(input_prompt);
226 if (input == NULL) // Got EOF; return with it.
228 if (input[0] == '#') { // Ignore comments.
232 // We have a 'normal' line; leave the loop.
236 // Strip trailing newlines from the input
237 input[strcspn(input, "\n")] = 0;
242 echo_input(stdout, input_prompt, input);
245 echo_input(settings.logfp, "", input);
250 bool silent_yes_or_no(void) {
251 bool outcome = false;
254 char *reply = get_input();
257 // Should be unreachable. Reply should never be NULL
262 if (strlen(reply) == 0) {
264 rspeak(PLEASE_ANSWER);
268 char *firstword = (char *)xcalloc(strlen(reply) + 1);
269 sscanf(reply, "%s", firstword);
273 for (int i = 0; i < (int)strlen(firstword); ++i)
274 firstword[i] = tolower(firstword[i]);
276 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
277 int y = strncmp("y", firstword, sizeof("y") - 1);
278 int no = strncmp("no", firstword, sizeof("no") - 1);
279 int n = strncmp("n", firstword, sizeof("n") - 1);
283 if (yes == 0 || y == 0) {
286 } else if (no == 0 || n == 0) {
290 rspeak(PLEASE_ANSWER);
295 bool yes_or_no(const char *question, const char *yes_response,
296 const char *no_response) {
297 /* Print message X, wait for yes/no answer. If yes, print Y and return
298 * true; if no, print Z and return false. */
299 bool outcome = false;
304 char *reply = get_input();
307 // Should be unreachable. Reply should never be NULL
313 if (strlen(reply) == 0) {
315 rspeak(PLEASE_ANSWER);
319 char *firstword = (char *)xcalloc(strlen(reply) + 1);
320 sscanf(reply, "%s", firstword);
324 for (int i = 0; i < (int)strlen(firstword); ++i) {
325 firstword[i] = tolower(firstword[i]);
328 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
329 int y = strncmp("y", firstword, sizeof("y") - 1);
330 int no = strncmp("no", firstword, sizeof("no") - 1);
331 int n = strncmp("n", firstword, sizeof("n") - 1);
335 if (yes == 0 || y == 0) {
339 } else if (no == 0 || n == 0) {
344 rspeak(PLEASE_ANSWER);
350 /* Data structure routines */
352 static int get_motion_vocab_id(const char *word) {
353 // Return the first motion number that has 'word' as one of its words.
354 for (int i = 0; i < NMOTIONS; ++i) {
355 for (int j = 0; j < motions[i].words.n; ++j) {
356 if (strncasecmp(word, motions[i].words.strs[j],
359 strchr(ignore, word[0]) == NULL ||
364 // If execution reaches here, we didn't find the word.
365 return (WORD_NOT_FOUND);
368 static int get_object_vocab_id(const char *word) {
369 // Return the first object number that has 'word' as one of its words.
370 for (int i = 0; i < NOBJECTS + 1;
371 ++i) { // FIXME: the + 1 should go when 1-indexing for objects is
373 for (int j = 0; j < objects[i].words.n; ++j) {
374 if (strncasecmp(word, objects[i].words.strs[j],
379 // If execution reaches here, we didn't find the word.
380 return (WORD_NOT_FOUND);
383 static int get_action_vocab_id(const char *word) {
384 // Return the first motion number that has 'word' as one of its words.
385 for (int i = 0; i < NACTIONS; ++i) {
386 for (int j = 0; j < actions[i].words.n; ++j) {
387 if (strncasecmp(word, actions[i].words.strs[j],
390 strchr(ignore, word[0]) == NULL ||
391 !settings.oldstyle)) {
396 // If execution reaches here, we didn't find the word.
397 return (WORD_NOT_FOUND);
400 static bool is_valid_int(const char *str) {
401 /* Returns true if the string passed in is represents a valid integer,
402 * that could then be parsed by atoi() */
403 // Handle negative number
408 // Handle empty string or just "-". Should never reach this
409 // point, because this is only used with transitive verbs.
411 return false; // LCOV_EXCL_LINE
414 // Check for non-digit chars in the rest of the string.
416 if (!isdigit(*str)) {
426 static void get_vocab_metadata(const char *word, vocab_t *id,
428 /* Check for an empty string */
429 if (strncmp(word, "", sizeof("")) == 0) {
431 *type = NO_WORD_TYPE;
437 ref_num = get_motion_vocab_id(word);
438 // Second conjunct is because the magic-word placeholder is a bit
440 if (ref_num != WORD_NOT_FOUND) {
446 ref_num = get_object_vocab_id(word);
447 if (ref_num != WORD_NOT_FOUND) {
453 ref_num = get_action_vocab_id(word);
454 if (ref_num != WORD_NOT_FOUND && ref_num != PART) {
460 // Check for the reservoir magic word.
461 if (strcasecmp(word, game.zzword) == 0) {
467 // Check words that are actually numbers.
468 if (is_valid_int(word)) {
474 *id = WORD_NOT_FOUND;
475 *type = NO_WORD_TYPE;
479 static void tokenize(char *raw, command_t *cmd) {
481 * Be careful about modifying this. We do not want to nuke the
482 * the speech part or ID from the previous turn.
484 memset(&cmd->word[0].raw, '\0', sizeof(cmd->word[0].raw));
485 memset(&cmd->word[1].raw, '\0', sizeof(cmd->word[1].raw));
487 /* Bound prefix on the %s would be needed to prevent buffer
488 * overflow. but we shortstop this more simply by making each
489 * raw-input buffer as int as the entire input buffer. */
490 sscanf(raw, "%s%s", cmd->word[0].raw, cmd->word[1].raw);
492 /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
493 * effect on raw tokens of packing them into sixbit characters, 5
494 * to a 32-bit word. This is something the FORTRAN version did
495 * because archaic FORTRAN had no string types. Don Wood's
496 * mechanical translation of 2.5 to C retained the packing and
497 * thus this misfeature.
499 * It's philosophically questionable whether this is the right
500 * thing to do even in oldstyle mode. On one hand, the text
501 * mangling was not authorial intent, but a result of limitations
502 * in their tools. On the other, not simulating this misbehavior
503 * goes against the goal of making oldstyle as accurate as
504 * possible an emulation of the original UI.
506 if (settings.oldstyle) {
507 cmd->word[0].raw[TOKLEN + TOKLEN] =
508 cmd->word[1].raw[TOKLEN + TOKLEN] = '\0';
509 for (size_t i = 0; i < strlen(cmd->word[0].raw); i++) {
510 cmd->word[0].raw[i] = toupper(cmd->word[0].raw[i]);
512 for (size_t i = 0; i < strlen(cmd->word[1].raw); i++) {
513 cmd->word[1].raw[i] = toupper(cmd->word[1].raw[i]);
517 /* populate command with parsed vocabulary metadata */
518 get_vocab_metadata(cmd->word[0].raw, &(cmd->word[0].id),
519 &(cmd->word[0].type));
520 get_vocab_metadata(cmd->word[1].raw, &(cmd->word[1].id),
521 &(cmd->word[1].type));
522 cmd->state = TOKENIZED;
525 bool get_command_input(command_t *command) {
526 /* Get user input on stdin, parse and map to command */
527 char inputbuf[LINESIZE];
534 if (word_count(input) > 2) {
539 if (strcmp(input, "") != 0) {
545 strncpy(inputbuf, input, LINESIZE - 1);
548 tokenize(inputbuf, command);
551 /* Needs to stay synced with enum word_type_t */
552 const char *types[] = {"NO_WORD_TYPE", "MOTION", "OBJECT", "ACTION",
554 /* needs to stay synced with enum speechpart */
555 const char *roles[] = {"unknown", "intransitive", "transitive"};
557 "Command: role = %s type1 = %s, id1 = %d, type2 = %s, id2 = %d\n",
558 roles[command->part], types[command->word[0].type],
559 command->word[0].id, types[command->word[1].type],
560 command->word[1].id);
563 command->state = GIVEN;
567 void clear_command(command_t *cmd) {
568 /* Resets the state of the command to empty */
569 cmd->verb = ACT_NULL;
571 game.oldobj = cmd->obj;
572 cmd->obj = NO_OBJECT;
576 void juggle(obj_t object) {
577 /* Juggle an object by picking it up and putting it down again, the
578 * purpose being to get the object to the front of the chain of things
582 i = game.objects[object].place;
583 j = game.objects[object].fixed;
585 move(object + NOBJECTS, j);
588 void move(obj_t object, loc_t where) {
589 /* Place any object anywhere by picking it up and dropping it. May
590 * already be toting, in which case the carry is a no-op. Mustn't
591 * pick up objects which are not at any loc, since carry wants to
592 * remove objects from game atloc chains. */
595 if (object > NOBJECTS) {
596 from = game.objects[object - NOBJECTS].fixed;
598 from = game.objects[object].place;
600 /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong...
602 if (from != LOC_NOWHERE && from != CARRIED) {
608 void put(obj_t object, loc_t where, int pval) {
609 /* put() is the same as move(), except it returns a value used to set
610 * up the negated game.prop values for the repository objects. */
612 /* (ESR) Read this in combination with the macro defintions in advebt.h.
614 game.objects[object].prop = PROP_STASHIFY(pval);
616 PROP_SET_SEEN(object);
620 void carry(obj_t object, loc_t where) {
621 /* Start toting an object, removing it from the list of things at its
622 * former location. Incr holdng unless it was already being toted. If
623 * object>NOBJECTS (moving "fixed" second loc), don't change game.place
627 if (object <= NOBJECTS) {
628 if (game.objects[object].place == CARRIED) {
631 game.objects[object].place = CARRIED;
634 * Without this conditional your inventory is overcounted
635 * when you pick up the bird while it's caged. This fixes
636 * a cosmetic bug in the original.
638 * Possibly this check should be skipped whwn oldstyle is on.
643 if (game.locs[where].atloc == object) {
644 game.locs[where].atloc = game.link[object];
647 temp = game.locs[where].atloc;
648 while (game.link[temp] != object) {
649 temp = game.link[temp];
651 game.link[temp] = game.link[object];
654 void drop(obj_t object, loc_t where) {
655 /* Place an object at a given loc, prefixing it onto the game atloc
656 * list. Decr game.holdng if the object was being toted. No state
657 * change on the object. */
658 if (object > NOBJECTS) {
659 game.objects[object - NOBJECTS].fixed = where;
661 if (game.objects[object].place == CARRIED)
663 /* The bird has to be weightless. This ugly
664 * hack (and the corresponding code in the carry
665 * function) brought to you by the fact that
666 * when the bird is caged, we need to be able to
667 * either 'take bird' or 'take cage' and have
668 * the right thing happen.
671 game.objects[object].place = where;
673 if (where == LOC_NOWHERE || where == CARRIED) {
676 game.link[object] = game.locs[where].atloc;
677 game.locs[where].atloc = object;
680 int atdwrf(loc_t where) {
681 /* Return the index of first dwarf at the given location, zero if no
682 * dwarf is there (or if dwarves not active yet), -1 if all dwarves are
683 * dead. Ignore the pirate (6th dwarf). */
687 if (game.dflag < 2) {
691 for (int i = 1; i <= NDWARVES - 1; i++) {
692 if (game.dwarves[i].loc == where) {
695 if (game.dwarves[i].loc != 0) {
702 /* Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
705 int setbit(int bit) {
706 /* Returns 2**bit for use in constructing bit-masks. */
710 bool tstbit(int mask, int bit) {
711 /* Returns true if the specified bit is set in the mask. */
712 return (mask & (1 << bit)) != 0;
715 void set_seed(int32_t seedval) {
716 /* Set the LCG1 seed */
717 game.lcg_x = seedval % LCG_M;
718 if (game.lcg_x < 0) {
719 game.lcg_x = LCG_M + game.lcg_x;
721 // once seed is set, we need to generate the Z`ZZZ word
722 for (int i = 0; i < 5; ++i) {
723 game.zzword[i] = 'A' + randrange(26);
725 game.zzword[1] = '\''; // force second char to apostrophe
726 game.zzword[5] = '\0';
729 static int32_t get_next_lcg_value(void) {
730 /* Return the LCG's current value, and then iterate it. */
731 int32_t old_x = game.lcg_x;
732 game.lcg_x = (LCG_A * game.lcg_x + LCG_C) % LCG_M;
733 if (settings.debug) {
734 printf("# random %d\n", old_x); // LCOV_EXCL_LINE
739 int32_t randrange(int32_t range) {
740 /* Return a random integer from [0, range). */
741 return range * get_next_lcg_value() / LCG_M;
745 void bug(enum bugtype num, const char *error_string) {
746 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
751 void state_change(obj_t obj, int state) {
752 /* Object must have a change-message list for this to be useful; only
754 game.objects[obj].prop = state;
755 pspeak(obj, change, true, state);