This is a follow up to my previous Code Review, and I have incorporated feedback I received in this revision of the code, along with some other improvements.
I would appreciate your feedback on this code, specifically the practice of placing project-wide constants in config.h
, the count_missing_letters
method which uses a function pointer to print the word state, as well as my getchar
loop in main.c
, where I am now continuing on invalid input and consuming white-space characters.
Is there any cleaner way to write count_missing_letters
which accomplishes the task of being easy to use as well as not having its code repeated. I opted to keep one function so that the single loop performs two different checks in one go, and the use of a function pointer decouples what happens on each iteration - unsure if this is 'idiomatic' C.
Below are the source files and the CMakeLists file (which includes many runtime Clang sanitizers enabled). Alternatively, the code can be easily compiled with the following: cc *.c -o hangman && ./hangman
main.c
/**
* * Hangman in C *
* O(1) lookup using pointers to 26 letters which each have a
* state. A letter is either empty, or the letter itself.
* I was inspired by seeing many other Hangman implementations which
* relied on a multiple layers of iteration, this aims to be 'simple'
* and 'idiomatic', by using a different approach.
*
* @version 2.0
* @date 1/18/19
* @author Faraz Fazli
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include "rng.h"
#include "utils.h"
#include "config.h"
// Returns length of an array
#define len(x) (((sizeof(x)))/(sizeof((x)[0])))
int main() {
char letters[ALPHABET_SIZE];
int tries = 0;
rng_init();
memset(letters, HIDDEN_LETTER, ALPHABET_SIZE);
size_t total_elems = len(words);
char *word = words[rng_to(total_elems)];
size_t word_len = strlen(word); // excludes NUL
size_t word_size = word_len + 1; // includes NUL
char **word_to_guess = malloc(word_size * sizeof(*word_to_guess));
// Link letters in word to 'letters' array
for (size_t i = 0; i < word_len; i++) {
word_to_guess[i] = &letters[dst_from_a(word[i])];
}
size_t num_prev_missing = word_len;
count_missing_letters(word_to_guess, print_char);
fputs("\nPick a letter: ", stdout);
int chosen_letter;
while ((chosen_letter = getchar()) != EOF) {
// Consume newline and other white-space characters
if (isspace(chosen_letter)) {
continue;
}
if (!isalpha(chosen_letter)) {
puts("Please enter a valid letter.");
continue;
}
chosen_letter = tolower(chosen_letter);
size_t letter_pos = dst_from_a(chosen_letter);
if (letters[letter_pos] != (char) HIDDEN_LETTER) {
puts("Please pick a different letter");
continue;
}
letters[letter_pos] = (char) chosen_letter;
size_t num_missing = count_missing_letters(word_to_guess, print_char);
if (num_missing == num_prev_missing) {
tries++;
}
num_prev_missing = num_missing;
if (num_missing == 0) {
puts("-> YOU WIN!");
break;
}
puts("");
int tries_left = TOTAL_TRIES - tries;
print_hangman(tries_left);
if (tries_left > 0) {
printf("\nTries Remaining: %d\n", tries_left);
fputs("Pick a letter: ", stdout);
} else {
puts("No tries left! Game Over!");
break;
}
}
free(word_to_guess);
}
config.h
#ifndef HANGMAN_CONFIG_H
#define HANGMAN_CONFIG_H
/**
* Use enum to replace "magic numbers" instead of #define or const
* Ref: Practice of Programming, p.21
*/
enum {
ALPHABET_SIZE = 26,
TOTAL_TRIES = 10,
HIDDEN_LETTER = '_',
};
static char *words[] = {"racing", "magic", "bow", "racecar"};
#endif //HANGMAN_CONFIG_H
utils.c
#include <stdio.h>
#include <stdlib.h>
#include "config.h"
void print_hangman(int tries_left) {
if (tries_left > 7) {
return;
}
switch (tries_left) {
case 7:
puts("┏━━━╤━");
puts("┃┃ ");
puts("┃┃");
puts("┃┃");
puts("┃┃");
puts("┻┻━━━━━━━");
break;
case 6:
puts("┏━━━╤━");
puts("┃┃ O ");
puts("┃┃");
puts("┃┃");
puts("┃┃");
puts("┻┻━━━━━━━");
break;
case 5:
puts("┏━━━╤━");
puts("┃┃ O ");
puts("┃┃ | ");
puts("┃┃ ");
puts("┃┃ ");
puts("┻┻━━━━━━━");
break;
case 4:
puts("┏━━━╤━");
puts("┃┃ O ");
puts("┃┃ ╲| ");
puts("┃┃ ");
puts("┃┃ ");
puts("┻┻━━━━━━━");
break;
case 3:
puts("┏━━━╤━");
puts("┃┃ O ");
puts("┃┃ ╲|╱");
puts("┃┃ ");
puts("┃┃ ");
puts("┻┻━━━━━━━");
break;
case 2:
puts("┏━━━╤━");
puts("┃┃ O ");
puts("┃┃ ╲|╱");
puts("┃┃ | ");
puts("┃┃ ");
puts("┻┻━━━━━━━");
break;
case 1:
puts("┏━━━╤━");
puts("┃┃ O ");
puts("┃┃ ╲|╱");
puts("┃┃ | ");
puts("┃┃ ╱ ");
puts("┻┻━━━━━━━");
break;
case 0:
puts("┏━━━╤━");
puts("┃┃ O ");
puts("┃┃ ╲|╱");
puts("┃┃ | ");
puts("┃┃ ╱ ╲");
puts("┻┻━━━━━━━");
break;
}
}
void print_char(char char_to_print) {
putchar(char_to_print);
putchar(' ');
}
size_t count_missing_letters(char **word_to_guess, const void(on_each(char))) {
size_t num_missing = 0;
while (*word_to_guess) {
if (on_each != NULL) {
on_each(**word_to_guess);
}
if (**word_to_guess++ == HIDDEN_LETTER) {
num_missing++;
}
}
return num_missing;
}
size_t dst_from_a(int letter) {
return (size_t) abs(letter - 'a');
}
utils.h
#ifndef HANGMAN_UTILS_H
#define HANGMAN_UTILS_H
#include <stdlib.h>
/**
* Prints "hangman" ascii art
* @param tries_left - must be <= 7 to display
*/
void print_hangman(int tries_left);
/**
* Prints character, followed by a space
* @param char_to_print
*/
void print_char(char char_to_print);
/**
* Prints the state of each letter and counts the number of missing letters
* Optionally calls a function with each character read
* @param word_to_guess - word being guessed (array of pointers)
* @param on_each - optional function to call on each iteration
* @return underscore count
*/
size_t count_missing_letters(char **word_to_guess, void(on_each(char)));
/**
* Returns the distance from 'a'
* @param letter 'a' to 'z' (must be lower case)
* @return 0 through 25
*/
size_t dst_from_a(int letter);
#endif //HANGMAN_UTILS_H
rng.c
#include "rng.h"
#include <stdlib.h>
#include <time.h>
void rng_init(void) {
srand((unsigned int) time(NULL));
}
size_t rng_to(size_t max) {
return (unsigned) rand() / ((unsigned) RAND_MAX / max + 1u);
}
rng.h
#ifndef HANGMAN_RNG_H
#define HANGMAN_RNG_H
#include <stdlib.h>
/**
* Initializes Random Number Generator
* Note: RNG is based on the current time and thus does not produce secure values.
* This is intentional, as the RNG is solely used to select a random current word.
*/
void rng_init(void);
/**
* Helper method for Random Number Generation
* @param max - max number
* @return between 0 to max
*/
size_t rng_to(size_t max);
#endif //HANGMAN_RNG_H
CMakeLists.txt
# Improved version adapted from https://codereview.stackexchange.com/a/210770/78786
cmake_minimum_required(VERSION 3.13)
project(Hangman C)
add_executable(${CMAKE_PROJECT_NAME} main.c utils.c utils.h rng.c rng.h config.h)
set(CMAKE_C_COMPILER clang)
target_compile_features(${CMAKE_PROJECT_NAME} PRIVATE c_std_99)
target_compile_options(${CMAKE_PROJECT_NAME} PRIVATE
$<$<C_COMPILER_ID:Clang>:
-Weverything
-fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi
-flto
-fvisibility=default>)
target_link_options(${CMAKE_PROJECT_NAME} PRIVATE
$<$<C_COMPILER_ID:Clang>:
-fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi
-flto>)