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 "-"
401 // Check for non-digit chars in the rest of the stirng.
413 static void get_vocab_metadata(const char* word, vocab_t* id, enum wordtype* type)
415 /* Check for an empty string */
416 if (strncmp(word, "", sizeof("")) == 0) {
418 *type = NO_WORD_TYPE;
424 ref_num = get_motion_vocab_id(word);
425 if (ref_num != WORD_NOT_FOUND) {
431 ref_num = get_object_vocab_id(word);
432 if (ref_num != WORD_NOT_FOUND) {
438 ref_num = get_action_vocab_id(word);
439 if (ref_num != WORD_NOT_FOUND) {
445 // Check for the reservoir magic word.
446 if (strcasecmp(word, game.zzword) == 0) {
452 // Check words that are actually numbers.
453 if (is_valid_int(word)) {
459 *id = WORD_NOT_FOUND;
460 *type = NO_WORD_TYPE;
464 static void tokenize(char* raw, struct command_t *cmd)
466 memset(cmd, '\0', sizeof(struct command_t));
468 /* Bound prefix on the %s would be needed to prevent buffer
469 * overflow. but we shortstop this more simply by making each
470 * raw-input buffer as long as the entire input buffer. */
471 sscanf(raw, "%s%s", cmd->raw1, cmd->raw2);
473 /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
474 * effect on raw tokens of packing them into sixbit characters, 5
475 * to a 32-bit word. This is something the FORTRAN version did
476 * becuse archaic FORTRAN had no string types. Don Wood's
477 * mechanical translation of 2.5 to C retained the packing and
478 * thus this misfeature.
480 * It's philosophically questionable whether this is the right
481 * thing to do even in oldstyle mode. On one hand, the text
482 * mangling was not authorial intent, but a result of limitations
483 * in their tools. On the other, not simulating this misbehavior
484 * goes against the goal of making oldstyle as accurate as
485 * possible an emulation of the original UI.
487 if (settings.oldstyle) {
488 cmd->raw1[TOKLEN + TOKLEN] = cmd->raw2[TOKLEN + TOKLEN] = '\0';
489 for (size_t i = 0; i < strlen(cmd->raw1); i++)
490 cmd->raw1[i] = toupper(cmd->raw1[i]);
491 for (size_t i = 0; i < strlen(cmd->raw2); i++)
492 cmd->raw2[i] = toupper(cmd->raw2[i]);
495 /* populate command with parsed vocabulary metadata */
496 get_vocab_metadata(cmd->raw1, &(cmd->id1), &(cmd->type1));
497 get_vocab_metadata(cmd->raw2, &(cmd->id2), &(cmd->type2));
500 bool get_command_input(struct command_t *command)
501 /* Get user input on stdin, parse and map to command */
503 char inputbuf[LINESIZE];
510 if (word_count(input) > 2) {
515 if (strcmp(input, "") != 0)
520 strncpy(inputbuf, input, LINESIZE - 1);
523 tokenize(inputbuf, command);
528 void juggle(obj_t object)
529 /* Juggle an object by picking it up and putting it down again, the purpose
530 * being to get the object to the front of the chain of things at its loc. */
534 i = game.place[object];
535 j = game.fixed[object];
537 move(object + NOBJECTS, j);
540 void move(obj_t object, loc_t where)
541 /* Place any object anywhere by picking it up and dropping it. May
542 * already be toting, in which case the carry is a no-op. Mustn't
543 * pick up objects which are not at any loc, since carry wants to
544 * remove objects from game.atloc chains. */
548 if (object > NOBJECTS)
549 from = game.fixed[object - NOBJECTS];
551 from = game.place[object];
552 /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong... */
553 if (from != LOC_NOWHERE && from != CARRIED)
558 loc_t put(obj_t object, loc_t where, long pval)
559 /* put() is the same as move(), except it returns a value used to set up the
560 * negated game.prop values for the repository objects. */
563 return STASHED(pval);
566 void carry(obj_t object, loc_t where)
567 /* Start toting an object, removing it from the list of things at its former
568 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
569 * (moving "fixed" second loc), don't change game.place or game.holdng. */
573 if (object <= NOBJECTS) {
574 if (game.place[object] == CARRIED)
576 game.place[object] = CARRIED;
579 if (game.atloc[where] == object) {
580 game.atloc[where] = game.link[object];
583 temp = game.atloc[where];
584 while (game.link[temp] != object) {
585 temp = game.link[temp];
587 game.link[temp] = game.link[object];
590 void drop(obj_t object, loc_t where)
591 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
592 * game.holdng if the object was being toted. */
594 if (object > NOBJECTS)
595 game.fixed[object - NOBJECTS] = where;
597 if (game.place[object] == CARRIED)
599 game.place[object] = where;
601 if (where == LOC_NOWHERE ||
604 game.link[object] = game.atloc[where];
605 game.atloc[where] = object;
608 int atdwrf(loc_t where)
609 /* Return the index of first dwarf at the given location, zero if no dwarf is
610 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
611 * the pirate (6th dwarf). */
619 for (long i = 1; i <= NDWARVES - 1; i++) {
620 if (game.dloc[i] == where)
622 if (game.dloc[i] != 0)
628 /* Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
632 /* Returns 2**bit for use in constructing bit-masks. */
637 bool tstbit(long mask, int bit)
638 /* Returns true if the specified bit is set in the mask. */
640 return (mask & (1 << bit)) != 0;
643 void set_seed(long seedval)
644 /* Set the LCG seed */
646 game.lcg_x = (unsigned long) seedval % game.lcg_m;
648 // once seed is set, we need to generate the Z`ZZZ word
649 for (int i = 0; i < 5; ++i) {
650 game.zzword[i] = 'A' + randrange(26);
652 game.zzword[1] = '\''; // force second char to apostrophe
653 game.zzword[5] = '\0';
656 unsigned long get_next_lcg_value(void)
657 /* Return the LCG's current value, and then iterate it. */
659 unsigned long old_x = game.lcg_x;
660 game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
664 long randrange(long range)
665 /* Return a random integer from [0, range). */
667 return range * get_next_lcg_value() / game.lcg_m;
671 void bug(enum bugtype num, const char *error_string)
673 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
680 void state_change(obj_t obj, int state)
681 /* Object must have a change-message list for this to be useful; only some do */
683 game.prop[obj] = state;
684 pspeak(obj, change, state, true);