objective-ccocos2d-iphonecocos2d-iphone-3

Creating a lot of buttons for levels in Cocos2d using a for loop


I'm trying to make a couple hundred levels for a game I'm developing, so obviously I want to use a for loop and not create each button individually.

I do all of this fine, but the code I'm currently using makes it so that the call block for each button is the same. Obviously if I'm going to have the different level buttons go to different levels, the call block must be different for each one.

In order to differentiate which level I'm on, I call [[LevelManager sharedInstance] nextLevel] the number of times corresponding to the level number. I attempted to change this number by getting the touch location of the user touching the button, getting a row/column number, then running the above code a certain number of times. However, it was not updating the touch position before running the whole call block after touching the button, which obviously makes my code not work.

Is there a way to update the touch position manually, before the call block finishes? Is there a way to somehow store every button in an array and establish a different call block for each one? I'm not sure what the best approach is to fixing my problem. Thanks and my code is below.

Called upon initialization

for (int l = 0; l < NUMBER_OF_WORLDS; l++) {
        for (int j = 0; j < 4; j++) {
            for (int k = 0; k < 5; k++) {
                NSString *tempTitle = [NSString stringWithFormat:@"%i",(k+1)+(l*5)];
                CCButton *tempButton;
                tempButton = [CCButton buttonWithTitle:tempTitle]
                tempButton.block = ^(id sender) {
                    int row = floorf(touchLocation.y/(screenBounds.size.height/6)) + 1;
                    int column = floorf(touchLocation.x/(screenBounds.size.width/4)) + 1;
                    int buttonIndex = row*column;
                    for (int m = 1; m < buttonIndex; m++) {
                        [[LevelManager sharedInstance] nextLevel];
                    }
                    CCScene *gameplayScene = [CCBReader loadAsScene:@"LevelScene"];
                    [[CCDirector sharedDirector] replaceScene:gameplayScene];
                    levelNumber = i;
                };
                tempButton.position = ccp((screenBounds.size.width/4)*j + levelImagePlaceholder.contentSize.width*tempButton.scale, screenBounds.size.height/6*k + 50 + l*screenBounds.size.height);
                [self addChild:tempButton];
                i++;
            }
        }
}

Method for getting touch position

-(void) touchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    CCLOG(@"touch ran");
    touchLocation = [touch locationInNode:self];
}

Solution

  • You already have the row/column available. They are j and k. Those variables can be referenced in your button's "on pressed" block.