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 /* Version specifier */
98 strcpy(renderp, VERSION);
99 size_t len = strlen(VERSION);
107 // Print the message.
108 printf("%s\n", rendered);
113 void speak(const char* msg, ...)
117 vspeak(msg, true, ap);
121 void sspeak(const int msg, ...)
126 vprintf(arbitrary_messages[msg], ap);
131 void pspeak(vocab_t msg, enum speaktype mode, int skip, bool blank, ...)
132 /* Find the skip+1st message from msg and print it. Modes are:
133 * feel = for inventory, what you can touch
134 * look = the full description for the state the object is in
135 * listen = the sound for the state the object is in
136 * study = text on the object. */
142 vspeak(objects[msg].inventory, blank, ap);
145 vspeak(objects[msg].descriptions[skip], blank, ap);
148 vspeak(objects[msg].sounds[skip], blank, ap);
151 vspeak(objects[msg].texts[skip], blank, ap);
154 vspeak(objects[msg].changes[skip], blank, ap);
160 void rspeak(vocab_t i, ...)
161 /* Print the i-th "random" message (section 6 of database). */
165 vspeak(arbitrary_messages[i], true, ap);
169 void echo_input(FILE* destination, const char* input_prompt, const char* input)
171 size_t len = strlen(input_prompt) + strlen(input) + 1;
172 char* prompt_and_input = (char*) xcalloc(len);
173 strcpy(prompt_and_input, input_prompt);
174 strcat(prompt_and_input, input);
175 fprintf(destination, "%s\n", prompt_and_input);
176 free(prompt_and_input);
179 static int word_count(char* str)
181 char delims[] = " \t";
185 for (char *s = str; *s; s++)
187 if (strchr(delims, *s) == 0) {
192 if (strchr(delims, *s) != 0) {
200 static char* get_input(void)
203 char input_prompt[] = "> ";
204 if (!settings.prompt)
205 input_prompt[0] = '\0';
207 // Print a blank line
212 input = readline(input_prompt);
214 if (input == NULL) // Got EOF; return with it.
216 if (input[0] == '#') { // Ignore comments.
220 // We have a 'normal' line; leave the loop.
224 // Strip trailing newlines from the input
225 input[strcspn(input, "\n")] = 0;
230 echo_input(stdout, input_prompt, input);
233 echo_input(settings.logfp, "", input);
238 bool silent_yes(void)
240 bool outcome = false;
243 char* reply = get_input();
246 // Should be unreachable. Reply should never be NULL
251 if (strlen(reply) == 0) {
253 rspeak(PLEASE_ANSWER);
257 char* firstword = (char*) xcalloc(strlen(reply) + 1);
258 sscanf(reply, "%s", firstword);
262 for (int i = 0; i < (int)strlen(firstword); ++i)
263 firstword[i] = tolower(firstword[i]);
265 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
266 int y = strncmp("y", firstword, sizeof("y") - 1);
267 int no = strncmp("no", firstword, sizeof("no") - 1);
268 int n = strncmp("n", firstword, sizeof("n") - 1);
276 } else if (no == 0 ||
281 rspeak(PLEASE_ANSWER);
287 bool yes(const char* question, const char* yes_response, const char* no_response)
288 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
289 * if no, print Z and return false. */
291 bool outcome = false;
296 char* reply = get_input();
299 // Should be unreachable. Reply should never be NULL
305 if (strlen(reply) == 0) {
307 rspeak(PLEASE_ANSWER);
311 char* firstword = (char*) xcalloc(strlen(reply) + 1);
312 sscanf(reply, "%s", firstword);
316 for (int i = 0; i < (int)strlen(firstword); ++i)
317 firstword[i] = tolower(firstword[i]);
319 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
320 int y = strncmp("y", firstword, sizeof("y") - 1);
321 int no = strncmp("no", firstword, sizeof("no") - 1);
322 int n = strncmp("n", firstword, sizeof("n") - 1);
331 } else if (no == 0 ||
337 rspeak(PLEASE_ANSWER);
344 /* Data structure routines */
346 static int get_motion_vocab_id(const char* word)
347 // Return the first motion number that has 'word' as one of its words.
349 for (int i = 0; i < NMOTIONS; ++i) {
350 for (int j = 0; j < motions[i].words.n; ++j) {
351 if (strncasecmp(word, motions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
352 strchr(ignore, word[0]) == NULL ||
357 // If execution reaches here, we didn't find the word.
358 return (WORD_NOT_FOUND);
361 static int get_object_vocab_id(const char* word)
362 // Return the first object number that has 'word' as one of its words.
364 for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
365 for (int j = 0; j < objects[i].words.n; ++j) {
366 if (strncasecmp(word, objects[i].words.strs[j], TOKLEN) == 0)
370 // If execution reaches here, we didn't find the word.
371 return (WORD_NOT_FOUND);
374 static int get_action_vocab_id(const char* word)
375 // Return the first motion number that has 'word' as one of its words.
377 for (int i = 0; i < NACTIONS; ++i) {
378 for (int j = 0; j < actions[i].words.n; ++j) {
379 if (strncasecmp(word, actions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
380 strchr(ignore, word[0]) == NULL ||
385 // If execution reaches here, we didn't find the word.
386 return (WORD_NOT_FOUND);
389 static bool is_valid_int(const char *str)
390 /* Returns true if the string passed in is represents a valid integer,
391 * that could then be parsed by atoi() */
393 // Handle negative number
397 // Handle empty string or just "-". Should never reach this
398 // point, because this is only used with transitive verbs.
400 return false; // LCOV_EXCL_LINE
402 // Check for non-digit chars in the rest of the stirng.
414 static void get_vocab_metadata(const char* word, vocab_t* id, enum wordtype* type)
416 /* Check for an empty string */
417 if (strncmp(word, "", sizeof("")) == 0) {
419 *type = NO_WORD_TYPE;
425 ref_num = get_motion_vocab_id(word);
426 if (ref_num != WORD_NOT_FOUND) {
432 ref_num = get_object_vocab_id(word);
433 if (ref_num != WORD_NOT_FOUND) {
439 ref_num = get_action_vocab_id(word);
440 if (ref_num != WORD_NOT_FOUND) {
446 // Check for the reservoir magic word.
447 if (strcasecmp(word, game.zzword) == 0) {
453 // Check words that are actually numbers.
454 if (is_valid_int(word)) {
460 *id = WORD_NOT_FOUND;
461 *type = NO_WORD_TYPE;
465 static void tokenize(char* raw, struct command_t *cmd)
467 memset(cmd, '\0', sizeof(struct command_t));
469 /* Bound prefix on the %s would be needed to prevent buffer
470 * overflow. but we shortstop this more simply by making each
471 * raw-input buffer as long as the entire input buffer. */
472 sscanf(raw, "%s%s", cmd->raw1, cmd->raw2);
474 /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
475 * effect on raw tokens of packing them into sixbit characters, 5
476 * to a 32-bit word. This is something the FORTRAN version did
477 * becuse archaic FORTRAN had no string types. Don Wood's
478 * mechanical translation of 2.5 to C retained the packing and
479 * thus this misfeature.
481 * It's philosophically questionable whether this is the right
482 * thing to do even in oldstyle mode. On one hand, the text
483 * mangling was not authorial intent, but a result of limitations
484 * in their tools. On the other, not simulating this misbehavior
485 * goes against the goal of making oldstyle as accurate as
486 * possible an emulation of the original UI.
488 if (settings.oldstyle) {
489 cmd->raw1[TOKLEN + TOKLEN] = cmd->raw2[TOKLEN + TOKLEN] = '\0';
490 for (size_t i = 0; i < strlen(cmd->raw1); i++)
491 cmd->raw1[i] = toupper(cmd->raw1[i]);
492 for (size_t i = 0; i < strlen(cmd->raw2); i++)
493 cmd->raw2[i] = toupper(cmd->raw2[i]);
496 /* populate command with parsed vocabulary metadata */
497 get_vocab_metadata(cmd->raw1, &(cmd->id1), &(cmd->type1));
498 get_vocab_metadata(cmd->raw2, &(cmd->id2), &(cmd->type2));
501 bool get_command_input(struct command_t *command)
502 /* Get user input on stdin, parse and map to command */
504 char inputbuf[LINESIZE];
511 if (word_count(input) > 2) {
516 if (strcmp(input, "") != 0)
521 strncpy(inputbuf, input, LINESIZE - 1);
524 tokenize(inputbuf, command);
529 void juggle(obj_t object)
530 /* Juggle an object by picking it up and putting it down again, the purpose
531 * being to get the object to the front of the chain of things at its loc. */
535 i = game.place[object];
536 j = game.fixed[object];
538 move(object + NOBJECTS, j);
541 void move(obj_t object, loc_t where)
542 /* Place any object anywhere by picking it up and dropping it. May
543 * already be toting, in which case the carry is a no-op. Mustn't
544 * pick up objects which are not at any loc, since carry wants to
545 * remove objects from game.atloc chains. */
549 if (object > NOBJECTS)
550 from = game.fixed[object - NOBJECTS];
552 from = game.place[object];
553 /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong... */
554 if (from != LOC_NOWHERE && from != CARRIED)
559 loc_t put(obj_t object, loc_t where, long pval)
560 /* put() is the same as move(), except it returns a value used to set up the
561 * negated game.prop values for the repository objects. */
564 return STASHED(pval);
567 void carry(obj_t object, loc_t where)
568 /* Start toting an object, removing it from the list of things at its former
569 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
570 * (moving "fixed" second loc), don't change game.place or game.holdng. */
574 if (object <= NOBJECTS) {
575 if (game.place[object] == CARRIED)
577 game.place[object] = CARRIED;
580 if (game.atloc[where] == object) {
581 game.atloc[where] = game.link[object];
584 temp = game.atloc[where];
585 while (game.link[temp] != object) {
586 temp = game.link[temp];
588 game.link[temp] = game.link[object];
591 void drop(obj_t object, loc_t where)
592 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
593 * game.holdng if the object was being toted. */
595 if (object > NOBJECTS)
596 game.fixed[object - NOBJECTS] = where;
598 if (game.place[object] == CARRIED)
600 game.place[object] = where;
602 if (where == LOC_NOWHERE ||
605 game.link[object] = game.atloc[where];
606 game.atloc[where] = object;
609 int atdwrf(loc_t where)
610 /* Return the index of first dwarf at the given location, zero if no dwarf is
611 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
612 * the pirate (6th dwarf). */
620 for (long i = 1; i <= NDWARVES - 1; i++) {
621 if (game.dloc[i] == where)
623 if (game.dloc[i] != 0)
629 /* Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
633 /* Returns 2**bit for use in constructing bit-masks. */
638 bool tstbit(long mask, int bit)
639 /* Returns true if the specified bit is set in the mask. */
641 return (mask & (1 << bit)) != 0;
644 void set_seed(long seedval)
645 /* Set the LCG seed */
647 game.lcg_x = (unsigned long) seedval % game.lcg_m;
649 // once seed is set, we need to generate the Z`ZZZ word
650 for (int i = 0; i < 5; ++i) {
651 game.zzword[i] = 'A' + randrange(26);
653 game.zzword[1] = '\''; // force second char to apostrophe
654 game.zzword[5] = '\0';
657 unsigned long get_next_lcg_value(void)
658 /* Return the LCG's current value, and then iterate it. */
660 unsigned long old_x = game.lcg_x;
661 game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
665 long randrange(long range)
666 /* Return a random integer from [0, range). */
668 return range * get_next_lcg_value() / game.lcg_m;
672 void bug(enum bugtype num, const char *error_string)
674 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
681 void state_change(obj_t obj, int state)
682 /* Object must have a change-message list for this to be useful; only some do */
684 game.prop[obj] = state;
685 pspeak(obj, change, state, true);