-
Notifications
You must be signed in to change notification settings - Fork 0
/
CardMatchingGame.m
84 lines (73 loc) · 1.75 KB
/
CardMatchingGame.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//
// CardMatchingGame.m
// cs193p
//
// Created by Wojciech Koszek (home) on 7/18/15.
// Copyright (c) 2015 Wojciech Koszek (home). All rights reserved.
//
#import "CardMatchingGame.h"
#import "Deck.h"
@interface CardMatchingGame()
@property (nonatomic, readwrite) NSInteger score;
@property (nonatomic, strong) NSMutableArray *cards;
@end
@implementation CardMatchingGame
- (NSMutableArray *)cards
{
if (!_cards) _cards = [[NSMutableArray alloc] init];
return _cards;
}
- (instancetype)initWithCardCount:(NSUInteger)count
usingDeck:(Deck *)deck;
{
self = [super init];
if (self) {
for (int i = 0; i < count; i++) {
Card *card = [deck drawRandomCard];
if (!card) {
self = nil;
break;
}
[self.cards addObject:card];
}
}
return self;
}
static const int MATCH_BONUS = 2;
static const int MISMATCH_PENALTY = 4;
static const int COST_TO_CHANGE = 1;
- (void) chooseCardAtIndex:(NSUInteger)index
{
Card *card = [self cardAtIndex:index];
if (!card.isMatched) {
if (card.isChosen) {
card.chosen = NO;
} else {
for (Card *otherCard in self.cards) {
if (otherCard.isChosen && !otherCard.isMatched) {
int matchScore = [card match:@[otherCard]];
if (matchScore) {
self.score += (matchScore * MATCH_BONUS);
card.matched = YES;
otherCard.matched = YES;
} else {
self.score -= MISMATCH_PENALTY;
otherCard.chosen = NO;
}
break;
}
}
self.score -= COST_TO_CHANGE;
card.chosen = YES;
}
}
}
- (Card *)cardAtIndex:(NSUInteger)index
{
if (index >= [self.cards count]) {
return nil;
} else {
return [self.cards objectAtIndex:index];
}
}
@end