Deck
- .h
#import <Foundation/Foundation.h>
@interface Deck : NSObject
- (void)addCard:(Card *)card;
- (void)addCard:(Card *)card atTop:(Bool)atTop;
- (Card *)drawRandomCard;
@end
- .m
#import "Deck.h"
@interface Deck()
@property (strong, nonatomic) NSMutableArray *cards;
@end
@implementation Deck
//一開(kāi)始 cards 實(shí)例變量是 nil选侨,要重寫(xiě) getter 來(lái)初始化
- (NSMutableArray *)cards {
//惰性初始化徒爹,即當(dāng)要使用該變量時(shí)才初始化
if (!_cards) _cards = [[NSMutableArray alloc] init];
return _cards;
}
- (void)addCard:(Card *)card atTop:(Bool)atTop {
if (atTop) {
[self.cards insertObject:card atIndex:0];
} else {
[self.cards addObject:card];
}
}
- (void)addCard:(Card *)card {
[self addCard:card atTop:NO];
}
- (Card *)drawRandomCard {
Card *randomCard = nil;
if ([self.cards count]){}
unsigned index = arc4random() % [self.cards count]
randomCard = self.cards[index];
[self.cards removeObjectAtIndex:index];
}
return randomCard;
}
@end
PlayingCard
-
.h
#import "Card.h" @interface PlayingCard: Card @property (strong, nonatomic) NSString *suit; @property (nonatomic) NSUInteger rank; + (NSArray *)validSuits; + (NSUInteger)maxRank; //外部只需要知道最大牌點(diǎn)是多少,而不需要知道詳細(xì)有什么牌 @end
-
.m
#import "PlayingCard.h" @implementation PlayingCard - (NSString *)contents { NSArray *rankStrings = [self rankStrings]; return [rankStrings[self.rank] stringByAppendingString:self.suit]; } + (NSArray *)rankStrings { return @[@"?", @"A", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10", @"J", @"Q", @"K"]; } + (NSArray *)validSuits { return @[@"??", @"??", @"??", @"??"]; } //上述兩個(gè)類(lèi)方法不會(huì)影響性能,只是為了可讀性 + (NSUInteger)maxRank { return [[self rankStrings] count]-1; } - (void)setRank:(NSUInteger)rank { if (rank M= [PlayingCard maxRank]) { _rank = rank; } } @synthesize suit = _suit; //同時(shí)重寫(xiě) setter 和 getter 時(shí)必須手寫(xiě) synthesize - (void)setSuit:(NSString *)suit { if ([validSuits containsObject:suit]) { _suit = suit; } } - (NSString *)suit { return _suit? : _suit : @"?"; } @end
PlayingCardDeck
-
.h
import "Deck.h" @interface PlayingCardDeck : Deck @end
-
.m
#import "PlayingCardDeck.h" #import "PlayingCard.h" @implementation Deck - (instancetype)init { //instancetype 是 NSObject 中規(guī)定的 init 的返回值 //它的意思是這個(gè)返回的對(duì)象和這個(gè)消息將要發(fā)送給的對(duì)象是同一類(lèi)型的 self = [super init]; if (self) { for (NSString *suit in [PlayingCard validSuits]) { for (NSUInteger rank = 1; rank <= [PlayingCard maxRank]); ++rank) { PlayingCard *card = [[PlayingCard alloc] init]; card.rank = rank; card.suit = suit; [self addCard: card]; } } } return self; } @end
CardGameViewController
IBAction 和 IBOutlet 實(shí)際上都是 typedef void
只是為了方便 xcode妥凳,編譯時(shí)會(huì)忽略