2 * I/O and support routines.
4 * Copyright (c) 1977, 2005 by Will Crowther and Don Woods
5 * Copyright (c) 2017 by Eric S. Raymond
6 * SPDX-License-Identifier: BSD-2-clause
16 #include <editline/readline.h>
22 static void* xcalloc(size_t size)
24 void* ptr = calloc(size, 1);
27 // exclude from coverage analysis because we can't simulate an out of memory error in testing
28 fprintf(stderr, "Out of memory!\n");
35 /* I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
37 static void vspeak(const char* msg, bool blank, va_list ap)
38 /* Engine for various speak functions */
40 // Do nothing if we got a null pointer.
44 // Do nothing if we got an empty string.
51 int msglen = strlen(msg);
54 ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
55 char* rendered = xcalloc(size);
56 char* renderp = rendered;
58 // Handle format specifiers (including the custom %S) by
59 // adjusting the parameter accordingly, and replacing the
61 bool pluralize = false;
62 for (int i = 0; i < msglen; i++) {
64 /* Ugh. Least obtrusive way to deal with artifacts "on the floor"
65 * being dropped outside of both cave and building. */
66 if (strncmp(msg + i, "floor", 5) == 0 && strchr(" .", msg[i + 5]) && !INSIDE(game.loc)) {
67 strcpy(renderp, "ground");
79 int32_t arg = va_arg(ap, int32_t);
80 int ret = snprintf(renderp, size, "%" PRId32, arg);
85 pluralize = (arg != 1);
88 // Unmodified string specifier.
90 char *arg = va_arg(ap, char *);
91 strncat(renderp, arg, size - 1);
92 size_t len = strlen(renderp);
97 // Singular/plural specifier.
99 // look at the *previous* numeric parameter
106 // LCOV_EXCL_START - doesn't occur in test suite.
107 /* Version specifier */
109 strcpy(renderp, VERSION);
110 size_t len = strlen(VERSION);
119 // Print the message.
120 printf("%s\n", rendered);
125 void speak(const char* msg, ...)
126 /* speak a specified string */
130 vspeak(msg, true, ap);
134 void sspeak(const int msg, ...)
135 /* Speak a message from the arbitrary-messages list */
140 vprintf(arbitrary_messages[msg], ap);
145 void pspeak(vocab_t msg, enum speaktype mode, bool blank, int skip, ...)
146 /* Find the skip+1st message from msg and print it. Modes are:
147 * feel = for inventory, what you can touch
148 * look = the full description for the state the object is in
149 * listen = the sound for the state the object is in
150 * study = text on the object. */
156 vspeak(objects[msg].inventory, blank, ap);
159 vspeak(objects[msg].descriptions[skip], blank, ap);
162 vspeak(objects[msg].sounds[skip], blank, ap);
165 vspeak(objects[msg].texts[skip], blank, ap);
168 vspeak(objects[msg].changes[skip], blank, ap);
174 void rspeak(vocab_t i, ...)
175 /* 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, const char* input)
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)
195 char delims[] = " \t";
199 for (char *s = str; *s; s++)
201 if (strchr(delims, *s) == 0) {
206 if (strchr(delims, *s) != 0) {
214 static char* get_input(void)
217 char input_prompt[] = PROMPT;
218 if (!settings.prompt)
219 input_prompt[0] = '\0';
221 // Print a blank line
226 input = myreadline(input_prompt);
228 if (input == NULL) // Got EOF; return with it.
230 if (input[0] == '#') { // Ignore comments.
234 // We have a 'normal' line; leave the loop.
238 // Strip trailing newlines from the input
239 input[strcspn(input, "\n")] = 0;
244 echo_input(stdout, input_prompt, input);
247 echo_input(settings.logfp, "", input);
252 bool silent_yes_or_no(void)
254 bool outcome = false;
257 char* reply = get_input();
260 // Should be unreachable. Reply should never be NULL
265 if (strlen(reply) == 0) {
267 rspeak(PLEASE_ANSWER);
271 char* firstword = (char*) xcalloc(strlen(reply) + 1);
272 sscanf(reply, "%s", firstword);
276 for (int i = 0; i < (int)strlen(firstword); ++i)
277 firstword[i] = tolower(firstword[i]);
279 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
280 int y = strncmp("y", firstword, sizeof("y") - 1);
281 int no = strncmp("no", firstword, sizeof("no") - 1);
282 int n = strncmp("n", firstword, sizeof("n") - 1);
286 if (yes == 0 || y == 0) {
289 } else if (no == 0 || n == 0) {
293 rspeak(PLEASE_ANSWER);
299 bool yes_or_no(const char* question, const char* yes_response, const char* no_response)
300 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
301 * if no, print Z and return false. */
303 bool outcome = false;
308 char* reply = get_input();
311 // Should be unreachable. Reply should never be NULL
317 if (strlen(reply) == 0) {
319 rspeak(PLEASE_ANSWER);
323 char* firstword = (char*) xcalloc(strlen(reply) + 1);
324 sscanf(reply, "%s", firstword);
328 for (int i = 0; i < (int)strlen(firstword); ++i)
329 firstword[i] = tolower(firstword[i]);
331 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
332 int y = strncmp("y", firstword, sizeof("y") - 1);
333 int no = strncmp("no", firstword, sizeof("no") - 1);
334 int n = strncmp("n", firstword, sizeof("n") - 1);
343 } else if (no == 0 ||
349 rspeak(PLEASE_ANSWER);
356 /* Data structure routines */
358 static int get_motion_vocab_id(const char* word)
359 // Return the first motion number that has 'word' as one of its words.
361 for (int i = 0; i < NMOTIONS; ++i) {
362 for (int j = 0; j < motions[i].words.n; ++j) {
363 if (strncasecmp(word, motions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
364 strchr(ignore, word[0]) == NULL ||
369 // If execution reaches here, we didn't find the word.
370 return (WORD_NOT_FOUND);
373 static int get_object_vocab_id(const char* word)
374 // Return the first object number that has 'word' as one of its words.
376 for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
377 for (int j = 0; j < objects[i].words.n; ++j) {
378 if (strncasecmp(word, objects[i].words.strs[j], TOKLEN) == 0)
382 // If execution reaches here, we didn't find the word.
383 return (WORD_NOT_FOUND);
386 static int get_action_vocab_id(const char* word)
387 // Return the first motion number that has 'word' as one of its words.
389 for (int i = 0; i < NACTIONS; ++i) {
390 for (int j = 0; j < actions[i].words.n; ++j) {
391 if (strncasecmp(word, actions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
392 strchr(ignore, word[0]) == NULL ||
397 // If execution reaches here, we didn't find the word.
398 return (WORD_NOT_FOUND);
401 static bool is_valid_int(const char *str)
402 /* Returns true if the string passed in is represents a valid integer,
403 * that could then be parsed by atoi() */
405 // Handle negative number
409 // Handle empty string or just "-". Should never reach this
410 // point, because this is only used with transitive verbs.
412 return false; // LCOV_EXCL_LINE
414 // Check for non-digit chars in the rest of the string.
425 static void get_vocab_metadata(const char* word, vocab_t* id, word_type_t* type)
427 /* Check for an empty string */
428 if (strncmp(word, "", sizeof("")) == 0) {
430 *type = NO_WORD_TYPE;
436 ref_num = get_motion_vocab_id(word);
437 if (ref_num != WORD_NOT_FOUND) {
443 ref_num = get_object_vocab_id(word);
444 if (ref_num != WORD_NOT_FOUND) {
450 ref_num = get_action_vocab_id(word);
451 if (ref_num != WORD_NOT_FOUND) {
457 // Check for the reservoir magic word.
458 if (strcasecmp(word, game.zzword) == 0) {
464 // Check words that are actually numbers.
465 if (is_valid_int(word)) {
471 *id = WORD_NOT_FOUND;
472 *type = NO_WORD_TYPE;
476 static void tokenize(char* raw, command_t *cmd)
479 * Be careful about modifying this. We do not want to nuke the
480 * the speech part or ID from the previous turn.
482 memset(&cmd->word[0].raw, '\0', sizeof(cmd->word[0].raw));
483 memset(&cmd->word[1].raw, '\0', sizeof(cmd->word[1].raw));
485 /* Bound prefix on the %s would be needed to prevent buffer
486 * overflow. but we shortstop this more simply by making each
487 * raw-input buffer as int as the entire input buffer. */
488 sscanf(raw, "%s%s", cmd->word[0].raw, cmd->word[1].raw);
490 /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
491 * effect on raw tokens of packing them into sixbit characters, 5
492 * to a 32-bit word. This is something the FORTRAN version did
493 * because archaic FORTRAN had no string types. Don Wood's
494 * mechanical translation of 2.5 to C retained the packing and
495 * thus this misfeature.
497 * It's philosophically questionable whether this is the right
498 * thing to do even in oldstyle mode. On one hand, the text
499 * mangling was not authorial intent, but a result of limitations
500 * in their tools. On the other, not simulating this misbehavior
501 * goes against the goal of making oldstyle as accurate as
502 * possible an emulation of the original UI.
504 if (settings.oldstyle) {
505 cmd->word[0].raw[TOKLEN + TOKLEN] = cmd->word[1].raw[TOKLEN + TOKLEN] = '\0';
506 for (size_t i = 0; i < strlen(cmd->word[0].raw); i++)
507 cmd->word[0].raw[i] = toupper(cmd->word[0].raw[i]);
508 for (size_t i = 0; i < strlen(cmd->word[1].raw); i++)
509 cmd->word[1].raw[i] = toupper(cmd->word[1].raw[i]);
512 /* populate command with parsed vocabulary metadata */
513 get_vocab_metadata(cmd->word[0].raw, &(cmd->word[0].id), &(cmd->word[0].type));
514 get_vocab_metadata(cmd->word[1].raw, &(cmd->word[1].id), &(cmd->word[1].type));
515 cmd->state = TOKENIZED;
518 bool get_command_input(command_t *command)
519 /* Get user input on stdin, parse and map to command */
521 char inputbuf[LINESIZE];
528 if (word_count(input) > 2) {
533 if (strcmp(input, "") != 0)
538 strncpy(inputbuf, input, LINESIZE - 1);
541 tokenize(inputbuf, command);
544 /* Needs to stay synced with enum word_type_t */
545 const char *types[] = {"NO_WORD_TYPE", "MOTION", "OBJECT", "ACTION", "NUMERIC"};
546 /* needs to stay synced with enum speechpart */
547 const char *roles[] = {"unknown", "intransitive", "transitive"};
548 printf("Command: role = %s type1 = %s, id1 = %d, type2 = %s, id2 = %d\n",
549 roles[command->part],
550 types[command->word[0].type],
552 types[command->word[1].type],
553 command->word[1].id);
556 command->state = GIVEN;
560 void clear_command(command_t *cmd)
561 /* Resets the state of the command to empty */
563 cmd->verb = ACT_NULL;
565 game.oldobj = cmd->obj;
566 cmd->obj = NO_OBJECT;
570 void juggle(obj_t object)
571 /* Juggle an object by picking it up and putting it down again, the purpose
572 * being to get the object to the front of the chain of things at its loc. */
576 i = game.place[object];
577 j = game.fixed[object];
579 move(object + NOBJECTS, j);
582 void move(obj_t object, loc_t where)
583 /* Place any object anywhere by picking it up and dropping it. May
584 * already be toting, in which case the carry is a no-op. Mustn't
585 * pick up objects which are not at any loc, since carry wants to
586 * remove objects from game.atloc chains. */
590 if (object > NOBJECTS)
591 from = game.fixed[object - NOBJECTS];
593 from = game.place[object];
594 /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong... */
595 if (from != LOC_NOWHERE && from != CARRIED)
600 loc_t put(obj_t object, loc_t where, int pval)
601 /* put() is the same as move(), except it returns a value used to set up the
602 * negated game.prop values for the repository objects. */
605 return STASHED(pval);
608 void carry(obj_t object, loc_t where)
609 /* Start toting an object, removing it from the list of things at its former
610 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
611 * (moving "fixed" second loc), don't change game.place or game.holdng. */
615 if (object <= NOBJECTS) {
616 if (game.place[object] == CARRIED)
618 game.place[object] = CARRIED;
623 if (game.atloc[where] == object) {
624 game.atloc[where] = game.link[object];
627 temp = game.atloc[where];
628 while (game.link[temp] != object) {
629 temp = game.link[temp];
631 game.link[temp] = game.link[object];
634 void drop(obj_t object, loc_t where)
635 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
636 * game.holdng if the object was being toted. No state change on the object. */
638 if (object > NOBJECTS)
639 game.fixed[object - NOBJECTS] = where;
641 if (game.place[object] == CARRIED)
643 /* The bird has to be weightless. This ugly hack (and the
644 * corresponding code in the drop function) brought to you
645 * by the fact that when the bird is caged, we need to be able
646 * to either 'take bird' or 'take cage' and have the right thing
650 game.place[object] = where;
652 if (where == LOC_NOWHERE ||
655 game.link[object] = game.atloc[where];
656 game.atloc[where] = object;
659 int atdwrf(loc_t where)
660 /* Return the index of first dwarf at the given location, zero if no dwarf is
661 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
662 * the pirate (6th dwarf). */
670 for (int i = 1; i <= NDWARVES - 1; i++) {
671 if (game.dloc[i] == where)
673 if (game.dloc[i] != 0)
679 /* Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
683 /* Returns 2**bit for use in constructing bit-masks. */
688 bool tstbit(int mask, int bit)
689 /* Returns true if the specified bit is set in the mask. */
691 return (mask & (1 << bit)) != 0;
694 void set_seed(int32_t seedval)
695 /* Set the LCG seed */
697 game.lcg_x = seedval % LCG_M;
698 if (game.lcg_x < 0) {
699 game.lcg_x = LCG_M + game.lcg_x;
701 // once seed is set, we need to generate the Z`ZZZ word
702 for (int i = 0; i < 5; ++i) {
703 game.zzword[i] = 'A' + randrange(26);
705 game.zzword[1] = '\''; // force second char to apostrophe
706 game.zzword[5] = '\0';
709 static int32_t get_next_lcg_value(void)
710 /* Return the LCG's current value, and then iterate it. */
712 int32_t old_x = game.lcg_x;
713 game.lcg_x = (LCG_A * game.lcg_x + LCG_C) % LCG_M;
717 int32_t randrange(int32_t range)
718 /* Return a random integer from [0, range). */
720 return range * get_next_lcg_value() / LCG_M;
724 void bug(enum bugtype num, const char *error_string)
726 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
731 void state_change(obj_t obj, int state)
732 /* Object must have a change-message list for this to be useful; only some do */
734 game.prop[obj] = state;
735 pspeak(obj, change, true, state);