From cdd703a1131a04721fa8d45e53d8e35852b5efb7 Mon Sep 17 00:00:00 2001 From: Saba Fazlali Date: Wed, 7 Feb 2024 01:12:22 +0100 Subject: [PATCH] make the code cleaner + debugging --- src/main/c/Hangman/playHangman.c | 48 ++++---------------------------- 1 file changed, 5 insertions(+), 43 deletions(-) diff --git a/src/main/c/Hangman/playHangman.c b/src/main/c/Hangman/playHangman.c index 86865f5..dc64e50 100644 --- a/src/main/c/Hangman/playHangman.c +++ b/src/main/c/Hangman/playHangman.c @@ -9,37 +9,9 @@ char toLower(char ch) { return ch; } -// Ignores the inputs with more than one letter -void ignoreExtraInput() { - int c; - while ((c = getchar()) != '\n' && c != EOF); -} - -// Function to get a single character input from the user -char getSingleCharInput() { - char input[3]; // Buffer for input (including null terminator and newline character) - - // Read a line of input (up to 2 characters) and consume the rest - if (fgets(input, sizeof(input), stdin) == NULL) { - return '\0'; // Error or end of file - } - - // Check if the last character is a newline, if not, consume the rest of the line - if (input[strlen(input) - 1] != '\n') { - ignoreExtraInput(); - } - - // Check if only one character is entered - if (strlen(input) == 2 && input[1] == '\n') { - return input[0]; - } else { - return '\0'; // More than one character entered - } -} - void playHangman(char *wordToGuess) { int mistakes = 0; - char guessedLetters[30]; //Guessed letters + char guessedLetters[30] = ""; //Guessed letters char currentGuess[50]; //Current state of the guessed word displayRules(); @@ -55,13 +27,11 @@ void playHangman(char *wordToGuess) { printf("Enter your guess: \n"); scanf("%s", input); - // Check if the input is a single letter if(strlen(input) > 1) { printf("Invalid input. Please enter a single letter.\n"); continue; } - // Check if the input is an alphabet char guess = input[0]; if (!isalpha(guess)) { printf("Please enter a valid alphabet.\n"); @@ -80,17 +50,6 @@ void playHangman(char *wordToGuess) { // Add the guessed letter to the list guessedLetters[strlen(guessedLetters)] = guess; - - // Check if the letter has already been guessed by the player - if (strchr(guessedLetters, guess) != NULL) { - printf("You already guessed that letter. Try another letter.\n"); - ignoreExtraInput(); - continue; - } - - // Add the guessed letter to the list - guessedLetters[strlen(guessedLetters)] = guess; - // Check if the guessed letter is in the word int found = 0; for (int i = 0; i < strlen(wordToGuess); ++i) { @@ -125,6 +84,9 @@ void playHangman(char *wordToGuess) { if (mistakes == MAX_MISTAKES) { currentState(currentGuess, mistakes); printf("Oops! You have no more guesses :( \n The answer was: %s \n", wordToGuess); + break; } + + currentState(currentGuess, mistakes); } -} +} \ No newline at end of file