【发布时间】:2013-03-14 15:48:57
【问题描述】:
我正在学习斯坦福的课程,我们必须为应用程序构建一个方法来检查 2 张卡片是否匹配,这就是具有逻辑的模型的样子(查看那里的方法是 flipCardAtIndex):
#import "CardMatchingGame.h"
#import "PlayingCardsDeck.h"
@interface CardMatchingGame()
@property (readwrite, nonatomic) int score;
@property (strong, nonatomic) NSMutableArray *cards;
@property (strong, nonatomic) NSString *notification;
@end
@implementation CardMatchingGame
-(NSMutableArray *) cards {
if (!_cards) _cards = [[NSMutableArray alloc] init];
return _cards;
}
-(id)initWithCardCount:(NSUInteger)count usingDeck:(Deck *)deck {
self = [super init];
if (self) {
for (int i = 0; i < count; i++) {
Card *card = [deck drawRandonCard];
if (!card) {
self = nil;
} else {
self.cards[i] = card;
}
}
}
return self;
}
-(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;
}
}
@end
这是整个游戏的类模型,得到了实际的匹配方法:
#import "PlayingCards.h"
@implementation PlayingCards
@synthesize suit = _suit;
//overriding the :match method of cards to give different acore if its only a suit match or a number match
-(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;
}
//more stuff...
W 已经用数组创建了它,所以我们可以为更多对象扩展它,但现在我想弄清楚如何扩展它:/
这是我的项目 github https://github.com/NirOhayon/Matchismo
我是 Objective C 的新手,如果你能帮我弄清楚,我会很感激。
非常感谢
【问题讨论】:
-
这不是答案。你应该将这些
if (!card.isUnplayable) { if (!card.isFaceUp) {结合到if(!card.isUnplayable && !card.isFaceUp)) -
抱歉没有更新你,我正忙着招聘。现在我没有mac。如果您在文本中解释您的要求会更好。
-
@AnoopVaidya:这是风格问题。我们中的一些人更喜欢他拥有它的方式,因为它可以更容易地确定为什么在调试和单步执行代码时特定检查为真。
-
@AnoopVaidya 嘿,Anoop,谢谢。我有一个应用程序已经在使用 2 张卡片匹配,我现在的要求是添加匹配 3 张卡片的可能性......我可以添加更多细节吗?这是我的项目的 github 文件夹github.com/NirOhayon/Matchismo
-
我是按照斯坦福课程中 Paul Hugerty 的指示做的
标签: iphone ios objective-c cocoa-touch cocoa