Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <string.h>
- #define LENOF(A) (int)(sizeof(A)/sizeof(*A))
- int main(){
- char *word;
- char *words[]= {"elephant", "cook", "balling", "monkey", "eggs", "pacifist", "sick", "cool", "dog", "city"};
- char *guessed;
- char *guessed_before;
- int i;
- int guesses_wrong = 0;
- int len;
- int max_len = 0;
- int word_len;
- srand(time(NULL));
- word = words[rand() % (LENOF(words))];
- for(i = 0; i < LENOF(words); i++) {
- len = strlen(words[i]); /* finds the longest word in the array */
- if(len > max_len) max_len = len;
- }
- guessed = malloc(sizeof(char) * max_len + 1);
- if(!guessed) {perror("malloc"); return 1;}
- guessed_before = malloc(sizeof(char) * max_len + 1);
- if(!guessed) {perror("malloc"); return 1;}
- printf("This is a hangman game, even though there is no hanging men around here.\n");
- printf("You only have 3 chances before the game ends.\n");
- printf("Also, every duplicate counts as a wrong guess! Have fun!\n\n");
- word_len = strlen(word);
- for(i = 0; i < word_len; i++){ /* fills guessed array with underscores */
- guessed[i] = '_';
- }
- guessed[word_len] = '\0';
- printf("%s\n", guessed);
- while(strcmp(word,guessed) != 0){ /* game over if over 3 fails */
- char letter;
- if(guesses_wrong > 2){
- printf("\nGame over!\nThe word was '%s'.\n", word);
- free(guessed);
- free(guessed_before);
- return 0;
- }
- printf("\nInput a letter:");
- scanf(" %c", &letter);
- strcpy(guessed_before, guessed); /* generates before version of the array */
- for(i = 0; i < word_len; i++){
- if(word[i] == letter){
- guessed[i] = letter; /* if the letter is correct, replace underscore with it */
- }
- }
- printf("\n%s\n", guessed);
- if(strcmp(guessed_before, guessed) == 0){ /* if there was no change in guessed array, increase wrong count */
- guesses_wrong++;
- printf("\nYou have %d wrong guesses!\n", guesses_wrong);
- }
- }
- printf("\nCongratulations, you won!\n");
- free(guessed);
- free(guessed_before);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment