如何比较数组中的三个对象?

时间:2013-03-12 21:23:28

标签: ios objective-c cocoa-touch cocoa nsarray

在我的卡片匹配游戏中(遵循stanford课程)我需要创建一个UISwitch,它将改变两个卡匹配到三张卡匹配之间的游戏模式,现在我已经有一个匹配的方法看起来像这样:

-(int)match:(NSArray *)cardToMatch {

    int score = 0;

    if (cardToMatch.count == 1) {
        PlayingCards *aCard = [cardToMatch lastObject];

        if ([aCard.suit isEqualToString: self.suit]) {
            score = 1;
        } else if (aCard.rank == self.rank) {
            score = 4;
        }

    }

    return score;
}

它已经是一个阵列,但我只是在两张牌之间进行检查。如何改进此方法以检查三个,或创建一个单独的方法?

这也是检查已翻转的卡片的方法:

-(Card *) cardAtIndex:(NSUInteger)index {

    return (index < self.cards.count) ? self.cards[index] : nil;
}


#define FLIP_COST 1
#define MISMATCH_PENALTY 2
#define BONUS 4

-(void) flipCardAtIndex:(NSUInteger)index {



    Card *card = [self cardAtIndex:index];

    if (!card.isUnplayable) {

        if (!card.isFaceUp) {

            for (Card *otherCard in self.cards) {

                if (otherCard.isFaceUp && !otherCard.isUnplayable) {

                   int matchScore = [card match:@[otherCard]];

                    if (matchScore) {

                        otherCard.unplayble = YES;
                        card.unplayble = YES;

                        self.notification = [NSString stringWithFormat:@"%@ & %@  match!", card.contents, otherCard.contents];

                        self.score += matchScore * BONUS;
                    } else {
                        otherCard.faceUp = NO;
                        self.score -= MISMATCH_PENALTY;
                        self.notification = [NSString stringWithFormat:@"%@ did not matched to %@", card.contents, otherCard.contents];
                    }
                    break;
                }

            }
            self.score -= FLIP_COST;
        }
        card.faceUp = !card.isFaceUp;

    }
}

感谢。

1 个答案:

答案 0 :(得分:0)

我假设你已经知道你想要匹配的牌的索引。因此,如果您有三个索引,则匹配函数将返回bool值。然后你可以使用嵌套的if来测试第三张卡。它看起来像这样。

if([self match:index1 card2:index2]){
    if(self match:index1 card2:index3){
        NSLog(@"You have a match");
    }
}
else NSLog@"No match";

您的匹配功能类似于:

-(BOOL)match:(int)index1 card2:(int)index2{
    //Do your matching here and return if YES or NO accordingly
}