An example
If we isolate dictionary things to the dictionary, it might look like this:
const char *dict_init () {
static const char *alphabet = "abcdefghijklmnopqrstuvwxyz";
rng_init();
return alphabet;
}
const char *get_random_word() {
static const char *words[] = {"racing", "magic", "bow", "racecar"};
static const size_t word_count = sizeof(words)/sizeof(words[0]);
return words[rng_to(word_count)];
}
Now from within main
we might have this:
int main() {
const char *alphabet = dict_init();
bool *guessed = calloc(strlen(alphabet), sizeof(bool));
int tries = 10;
const char *word = get_random_word();
size_t word_len = strlen(word);
bool playing = true;
while (playing) {
display_word(word, word_len, alphabet, guessed);
fputs("\nPick a letter: ", stdout);
int chosen_letter;
for (chosen_letter = tolower(getchar()); isspace(chosen_letter); chosen_letter = tolower(getchar()))
{ }
if (chosen_letter == EOF) {
playing = false;
continue;
}
const char *target = strchr(alphabet, chosen_letter);
if (target == NULL) {
puts("Please enter a valid letter.");
continue;
}
if (guessed[target - alphabet]) {
puts("Please pick a different letter");
continue;
}
guessed[target - alphabet] = true;
// is this letter in the word to be guessed?
if (strchr(word, *target) != NULL) {
if (display_word(word, word_len, alphabet, guessed)) {
printf("\nTries Remaining: %d\n", tries);
} else {
puts("-> YOU WIN!");
playing = false;
}
} else { // guessed letter not in target word
playing = print_hangman(--tries);
}
}
free(guessed);
}
Note that I've used strchr
to see if the character is within the alphabet. I've also modified your print_hangman
to return true if there are guesses left and added this function:
size_t display_word(const char *word, const size_t word_len, const char *alphabet, const bool *guessed) {
size_t hidden = word_len;
for (size_t i=0; i < word_len; ++i) {
bool revealed = guessed[strchr(alphabet, word[i]) - alphabet];
if (revealed) {
putchar(word[i]);
--hidden;
} else {
putchar('_');
}
putchar(' ');
}
return hidden;
}
It's not terribly efficient in terms of runtime performance, but it doesn't matter much since it will be fast enough for a human player.