Skip to content

Instantly share code, notes, and snippets.

@charleshkang
Created June 22, 2015 16:16
Show Gist options
  • Save charleshkang/5eff09d228302ac41c0e to your computer and use it in GitHub Desktop.
Save charleshkang/5eff09d228302ac41c0e to your computer and use it in GitHub Desktop.
HANGMAN GAME
//
// main.m
// HangManGame_CHK
//
// Created by Charles Kang on 6/17/15.
// Copyright (c) 2015 Charles Kang. All rights reserved.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
srand(time(NULL));
char guessWords[][16] = {
"snowman", "idaho", "pikachu", "coffee", "espresso", "aligator", "robot", "computer", "kangaroo"
};
// index for random word
int randomIndex = rand() % 6;
// you get 6 lives per game
int numLives = 5;
int numCorrect = 0;
int oldCorrect = 0;
int lengthOfWord = strlen(guessWords[randomIndex]);
int letterGuessed[8] = {0};
int quit = 0;
int loopIndex = 0;
int reguessed = 0;
char guess[16];
char letterEntered;
// game loop starts here
while ( numCorrect < lengthOfWord ) {
printf("\nWelcome to Hang Man! \n\nYour word is:");
for( loopIndex = 0; loopIndex < lengthOfWord; loopIndex++) {
if(letterGuessed[loopIndex] == 1) {
printf("%c",guessWords[randomIndex][loopIndex]);
} else {
printf(" _");
}
}
printf("\n\n");
printf("Letters correct so far: %d\n\n",numCorrect);
printf("Guess a letter!\n");
fgets(guess, 16, stdin);
if( strncmp(guess, "quit", 4) == 0) {
quit = 1;
break;
}
letterEntered = guess[0];
reguessed = 0;
printf("Letter entered: %c\n\n",letterEntered);
oldCorrect = numCorrect;
for( loopIndex = 0; loopIndex < lengthOfWord; loopIndex++) {
if(letterGuessed[loopIndex] == 1) {
if(guessWords[randomIndex][loopIndex] == letterEntered) {
reguessed = 1;
break;
}
continue;
}
if( letterEntered == guessWords[randomIndex][loopIndex] ) {
letterGuessed[loopIndex] = 1;
numCorrect++;
}
}
if( oldCorrect == numCorrect && reguessed == 0) {
numLives--;
if (numLives == 0) {
break;
}
} else if( reguessed == 1) {
printf("Already Guessed!!\n");
} else {
printf("Correct guess :)\n");
}
} // while loop
if( quit == 1 ) {
printf("\nthe user quit early\n");
} else if (numLives == 0) {
printf("\nSorry, you LOOOOSE! The word was: %s\n",
guessWords[randomIndex]);
} else {
printf("\nYOU WIN HANG MAN !!!\n");
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment