8 #include <editline/readline.h>
13 static void* xcalloc(size_t size)
15 void* ptr = calloc(size, 1);
18 // exclude from coverage analysis because we can't simulate an out of memory error in testing
19 fprintf(stderr, "Out of memory!\n");
26 /* I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
28 static void vspeak(const char* msg, bool blank, va_list ap)
30 // Do nothing if we got a null pointer.
34 // Do nothing if we got an empty string.
41 int msglen = strlen(msg);
44 ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
45 char* rendered = xcalloc(size);
46 char* renderp = rendered;
48 // Handle format specifiers (including the custom %S) by
49 // adjusting the parameter accordingly, and replacing the
51 bool pluralize = false;
52 for (int i = 0; i < msglen; i++) {
54 /* Ugh. Least obtrusive way to deal with artifacts "on the floor"
55 * being dropped outside of both cave and building. */
56 if (strncmp(msg + i, "floor", 5) == 0 && strchr(" .", msg[i + 5]) && !INSIDE(game.loc)) {
57 strcpy(renderp, "ground");
69 long arg = va_arg(ap, long);
70 int ret = snprintf(renderp, size, "%ld", arg);
75 pluralize = (arg != 1);
78 // Unmodified string specifier.
80 char *arg = va_arg(ap, char *);
81 strncat(renderp, arg, size - 1);
82 size_t len = strlen(renderp);
87 // Singular/plural specifier.
89 // look at the *previous* numeric parameter
96 // LCOV_EXCL_START - doesn't occur in test suite.
97 /* Version specifier */
99 strcpy(renderp, VERSION);
100 size_t len = strlen(VERSION);
109 // Print the message.
110 printf("%s\n", rendered);
115 void speak(const char* msg, ...)
119 vspeak(msg, true, ap);
123 void sspeak(const int msg, ...)
128 vprintf(arbitrary_messages[msg], ap);
133 void pspeak(vocab_t msg, enum speaktype mode, int skip, bool blank, ...)
134 /* Find the skip+1st message from msg and print it. Modes are:
135 * feel = for inventory, what you can touch
136 * look = the full description for the state the object is in
137 * listen = the sound for the state the object is in
138 * study = text on the object. */
144 vspeak(objects[msg].inventory, blank, ap);
147 vspeak(objects[msg].descriptions[skip], blank, ap);
150 vspeak(objects[msg].sounds[skip], blank, ap);
153 vspeak(objects[msg].texts[skip], blank, ap);
156 vspeak(objects[msg].changes[skip], blank, ap);
162 void rspeak(vocab_t i, ...)
163 /* Print the i-th "random" message (section 6 of database). */
167 vspeak(arbitrary_messages[i], true, ap);
171 void echo_input(FILE* destination, const char* input_prompt, const char* input)
173 size_t len = strlen(input_prompt) + strlen(input) + 1;
174 char* prompt_and_input = (char*) xcalloc(len);
175 strcpy(prompt_and_input, input_prompt);
176 strcat(prompt_and_input, input);
177 fprintf(destination, "%s\n", prompt_and_input);
178 free(prompt_and_input);
181 static int word_count(char* str)
183 char delims[] = " \t";
187 for (char *s = str; *s; s++)
189 if (strchr(delims, *s) == 0) {
194 if (strchr(delims, *s) != 0) {
202 static char* get_input(void)
205 char input_prompt[] = "> ";
206 if (!settings.prompt)
207 input_prompt[0] = '\0';
209 // Print a blank line
214 input = readline(input_prompt);
216 if (input == NULL) // Got EOF; return with it.
218 if (input[0] == '#') { // Ignore comments.
222 // We have a 'normal' line; leave the loop.
226 // Strip trailing newlines from the input
227 input[strcspn(input, "\n")] = 0;
232 echo_input(stdout, input_prompt, input);
235 echo_input(settings.logfp, "", input);
240 bool silent_yes(void)
242 bool outcome = false;
245 char* reply = get_input();
248 // Should be unreachable. Reply should never be NULL
253 if (strlen(reply) == 0) {
255 rspeak(PLEASE_ANSWER);
259 char* firstword = (char*) xcalloc(strlen(reply) + 1);
260 sscanf(reply, "%s", firstword);
264 for (int i = 0; i < (int)strlen(firstword); ++i)
265 firstword[i] = tolower(firstword[i]);
267 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
268 int y = strncmp("y", firstword, sizeof("y") - 1);
269 int no = strncmp("no", firstword, sizeof("no") - 1);
270 int n = strncmp("n", firstword, sizeof("n") - 1);
278 } else if (no == 0 ||
283 rspeak(PLEASE_ANSWER);
289 bool yes(const char* question, const char* yes_response, const char* no_response)
290 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
291 * if no, print Z and return false. */
293 bool outcome = false;
298 char* reply = get_input();
301 // Should be unreachable. Reply should never be NULL
307 if (strlen(reply) == 0) {
309 rspeak(PLEASE_ANSWER);
313 char* firstword = (char*) xcalloc(strlen(reply) + 1);
314 sscanf(reply, "%s", firstword);
318 for (int i = 0; i < (int)strlen(firstword); ++i)
319 firstword[i] = tolower(firstword[i]);
321 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
322 int y = strncmp("y", firstword, sizeof("y") - 1);
323 int no = strncmp("no", firstword, sizeof("no") - 1);
324 int n = strncmp("n", firstword, sizeof("n") - 1);
333 } else if (no == 0 ||
339 rspeak(PLEASE_ANSWER);
346 /* Data structure routines */
348 static int get_motion_vocab_id(const char* word)
349 // Return the first motion number that has 'word' as one of its words.
351 for (int i = 0; i < NMOTIONS; ++i) {
352 for (int j = 0; j < motions[i].words.n; ++j) {
353 if (strncasecmp(word, motions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
354 strchr(ignore, word[0]) == NULL ||
359 // If execution reaches here, we didn't find the word.
360 return (WORD_NOT_FOUND);
363 static int get_object_vocab_id(const char* word)
364 // Return the first object number that has 'word' as one of its words.
366 for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
367 for (int j = 0; j < objects[i].words.n; ++j) {
368 if (strncasecmp(word, objects[i].words.strs[j], TOKLEN) == 0)
372 // If execution reaches here, we didn't find the word.
373 return (WORD_NOT_FOUND);
376 static int get_action_vocab_id(const char* word)
377 // Return the first motion number that has 'word' as one of its words.
379 for (int i = 0; i < NACTIONS; ++i) {
380 for (int j = 0; j < actions[i].words.n; ++j) {
381 if (strncasecmp(word, actions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
382 strchr(ignore, word[0]) == NULL ||
387 // If execution reaches here, we didn't find the word.
388 return (WORD_NOT_FOUND);
391 static bool is_valid_int(const char *str)
392 /* Returns true if the string passed in is represents a valid integer,
393 * that could then be parsed by atoi() */
395 // Handle negative number
399 // Handle empty string or just "-". Should never reach this
400 // point, because this is only used with transitive verbs.
402 return false; // LCOV_EXCL_LINE
404 // Check for non-digit chars in the rest of the stirng.
415 static void get_vocab_metadata(command_word_t* word)
417 /* Check for an empty string */
418 if (strncmp(word->raw, "", sizeof("")) == 0) {
419 word->id = WORD_EMPTY;
420 word->type = NO_WORD_TYPE;
426 ref_num = get_motion_vocab_id(word->raw);
427 if (ref_num != WORD_NOT_FOUND) {
433 ref_num = get_object_vocab_id(word->raw);
434 if (ref_num != WORD_NOT_FOUND) {
440 ref_num = get_action_vocab_id(word->raw);
441 if (ref_num != WORD_NOT_FOUND) {
447 // Check for the reservoir magic word.
448 if (strcasecmp(word->raw, game.zzword) == 0) {
454 // Check words that are actually numbers.
455 if (is_valid_int(word->raw)) {
456 word->id = WORD_EMPTY;
457 word->type = NUMERIC;
461 word->id = WORD_NOT_FOUND;
462 word->type = NO_WORD_TYPE;
466 static void tokenize(char* raw, command_t *cmd)
468 memset(cmd, '\0', sizeof(command_t));
470 /* Bound prefix on the %s would be needed to prevent buffer
471 * overflow. but we shortstop this more simply by making each
472 * raw-input buffer as long as the entire input buffer. */
473 sscanf(raw, "%s%s", cmd->word[0].raw, cmd->word[1].raw);
475 /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
476 * effect on raw tokens of packing them into sixbit characters, 5
477 * to a 32-bit word. This is something the FORTRAN version did
478 * becuse archaic FORTRAN had no string types. Don Wood's
479 * mechanical translation of 2.5 to C retained the packing and
480 * thus this misfeature.
482 * It's philosophically questionable whether this is the right
483 * thing to do even in oldstyle mode. On one hand, the text
484 * mangling was not authorial intent, but a result of limitations
485 * in their tools. On the other, not simulating this misbehavior
486 * goes against the goal of making oldstyle as accurate as
487 * possible an emulation of the original UI.
489 if (settings.oldstyle) {
490 cmd->word[0].raw[TOKLEN + TOKLEN] = cmd->word[1].raw[TOKLEN + TOKLEN] = '\0';
491 for (size_t i = 0; i < strlen(cmd->word[0].raw); i++)
492 cmd->word[0].raw[i] = toupper(cmd->word[0].raw[i]);
493 for (size_t i = 0; i < strlen(cmd->word[1].raw); i++)
494 cmd->word[1].raw[i] = toupper(cmd->word[1].raw[i]);
497 /* populate command with parsed vocabulary metadata */
498 get_vocab_metadata(&(cmd->word[0]));
499 get_vocab_metadata(&(cmd->word[1]));
502 bool get_command_input(command_t *command)
503 /* Get user input on stdin, parse and map to command */
505 char inputbuf[LINESIZE];
512 if (word_count(input) > 2) {
517 if (strcmp(input, "") != 0)
522 strncpy(inputbuf, input, LINESIZE - 1);
525 tokenize(inputbuf, command);
530 void juggle(obj_t object)
531 /* Juggle an object by picking it up and putting it down again, the purpose
532 * being to get the object to the front of the chain of things at its loc. */
536 i = game.place[object];
537 j = game.fixed[object];
539 move(object + NOBJECTS, j);
542 void move(obj_t object, loc_t where)
543 /* Place any object anywhere by picking it up and dropping it. May
544 * already be toting, in which case the carry is a no-op. Mustn't
545 * pick up objects which are not at any loc, since carry wants to
546 * remove objects from game.atloc chains. */
550 if (object > NOBJECTS)
551 from = game.fixed[object - NOBJECTS];
553 from = game.place[object];
554 /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong... */
555 if (from != LOC_NOWHERE && from != CARRIED)
560 loc_t put(obj_t object, loc_t where, long pval)
561 /* put() is the same as move(), except it returns a value used to set up the
562 * negated game.prop values for the repository objects. */
565 return STASHED(pval);
568 void carry(obj_t object, loc_t where)
569 /* Start toting an object, removing it from the list of things at its former
570 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
571 * (moving "fixed" second loc), don't change game.place or game.holdng. */
575 if (object <= NOBJECTS) {
576 if (game.place[object] == CARRIED)
578 game.place[object] = CARRIED;
581 if (game.atloc[where] == object) {
582 game.atloc[where] = game.link[object];
585 temp = game.atloc[where];
586 while (game.link[temp] != object) {
587 temp = game.link[temp];
589 game.link[temp] = game.link[object];
592 void drop(obj_t object, loc_t where)
593 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
594 * game.holdng if the object was being toted. */
596 if (object > NOBJECTS)
597 game.fixed[object - NOBJECTS] = where;
599 if (game.place[object] == CARRIED)
601 game.place[object] = where;
603 if (where == LOC_NOWHERE ||
606 game.link[object] = game.atloc[where];
607 game.atloc[where] = object;
610 int atdwrf(loc_t where)
611 /* Return the index of first dwarf at the given location, zero if no dwarf is
612 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
613 * the pirate (6th dwarf). */
621 for (long i = 1; i <= NDWARVES - 1; i++) {
622 if (game.dloc[i] == where)
624 if (game.dloc[i] != 0)
630 /* Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
634 /* Returns 2**bit for use in constructing bit-masks. */
639 bool tstbit(long mask, int bit)
640 /* Returns true if the specified bit is set in the mask. */
642 return (mask & (1 << bit)) != 0;
645 void set_seed(long seedval)
646 /* Set the LCG seed */
648 game.lcg_x = (unsigned long) seedval % game.lcg_m;
650 // once seed is set, we need to generate the Z`ZZZ word
651 for (int i = 0; i < 5; ++i) {
652 game.zzword[i] = 'A' + randrange(26);
654 game.zzword[1] = '\''; // force second char to apostrophe
655 game.zzword[5] = '\0';
658 static unsigned long get_next_lcg_value(void)
659 /* Return the LCG's current value, and then iterate it. */
661 unsigned long old_x = game.lcg_x;
662 game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
666 long randrange(long range)
667 /* Return a random integer from [0, range). */
669 return range * get_next_lcg_value() / game.lcg_m;
673 void bug(enum bugtype num, const char *error_string)
675 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
682 void state_change(obj_t obj, int state)
683 /* Object must have a change-message list for this to be useful; only some do */
685 game.prop[obj] = state;
686 pspeak(obj, change, state, true);