我已经学习了 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♣︎”,因为提示告诉我我应该让它出现,而不是显示卡的背面。我成功构建了应用程序它似乎工作得很好。
然而,作业的提示告诉我:
A good solution will have given some thought to what happens if every card in the deck has been shown and the user still keeps flipping. Do something simple and sensible (for example, you should not have to modify the classes in the Model in any way).
但我的解决方案将让用户无限翻转卡片。所以我尝试通过添加一个 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 以查看其他人的解决方案,但似乎提示被忽略了。你能与我分享你的想法吗?
任何建议将不胜感激!!!
最佳答案
你只需要用这样的 if 语句包装它
if (card) {
//flip the card
}
记住card
是Deck.h
的一个对象,我们已经设置了Deck
当它用完card时返回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++;
}
关于ios - 关于CS193P作业1的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25580439/