Hangman v2 written in C












1












$begingroup$


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 n.



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.
*
* @date 1/11/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 'n' from puts/printf/etc.
if (chosen_letter == 'n') {
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: %dn", 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>)









share|improve this question









$endgroup$

















    1












    $begingroup$


    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 n.



    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.
    *
    * @date 1/11/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 'n' from puts/printf/etc.
    if (chosen_letter == 'n') {
    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: %dn", 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>)









    share|improve this question









    $endgroup$















      1












      1








      1





      $begingroup$


      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 n.



      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.
      *
      * @date 1/11/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 'n' from puts/printf/etc.
      if (chosen_letter == 'n') {
      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: %dn", 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>)









      share|improve this question









      $endgroup$




      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 n.



      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.
      *
      * @date 1/11/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 'n' from puts/printf/etc.
      if (chosen_letter == 'n') {
      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: %dn", 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>)






      c ascii-art hangman c99






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 13 mins ago









      FarazFaraz

      324110




      324110






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211739%2fhangman-v2-written-in-c%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211739%2fhangman-v2-written-in-c%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          TypeError: fit_transform() missing 1 required positional argument: 'X'