Browse Source

make the code cleaner + debugging

remotes/origin/Saba
Saba Fazlali 11 months ago
parent
commit
cdd703a113
  1. 48
      src/main/c/Hangman/playHangman.c

48
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);
}
}
}
Loading…
Cancel
Save