Question

I am writing an iOS app for a game that is similar to Hangman, except that the player is required to guess the secret word one letter at a time, starting with the first letter. The secret word is displayed as asterisks (*) in a UITextField at the beginning of the game.

When the player guesses the first letter, the program should compare it against the secret word to see if the letter is correct. If the guess is correct, the app should replace the first asterisk with the correct letter. If the guess is incorrect, some other action will be taken. The player repeats this process one letter at a time until the secret word has been completely spelled out.

Here is the code I am currently using to check the guessed letter against the secret word, but it is not working properly.

-(void) checkGameLetter : (NSString *) letterToCheck{
    bool match = NO;
    NSRange gameLetterRange;
    char charToCheck = [letterToCheck characterAtIndex:0];
        for(int i = 0; i < self.correctWord.length; i++)
        {
            char tempString = [self.correctWord characterAtIndex:i];
            if(charToCheck == tempString){
                match = YES;
                gameLetterRange = NSMakeRange(i, 1);//location, length
                Screen.text =[Screen.text stringByReplacingCharactersInRange:gameLetterRange withString:letterToCheck];

        }

}
Was it helpful?

Solution

The thing that's wrong with your code is that nothing in it says which letter of the correct word we are checking against.

For example, suppose the word is "zork" and the user guesses "r". You are trying to walk through "zork" looking to see if "r" matches any letter. But according to your spec, if this is a guess at the first letter, we should just be checking against the first letter ("z") and stop, since the "r" is wrong in that position.

So what you want to write is much simpler than the code you have. You don't want this:

-(void) checkGameLetter : (NSString *) letterToCheck{

You want this:

-(void) checkGameLetter:(NSString*)letterToCheck againstPosition:(NSInteger)position {

And there will be no loop: you will just look right at the letter in that position and see if they are the same.

Finally notice this important fact: == does not compare two strings. It asks whether they are the same object, which they manifestly are not. You want isEqualToString:.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top