我已经学习了CS193P的第一和第二课,并完成了第一个任务,要求我让Matchismo以随机顺序翻转整个扑克牌,每次显示一张牌。这是我的CardGameViewController.m代码
#import "CardGameViewController.h"
#import "Deck.h"
#import "PlayingCardDeck.h"
@interface CardGameViewController ()
@property (weak, nonatomic) IBOutlet UILabel *flipsLabel;
@property (nonatomic) int flipCount;
@property (strong, nonatomic) Deck *fullDeck;
@end
@implementation CardGameViewController
- (void)setFlipCount:(int)flipCount{
_flipCount = flipCount;
self.flipsLabel.text = [NSString stringWithFormat:@"Flips: %d",self.flipCount];
NSLog(@"flipCount changed to %d",self.flipCount);
}
- (Deck *)fullDeck{
if (!_fullDeck) _fullDeck =[[PlayingCardDeck alloc] init];
return _fullDeck;
}
- (IBAction)touchCardButton:(UIButton *)sender {
if (!sender.currentTitle) {
[sender setBackgroundImage:[UIImage imageNamed:@"cardfront"]
forState:UIControlStateNormal];
[sender setTitle:[[self.fullDeck drawRandomCard] contents]
forState:UIControlStateNormal];
} else {
[sender setBackgroundImage:[UIImage imageNamed:@"cardback"]
forState:UIControlStateNormal];
[sender setTitle:nil forState:UIControlStateNormal];
}
self.flipCount++;
}
@end
当然,在这之前,我先删除了教学演示按钮上的“A♣︎”,因为提示告诉我应该让它显示出卡背面。我构建应用程序成功,似乎工作得很好。
但是,作业的提示告诉我:
一个好的解决方案会考虑到如果牌组中的每张牌都已经显示且用户仍在翻转时会发生什么。做一些简单明了的事情(例如,你不应该以任何方式修改模型中的类。)
但是我的解决方案会让用户无限地翻转卡片。所以我尝试通过添加if()来达到目标:
- (IBAction)touchCardButton:(UIButton *)sender {
if (self.flipCount < 53){ /*There are 52 cards in a deck */
if (!sender.currentTitle) {
[sender setBackgroundImage:[UIImage imageNamed:@"cardfront"]
forState:UIControlStateNormal];
[sender setTitle:[[self.fullDeck drawRandomCard] contents]
forState:UIControlStateNormal];
} else {
[sender setBackgroundImage:[UIImage imageNamed:@"cardback"]
forState:UIControlStateNormal];
[sender setTitle:nil forState:UIControlStateNormal];
}
self.flipCount++;
}
}
然后当我运行应用程序并触摸屏幕时,当fliplabel达到52时,它将不再翻转。
这个解决方案天真荒谬吗?我已经搜索了github以查看其他人的解决方案,似乎忽略了这些提示。你能和我分享你的想法吗?
任何建议都将受到高度赞赏!!!
答案 0 :(得分:2)
你只需要用这样的if语句包装它
if (card) {
//flip the card
}
记住card
是Deck.h
的对象,我们已经设置Deck
在卡片用尽时返回nil。因此,一旦牌组卡片耗尽,它就会停止翻转
另外,最重要的是,没有神奇的数字!即使你已经写了一个解释它的命令,你也不能像这样抛出53
。这只是一个糟糕的编程习惯
- (IBAction)touchCardButton:(UIButton *)sender {
// No magic number! --> if (self.flipCount < 53){
if (!sender.currentTitle) {
Card *card = [self.fullDeck drawRandomCard];
if (card) { // <----- this is what I'm talking about
[sender setBackgroundImage:[UIImage imageNamed:@"cardfront"]
forState:UIControlStateNormal];
[sender setTitle:card.contents
forState:UIControlStateNormal];
}
} else {
[sender setBackgroundImage:[UIImage imageNamed:@"cardback"]
forState:UIControlStateNormal];
[sender setTitle:nil forState:UIControlStateNormal];
}
self.flipCount++;
}