CardMatchingGame
-
.h
@import Foundation #import "Deck.h" @interface CardMatchingGame : NSObject - (instancetype)initWithCardCount: (NSUInteger)count usingDeck: (Deck *)deck; @property (nonatomic, readonly) NSUInteger score; - (void)chooseCardAtIndex: (NSUInteger)index; - (Card *)cardAtIndex: (NSUInteger)index; @end
-
.m
#import "CardMathcingGame.h" @interface CardMatchingGame() @property (nonatomic, readwrite) NSInteger score; @property (nonatomic, strong) NSMutableArray *cards; @end @implementation - (NSMutableArray)cards { if (!_cards) _cards = [[NSMutableArray alloc] init]; return _cards; } - (instancetype)initWithCardCount: (NSUInteger)count usingDeck: (Deck *)deck { self = [super init]; if (self) { for (int i = 0; i < count; ++i) { Card *card = [deck drawRandomCard]; if (card) { [self.cards addObject:card]; } else { self = nil; break; } } } return self; } - (instancetype)init { return nil; } - (Card *)cardAtIndex: (NSUInteger)index { return (index < [self.cards count]) ? self.cards[index] : nil; } static const int MISMATCH_PENALTY = 2; static const int MATCH_BONUS = 2; static const int COST_TO_CHOOSE = 1; - (void)chooseCardAtIndex: (NSUInteger)index { Card *card = [self cardAtIndex: index]; if (!card.isMatched) { if (card.isChosen) { card.chosen = NO; } else { // match against another card for (Card *otherCard in self.cards) { if (otherCard.isChosen && !otherCard.isMatched) { int matchScore = [card match:@[otherCard]]; if (matchScore) { self.score += matchScore * MATCH_BONUS;; card.matched = YES; otherCard.matched = YES; } else { self.score -= MISMATCH_PENALTY; otherCard.chosen = NO; } break; } } self.score -= COST_TO_CHOOSE; card.Chosen = YES; } } } @end
其他
- firstObject/lastObject 方法和下标访问的差别在于,这两种方法当越界时会返回 nil,而下标访问会直接崩溃
- 所有的对象一定要记得初!始!化!否则默认是 nil