سؤال

I am working on a memory based matching puzzle game. For that I need to glow buttons randomly from sequence. I have been googling sample puzzles,games & code snippets since a week or so, yet I was unable to trace out an appropriate sample project or some source to get started.

I am glowing the lights(buttons) by changing its background images(imitation), I have already set the default images for buttons(coloured bulb when in stable state) in story board. I have used NSMutableArray of IBOutletCollection i.e. tapLightButtons. Here is what I tried to get the sequence of lights glowing in a random mode to get the game experience.

-(void)startGlowingLights
{
    [self shuffleValuesInArray:_tapLightButtons];
    [self shuffleValuesInArray:lightArray];
    [self shuffleValuesInArray:_initialButtonImages];
    [self performSelector:@selector(animateButtonSequence) withObject:self afterDelay:0.2];
}

- (void) animateButtonSequence
{
    __block UIButton *tapLight;

    [UIView animateWithDuration:0.15
                          delay:0.0
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{

                         // button flash animation
                     } completion:^(BOOL finished) {
                         if (finished) {
                             if (i < _tapLightButtons.count) {
                                 i++;
                                 [self performSelector:@selector(animateButtonSequence) withObject:self afterDelay:1.0];
                                 tapLight = [self.tapLightButtons objectAtIndex:i-1];
                                 UIImage *glownLight = [UIImage imageNamed:[lightArray objectAtIndex:i-1]];
                                 [tapLight setBackgroundImage:glownLight forState:UIControlStateNormal];
                                 [[TTLMusicPlayer sharedInstance] playGlowLightSound:[[NSBundle mainBundle] pathForResource:@"beep" ofType: @"mp3"]];

                         //Reset the completed glowed button to previous state(off mode)
                                     double delayInSeconds = 1.0;
                                     dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
                                     dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                                         if (i != 0 && i < _initialButtonImages.count) {
                                            [tapLight setBackgroundImage:[self.initialButtonImages objectAtIndex:i-1] forState:UIControlStateNormal];
                                         }
                                     });

                             }
                             else {
                                 i = 0;
                             }
                             NSLog(@"i value is %d",i);
                         }
                     }];
}

-(NSMutableArray *)shuffleValuesInArray:(NSMutableArray *)shuffledArray
{
    for (NSInteger x=0;x<[shuffledArray count];x++)
    {
        NSInteger randomNumber = (arc4random() % ([shuffledArray count] - x)) + x;
        [shuffledArray exchangeObjectAtIndex:x withObjectAtIndex:randomNumber];
    }
    return shuffledArray;
}

tapLightButtons is the array which holds puzzled buttons(lights) which glows automatically one after another in random fashion.

lightArray is an array holding all the appropriate colour images(flash to produce glowed affect)

initialButtonImages contains array of all default(initial) images of buttons(off mode lights)

Some how I could partially achieve what I wanted to, surprisingly even after shuffling all arrays, still I see variations in the order because the glowed image should be the corresponding of stable(off mode coloured light) and then after resetting, the stable image should match the one before the light was actually glowed.

Posted the question on game dev site from Stack Exchange as well!!

Game Screen for better understanding

enter image description here

After flashing of coloured light

enter image description here

How to properly glow the buttons randomly from sequence?

هل كانت مفيدة؟

المحلول

I would do this a different way that leads to simpler code. I created an array of 9 custom buttons in IB and added them to an outlet collection. I subclassed the buttons, and added a flashWithOnTime: method, so the button itself would take care of switching between the normal and highlighted states.

This is the method in the button subclass,

-(void)flashWithOnTime:(CGFloat)onTime {
    [self setHighlighted:YES];
    [self performSelector:@selector(setHighlighted:) withObject:@NO afterDelay:onTime];
}

This is the code in the view controller that starts the sequence (from a button tap). Rather than shuffling, I pick a random index out of an array, and then delete that entry so it can't be picked again. The methods offImageWithSolidColor and onImageWithSolidColor, are just methods I used to create the images.

@interface ViewController ()
@property (strong, nonatomic) IBOutletCollection(RDFlashingButton) NSArray *buttons;
@property (strong,nonatomic) NSArray *indexes;
@property (strong,nonatomic) NSMutableArray *mutableIndexes;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.indexes = @[@0,@1,@2,@3,@4,@5,@6,@7,@8];
    for (RDFlashingButton *aButton in self.buttons) {
        [aButton setBackgroundImage:[self offImageWithSolidColor] forState:UIControlStateNormal];;
        [aButton setBackgroundImage:[self onImageWithSolidColor] forState:UIControlStateHighlighted];
    }
}

-(void)flashRandomly {
    if (self.mutableIndexes.count > 0) {
        int index = arc4random_uniform(self.mutableIndexes.count);
        int value = [self.mutableIndexes[index] intValue];
        RDFlashingButton *aButton = self.buttons[value];
        [aButton flashWithOnTime:0.4];
        [self.mutableIndexes removeObjectAtIndex:index];
        [self performSelector:@selector(flashRandomly) withObject:nil afterDelay:.4];
    }
}

-(IBAction)startFlashing:(id)sender {
    self.mutableIndexes = [self.indexes mutableCopy];
    [self flashRandomly];
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top