Skip to content

Instantly share code, notes, and snippets.

Created January 8, 2014 16:50
Show Gist options
  • Save anonymous/8320019 to your computer and use it in GitHub Desktop.
Save anonymous/8320019 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <time.h>
#include <string.h>
#define MAX_WORD_LEN 20
#define MAX_TRIES 6
char* GetWordFromFile();
int HideWord(char* randomWordfromFile);
void PlayAgain();
void GameLogic(char *randomWordfromFile);
void clear_stdin();
void PlayGame();
int main()
{
char PlayorNot;
printf("Welcome to Hangman. Would you like play? Please answer Y/N. \n");
PlayorNot = getchar();
if (PlayorNot == 'Y' || PlayorNot == 'y')
{
PlayGame();
}
else
{
system("cls");
printf("Goodbye");
}
return 0;
}
void PlayGame()
{
char* randomWordfromFile = GetWordFromFile();
GameLogic(randomWordfromFile);
PlayAgain();
}
char* GetWordFromFile()
{
FILE* pointertoFile = NULL;
char randomWordfromFile[MAX_WORD_LEN];
int i = 0 , ran = 0;
srand(time(NULL));
pointertoFile = fopen("C:\\Users\\Aditya\\Dropbox\\Hangman\\hangman.txt" , "r+");
for(; fgets(randomWordfromFile , MAX_WORD_LEN, pointertoFile) ; i++)
;
ran = rand() % i;
rewind(pointertoFile);
for(i = 0 ; i < ran ; i++)
fgets(randomWordfromFile , MAX_WORD_LEN , pointertoFile);
return randomWordfromFile;
}
void GameLogic(char *randomWordfromFile)
{
char UserGuess;
int i, x;
int WrongGuesses = 0, CorrectGuesses = 0;
size_t j;
size_t len = strlen(randomWordfromFile);
printf("%s", randomWordfromFile);
char* HiddenWord = (char*)malloc(len);
HiddenWord[len] = '\0';
for (j = 0; j < len; ++j)
{
HiddenWord[2*j] = '_';
HiddenWord[2*j+1] = ' ';
}
printf("%s\n", HiddenWord);
for(i = 0; i < MAX_TRIES; i++ )
{
if (WrongGuesses >= MAX_TRIES)
{
printf("Sorry, you lost.\n");
break;
}
printf("Go ahead and guess a letter\n");
clear_stdin();
UserGuess = getchar();
for (x = 0; x < len; x++)
{
if (randomWordfromFile[x] == UserGuess)
{
UserGuess = HiddenWord[x];
i = i - 1;
}
else
{
++WrongGuesses;
printf("You got %d out of %d wrong\n", WrongGuesses, MAX_TRIES);
}
}
printf("%s\n", HiddenWord);
}
free(HiddenWord);
}
void PlayAgain()
{
printf("Do you want to play again? Please answer with Yes/No?");
char PlayAgainAnswer = getchar();
if (PlayAgainAnswer == 'Y' || PlayAgainAnswer == 'y')
PlayGame();
else if (PlayAgainAnswer == 'N"' || PlayAgainAnswer == 'n')
printf("Thanks for playing");
else
printf("Thanks for playing");
}
void clear_stdin()
{
while( getchar() != '\n' ){;}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment