记忆游戏 - 为每个级别定义不同数量的牌

时间:2015-05-13 06:51:30

标签: ios objective-c cgrectmake

我想制作一个简单的记忆匹配游戏。 这是我的以下情况:我有一个levelselectionviewcontroller和一个gameviewcontroller。在我的levelselectionviewcontroller我有10个按钮(10级)。我想,当我点击1级时,我的gameviewcontroller会产生1对2对。当我点击10级时,我希望gameviewcontroller可以制作2行,3对,例如。我的最大对数是11,我的最大行数是4。

我的gameviewcontroller中的代码是

·H

#define CARDS_PER_ROW 4
#define NUMBER_OF_PAIRS 2

的.m

-(void) generateCardViews {
int positionsLeftInRow = CARDS_PER_ROW;
int j = 0; // j = ROWNUMBER (j = 0) = ROW1, (j = 1) = ROW2...

for (int i = 0; i < [self.gameModel.cards count]; i++) {
    NSInteger value = ((CardModel *)self.gameModel.cards[i]).value;

    CGFloat x = (i % CARDS_PER_ROW) * 121 + (i % CARDS_PER_ROW) * 40 + 285;
    if (j == 1) {
        x += 80; // set additional indent (horizontal displacement)
    }
    if (j == 2) {
        x -= 160;
    }

    CGFloat y = j * 122 + j * 40 + 158;
    CGRect frame = CGRectMake(x, y, 125, 125);




    CardView *cv = [[CardView alloc] initWithFrame:frame andPosition:i andValue:value];

    if (!((CardModel *)self.gameModel.cards[i]).outOfPlay) {
        [self.boardView addSubview:cv];

       if ([self.gameModel.turnedCards containsObject: self.gameModel.cards[i]]) {
            [self.turnedCardViews addObject: cv];
            [cv flip];
        }
    }

    if (--positionsLeftInRow == 0) {
        j++;
        positionsLeftInRow = CARDS_PER_ROW;
        if (j == 1) {
            positionsLeftInRow = CARDS_PER_ROW-1;

        if (j == 2) {
            positionsLeftInRow = CARDS_PER_ROW-2;
        }}
    }
}
}

我的代码现在正在运行,但我只能更改gameviewcontroller中#define宏中的行和对。但我如何在我的levelselectionviewcontroller中#define呢? 我想要一个可重复使用的n级游戏视图控制器。

我希望我的问题是可以理解的。

1 个答案:

答案 0 :(得分:0)

如果我理解你在写什么,你可以在gameviewcontroller.h中创建这些参数(卡片和对)作为参数(而不是常量):

@property (nonatomic, assign) int CARDS_PER_ROW;
@property (nonatomic, assign) int NUMBER_OF_PAIRS;

添加到gameviewcontroller.m:

-(id)initWithCards:(int)numCards andPairs:(int)numPairs
{
    self = [Gameviewcontroller init];
    if (self)
    {
        CARDS_PER_ROW = numCards;
        NUMBER_OF_PAIRS = numPairs;
    }
    return self;
}

并在levelselectionviewcontroller.m中:

switch (chosenLevel):
    case 1:
    {
        Gameviewcontroller *level = [[Gameviewcontroller alloc] initWithCards: CARDS_PER_ROW andPairs: NUMBER_OF_PAIRS];
        break;
    }
    .
    .
    .
    case 10:
    {
        Gameviewcontroller *level = [[Gameviewcontroller alloc] initWithCards: CARDS_PER_ROW andPairs: NUMBER_OF_PAIRS];
        break;
    }
}
相关问题