Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define MAXLINE 20 /* pre cursor definitions and c libraries included */
- /* My attempt at creating a hangman game in c language */
- int main(){
- FILE *fpin;
- char line[MAXLINE]; /* actual word thats read in from unknown1.txt */
- char guess[MAXLINE]; /* line of asterixs with current letters known to be displayed to user */
- char character; /* character used for checking whether user wants to guess letter or word */
- char current_guess; /* character for guessing a letter */
- char word_guess[MAXLINE]; /* string for guessing the word all at once */
- int lifes_remaining=10; /* amount of lives remaining */
- int y,q,i; /* ints used for loop counters etc */
- int string_compare; /* initial variable declaration */
- if((fpin=fopen("unknown1.txt","r"))== NULL)
- {printf("Cannot open file\n"); /* open unknown1.txt as a read only file */
- exit(EXIT_FAILURE);}
- fscanf(fpin,"%s",line); /* taking the text from unknown1.txt and copying it to line */
- {printf("Ready to start!, the word is");}
- int x=strlen(line);
- for(y=0;y<x;y++)
- {guess[y]='*';}
- guess[y]='\0'; /* letting c know when the string is ended */
- printf("%s\n",guess);
- /* creating our guess line, which displays how many letters to be guessed/how many they have already guessed*/
- printf("the number of guesses remaining is %d\n", lifes_remaining); /* telling the user how many lives they have left*/
- printf("would you like to guess the word [w] or guess a letter [l]\n:"); /* asking the user for word or letter */
- scanf("%c", &character);
- if(character == 'l' || character == 'L') /* if user selects l or L, guessing letter */
- {printf("please choose a letter to guess in the word:\n");
- do
- {current_guess = getchar();} /* reading in a value for the guess from the user*/
- while( !isalpha(current_guess));
- for( i = 0 ; line[i] != '\0' ; i++)
- {if(line[i] == current_guess) /* looping through word being guessed, checking entriesagainst guess*/ {guess[i] = current_guess; /* assigning the value to the string of astrericks */
- } }
- printf("\n%s\n",guess);
- if(character == 'w' || character == 'W') /* user wants to guess word */
- {printf("You have chosen to guess the word\n");
- printf("\nplease enter your guess for the word:\n");
- char word_guess =getchar(); /* function to read in the word being guessed */
- while (getchar() != '\n'){ current_guess = getchar(); };
- string_compare = strcmp(word_guess, line); /* comparing the word to what we have already */
- if(string_compare==0) /* if ==0, they're equal, if not, incorrect guess */
- {printf("congratulations, you have guessed the word");}
- else
- {printf(" incorrect guess:");}
- }
- fclose(fpin);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement