2 * I/O and support riutines.
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)
39 // Do nothing if we got a null pointer.
43 // Do nothing if we got an empty string.
50 int msglen = strlen(msg);
53 ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
54 char* rendered = xcalloc(size);
55 char* renderp = rendered;
57 // Handle format specifiers (including the custom %S) by
58 // adjusting the parameter accordingly, and replacing the
60 bool pluralize = false;
61 for (int i = 0; i < msglen; i++) {
63 /* Ugh. Least obtrusive way to deal with artifacts "on the floor"
64 * being dropped outside of both cave and building. */
65 if (strncmp(msg + i, "floor", 5) == 0 && strchr(" .", msg[i + 5]) && !INSIDE(game.loc)) {
66 strcpy(renderp, "ground");
78 int32_t arg = va_arg(ap, int32_t);
79 int ret = snprintf(renderp, size, "%" PRId32, arg);
84 pluralize = (arg != 1);
87 // Unmodified string specifier.
89 char *arg = va_arg(ap, char *);
90 strncat(renderp, arg, size - 1);
91 size_t len = strlen(renderp);
96 // Singular/plural specifier.
98 // look at the *previous* numeric parameter
105 // LCOV_EXCL_START - doesn't occur in test suite.
106 /* Version specifier */
108 strcpy(renderp, VERSION);
109 size_t len = strlen(VERSION);
118 // Print the message.
119 printf("%s\n", rendered);
124 void speak(const char* msg, ...)
128 vspeak(msg, true, ap);
132 void sspeak(const int msg, ...)
137 vprintf(arbitrary_messages[msg], ap);
142 void pspeak(vocab_t msg, enum speaktype mode, int skip, bool blank, ...)
143 /* Find the skip+1st message from msg and print it. Modes are:
144 * feel = for inventory, what you can touch
145 * look = the full description for the state the object is in
146 * listen = the sound for the state the object is in
147 * study = text on the object. */
153 vspeak(objects[msg].inventory, blank, ap);
156 vspeak(objects[msg].descriptions[skip], blank, ap);
159 vspeak(objects[msg].sounds[skip], blank, ap);
162 vspeak(objects[msg].texts[skip], blank, ap);
165 vspeak(objects[msg].changes[skip], blank, ap);
171 void rspeak(vocab_t i, ...)
172 /* Print the i-th "random" message (section 6 of database). */
176 vspeak(arbitrary_messages[i], true, ap);
180 void echo_input(FILE* destination, const char* input_prompt, const char* input)
182 size_t len = strlen(input_prompt) + strlen(input) + 1;
183 char* prompt_and_input = (char*) xcalloc(len);
184 strcpy(prompt_and_input, input_prompt);
185 strcat(prompt_and_input, input);
186 fprintf(destination, "%s\n", prompt_and_input);
187 free(prompt_and_input);
190 static int word_count(char* str)
192 char delims[] = " \t";
196 for (char *s = str; *s; s++)
198 if (strchr(delims, *s) == 0) {
203 if (strchr(delims, *s) != 0) {
211 static char* get_input(void)
214 char input_prompt[] = "> ";
215 if (!settings.prompt)
216 input_prompt[0] = '\0';
218 // Print a blank line
223 input = readline(input_prompt);
225 if (input == NULL) // Got EOF; return with it.
227 if (input[0] == '#') { // Ignore comments.
231 // We have a 'normal' line; leave the loop.
235 // Strip trailing newlines from the input
236 input[strcspn(input, "\n")] = 0;
241 echo_input(stdout, input_prompt, input);
244 echo_input(settings.logfp, "", input);
249 bool silent_yes(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);
287 } else if (no == 0 ||
292 rspeak(PLEASE_ANSWER);
298 bool yes(const char* question, const char* yes_response, const char* no_response)
299 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
300 * if no, print Z and return false. */
302 bool outcome = false;
307 char* reply = get_input();
310 // Should be unreachable. Reply should never be NULL
316 if (strlen(reply) == 0) {
318 rspeak(PLEASE_ANSWER);
322 char* firstword = (char*) xcalloc(strlen(reply) + 1);
323 sscanf(reply, "%s", firstword);
327 for (int i = 0; i < (int)strlen(firstword); ++i)
328 firstword[i] = tolower(firstword[i]);
330 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
331 int y = strncmp("y", firstword, sizeof("y") - 1);
332 int no = strncmp("no", firstword, sizeof("no") - 1);
333 int n = strncmp("n", firstword, sizeof("n") - 1);
342 } else if (no == 0 ||
348 rspeak(PLEASE_ANSWER);
355 /* Data structure routines */
357 static int get_motion_vocab_id(const char* word)
358 // Return the first motion number that has 'word' as one of its words.
360 for (int i = 0; i < NMOTIONS; ++i) {
361 for (int j = 0; j < motions[i].words.n; ++j) {
362 if (strncasecmp(word, motions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
363 strchr(ignore, word[0]) == NULL ||
368 // If execution reaches here, we didn't find the word.
369 return (WORD_NOT_FOUND);
372 static int get_object_vocab_id(const char* word)
373 // Return the first object number that has 'word' as one of its words.
375 for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
376 for (int j = 0; j < objects[i].words.n; ++j) {
377 if (strncasecmp(word, objects[i].words.strs[j], TOKLEN) == 0)
381 // If execution reaches here, we didn't find the word.
382 return (WORD_NOT_FOUND);
385 static int get_action_vocab_id(const char* word)
386 // Return the first motion number that has 'word' as one of its words.
388 for (int i = 0; i < NACTIONS; ++i) {
389 for (int j = 0; j < actions[i].words.n; ++j) {
390 if (strncasecmp(word, actions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
391 strchr(ignore, word[0]) == NULL ||
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() */
404 // 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
413 // Check for non-digit chars in the rest of the stirng.
424 static void get_vocab_metadata(command_word_t* word)
426 /* Check for an empty string */
427 if (strncmp(word->raw, "", sizeof("")) == 0) {
428 word->id = WORD_EMPTY;
429 word->type = NO_WORD_TYPE;
435 ref_num = get_motion_vocab_id(word->raw);
436 if (ref_num != WORD_NOT_FOUND) {
442 ref_num = get_object_vocab_id(word->raw);
443 if (ref_num != WORD_NOT_FOUND) {
449 ref_num = get_action_vocab_id(word->raw);
450 if (ref_num != WORD_NOT_FOUND) {
456 // Check for the reservoir magic word.
457 if (strcasecmp(word->raw, game.zzword) == 0) {
463 // Check words that are actually numbers.
464 if (is_valid_int(word->raw)) {
465 word->id = WORD_EMPTY;
466 word->type = NUMERIC;
470 word->id = WORD_NOT_FOUND;
471 word->type = NO_WORD_TYPE;
475 static void tokenize(char* raw, command_t *cmd)
477 memset(cmd, '\0', sizeof(command_t));
479 /* Bound prefix on the %s would be needed to prevent buffer
480 * overflow. but we shortstop this more simply by making each
481 * raw-input buffer as long as the entire input buffer. */
482 sscanf(raw, "%s%s", cmd->word[0].raw, cmd->word[1].raw);
484 /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
485 * effect on raw tokens of packing them into sixbit characters, 5
486 * to a 32-bit word. This is something the FORTRAN version did
487 * becuse archaic FORTRAN had no string types. Don Wood's
488 * mechanical translation of 2.5 to C retained the packing and
489 * thus this misfeature.
491 * It's philosophically questionable whether this is the right
492 * thing to do even in oldstyle mode. On one hand, the text
493 * mangling was not authorial intent, but a result of limitations
494 * in their tools. On the other, not simulating this misbehavior
495 * goes against the goal of making oldstyle as accurate as
496 * possible an emulation of the original UI.
498 if (settings.oldstyle) {
499 cmd->word[0].raw[TOKLEN + TOKLEN] = cmd->word[1].raw[TOKLEN + TOKLEN] = '\0';
500 for (size_t i = 0; i < strlen(cmd->word[0].raw); i++)
501 cmd->word[0].raw[i] = toupper(cmd->word[0].raw[i]);
502 for (size_t i = 0; i < strlen(cmd->word[1].raw); i++)
503 cmd->word[1].raw[i] = toupper(cmd->word[1].raw[i]);
506 /* populate command with parsed vocabulary metadata */
507 get_vocab_metadata(&(cmd->word[0]));
508 get_vocab_metadata(&(cmd->word[1]));
511 bool get_command_input(command_t *command)
512 /* Get user input on stdin, parse and map to command */
514 char inputbuf[LINESIZE];
521 if (word_count(input) > 2) {
526 if (strcmp(input, "") != 0)
531 strncpy(inputbuf, input, LINESIZE - 1);
534 tokenize(inputbuf, command);
539 void juggle(obj_t object)
540 /* Juggle an object by picking it up and putting it down again, the purpose
541 * being to get the object to the front of the chain of things at its loc. */
545 i = game.place[object];
546 j = game.fixed[object];
548 move(object + NOBJECTS, j);
551 void move(obj_t object, loc_t where)
552 /* Place any object anywhere by picking it up and dropping it. May
553 * already be toting, in which case the carry is a no-op. Mustn't
554 * pick up objects which are not at any loc, since carry wants to
555 * remove objects from game.atloc chains. */
559 if (object > NOBJECTS)
560 from = game.fixed[object - NOBJECTS];
562 from = game.place[object];
563 /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong... */
564 if (from != LOC_NOWHERE && from != CARRIED)
569 loc_t put(obj_t object, loc_t where, long pval)
570 /* put() is the same as move(), except it returns a value used to set up the
571 * negated game.prop values for the repository objects. */
574 return STASHED(pval);
577 void carry(obj_t object, loc_t where)
578 /* Start toting an object, removing it from the list of things at its former
579 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
580 * (moving "fixed" second loc), don't change game.place or game.holdng. */
584 if (object <= NOBJECTS) {
585 if (game.place[object] == CARRIED)
587 game.place[object] = CARRIED;
592 if (game.atloc[where] == object) {
593 game.atloc[where] = game.link[object];
596 temp = game.atloc[where];
597 while (game.link[temp] != object) {
598 temp = game.link[temp];
600 game.link[temp] = game.link[object];
603 void drop(obj_t object, loc_t where)
604 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
605 * game.holdng if the object was being toted. */
607 if (object > NOBJECTS)
608 game.fixed[object - NOBJECTS] = where;
610 if (game.place[object] == CARRIED)
612 /* The bird has to be weightless. This ugly hack (and the
613 * corresponding code in the drop function) brought to you
614 * by the fact that when the bird is caged, we need to be able
615 * to either 'take bird' or 'take cage' and have the right thing
619 game.place[object] = where;
621 if (where == LOC_NOWHERE ||
624 game.link[object] = game.atloc[where];
625 game.atloc[where] = object;
628 int atdwrf(loc_t where)
629 /* Return the index of first dwarf at the given location, zero if no dwarf is
630 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
631 * the pirate (6th dwarf). */
639 for (long i = 1; i <= NDWARVES - 1; i++) {
640 if (game.dloc[i] == where)
642 if (game.dloc[i] != 0)
648 /* Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
652 /* Returns 2**bit for use in constructing bit-masks. */
657 bool tstbit(long mask, int bit)
658 /* Returns true if the specified bit is set in the mask. */
660 return (mask & (1 << bit)) != 0;
663 void set_seed(int32_t seedval)
664 /* Set the LCG seed */
666 game.lcg_x = seedval % LCG_M;
667 if (game.lcg_x < 0) {
668 game.lcg_x = LCG_M + game.lcg_x;
670 // once seed is set, we need to generate the Z`ZZZ word
671 for (int i = 0; i < 5; ++i) {
672 game.zzword[i] = 'A' + randrange(26);
674 game.zzword[1] = '\''; // force second char to apostrophe
675 game.zzword[5] = '\0';
678 static int32_t get_next_lcg_value(void)
679 /* Return the LCG's current value, and then iterate it. */
681 int32_t old_x = game.lcg_x;
682 game.lcg_x = (LCG_A * game.lcg_x + LCG_C) % LCG_M;
686 int32_t randrange(int32_t range)
687 /* Return a random integer from [0, range). */
689 return range * get_next_lcg_value() / LCG_M;
693 void bug(enum bugtype num, const char *error_string)
695 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
702 void state_change(obj_t obj, int state)
703 /* Object must have a change-message list for this to be useful; only some do */
705 game.prop[obj] = state;
706 pspeak(obj, change, state, true);