Printing the game state 打印游戏状态

之前我们把 printWord() 函数里面要写代码部分空了出来,现在呢,我们要,把这里的代码写完,搞定整个游戏,这个函数的作用是把已经猜中的字母打印出来,就像这样:RH_H

我们把实现过程分成两步。

首先,我们来打印游戏状态。先循环这个被猜的单词,然后看看这个单词的各个字母是否出现在了 usedLetters 数组里,如果出现了,就打印出来,否则就在那个字母的位置打一条下划线。

接着,在循环完每一个字母之后,我们就要看看是不是所有的字母都被猜出来了,如果所有字母都被猜出来了,那游戏玩家就获胜了。

我们把这部分代码加到这个函数里面:

printf("\nWord: ");
// this will be used to track missing letters 用来追踪有没有字母没猜中了
BOOL missingLetters = NO;

// loop over every letter 循环字母
for (NSInteger i = 0; i < [word length]; ++i) {
    // convert the unichar into an NSString for arrays
    unichar letter = [word characterAtIndex:i];
    NSString *letterString = [NSString stringWithFormat:@"%C",
letter];

// if we already guessed this letter, print it out 如果已经猜出了字母,就把结果打印出来
if ([usedLetters containsObject:letterString]) {
    printf("%C", letter);
} else {
    // letter not guessed; mark with a placeholder 没猜中就用下划线代替字母
    printf("_");
    // we haven't won yet! 还没有猜完诶
    missingLetters = YES;
}
}

这里还是用注释来帮助我们理解这些代码。

最后的这个部分,我们将打印出玩家一共猜了多少次。之前不管是玩家猜多少次,只要还有字母没有被猜出来,游戏就不会结束。

但现在我们可以规定最多的猜测次数,一旦超过了这个次数,我们就用 exit() 这个函数来终结游戏。

下面就是这部分的代码,把它放在 printWord() 函数之前:

// notice careful use of \n to control line breaks
printf("\nGuesses: %ld/8\n", [usedLetters count]);
if (missingLetters == NO) {
    // no missing letters - a winner!
    printf("It looks like you live on... for now.\n");
    exit(0);
} else {
    if ([usedLetters count] == 8) {
      // they guessed eight times; game over
        printf("Oops – you died! The word was %s.\n", [word
cStringUsingEncoding:NSUTF8StringEncoding]);
        exit(0);
    } else {
        // game is still active
        printf("Enter a guess: ");
    }
}

到这里所有代码都写完啦~~(♥^‿^)ノ

你可以用快捷键 Cmd+R 运行这个小游戏。

results matching ""

    No results matching ""