面向对象编程是一件美好的事情。快速编码,向您展示它是如何工作的......
//
// PlayingCard.h
//
#import <Foundation/Foundation.h>
@interface PlayingCard : NSObject
- (id)initWithSuit:(NSInteger)suit value:(NSInteger)value;
- (BOOL)isAce;
- (BOOL)isFace;
@end
//
// PlayingCard.m
//
#import "PlayingCard.h"
@interface PlayingCard ()
@property(nonatomic, assign) NSInteger suit;
@property(nonatomic, assign) NSInteger value;
@end
@implementation PlayingCard
- (id)initWithSuit:(NSInteger)suit value:(NSInteger)value {
self = [self init];
if (self) {
_suit = suit;
_value = value;
}
return self;
}
- (BOOL)isAce {
return self.value == 0;
}
- (BOOL)isFace {
return self.value > 10;
}
- (NSString *)suitName {
switch (self.suit) {
case 0:
return @"spades";
break;
case 1:
return @"diamonds";
break;
case 2:
return @"clubs";
break;
case 3:
return @"hearts";
break;
default:
return @"";
break;
}
}
// so it prints nicely. you should consider making the suits enums
- (NSString *)description {
return [NSString stringWithFormat:@"%@: suit:%@, value:%d", [super description], [self suitName], self.value];
}
@end
//
// CardDeck.h
//
#import <Foundation/Foundation.h>
@class PlayingCard;
@interface CardDeck : NSObject
+ (id)cardDeck;
- (void)shuffle;
- (NSUInteger)count;
- (PlayingCard *)dealOne;
@end
//
// CardDeck.m
//
#import "CardDeck.h"
#import "PlayingCard.h"
@interface CardDeck ()
@property(nonatomic,strong) NSMutableArray *cards;
@end
@implementation CardDeck
+ (id)cardDeck {
CardDeck *deck = [[self alloc] init];
for (NSInteger suit = 0; suit < 4; suit++) {
for (NSInteger value = 0; value < 13; value++) {
PlayingCard *card = [[PlayingCard alloc] initWithSuit:suit value:value];
[deck.cards addObject:card];
}
}
return deck;
}
- (id)init {
self = [super init];
if (self) {
_cards = [NSMutableArray array];
}
return self;
}
- (void)shuffle {
NSMutableArray *shuffledCards = [NSMutableArray array];
for (int i=0; i<52; i++) {
int randomIndex = arc4random_uniform(52-i);
[shuffledCards addObject:[self.cards objectAtIndex:randomIndex]];
[self.cards removeObjectAtIndex:randomIndex];
}
self.cards = shuffledCards;
}
- (NSUInteger)count {
return self.cards.count;
}
- (PlayingCard *)dealOne {
PlayingCard *card = [self.cards lastObject];
[self.cards removeLastObject];
return card;
}
@end
像这样称呼它...
CardDeck *deck = [CardDeck cardDeck];
// try it with and without shuffle
[deck shuffle];
while (deck.count) {
PlayingCard *card = [deck dealOne];
NSLog(@"%@", card);
}