2014-05-14 1 views
-1

나는 퍼즐 게임과 일치하는 메모리 기반의 작업을하고 있습니다. 이를 위해서는 시퀀스에서 버튼을 임의로 빛낼 필요가 있습니다. 나는 샘플 퍼즐, 게임 & 코드 스 니펫을 1 주일 이상 인터넷 검색을 해왔다. 그러나 시작하기에 적절한 샘플 프로젝트 나 소스를 추적 할 수 없었다.일련의 버튼에서 UIButton을 무작위로 발광시키는 방법

조명 (버튼)을 배경 이미지 (모방)를 변경하여 빛나고 있습니다. 스토리 보드에서 이미 버튼 (안정된 상태의 색이있는 전구)의 기본 이미지를 설정했습니다. IBOutletCollection의 NSMutableArray 즉 tapLightButtons를 사용했습니다. 다음은 무작위 모드에서 빛의 시퀀스를 통해 게임 경험을 얻으려고 시도한 것입니다. tapLightButtons

-(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; 
} 

자동 랜덤 방식으로 잇달아 광선 의아해 버튼 (조명)를 보유하는 배열이다.

lightArray은 모든 기본 (초기)의 배열을 포함 버튼의 이미지 (오프 모드 등)

initialButtonImages을 (빛났습니다 영향을 생산하는 플래시) 모든 적절한 컬러 이미지를 유지하는 배열입니다 일부는 어떻게 내가 부분적으로 모든 배열을 섞은 후에도 놀랍게도 원하는대로 얻을 수 있었는데, 빛나는 이미지가 안정된 (색이없는 모드의 빛) 상태이어야하고 다시 설정 한 후에 안정된 이미지가 나타나야하므로 여전히 순서가 변한다. 빛이 실제로 빛을 발하기 전에 그 빛을 맞추어 라. .

스택 교환에서 게임 개발 사이트에 question 게시 됨! 무작위 순서에서 색깔의 빛

enter image description here

어떻게 제대로 빛을 할 수있는 버튼의 점멸 후 더 나은 이해

enter image description here

에 대한

게임 화면?

+0

나는 사람들이 공개 포럼에서 모든 생각을 넣어 그들 중 대부분은 일부 클라이언트를 만들기 때문에 난 그래서 더 많은 정보를 제공해주세요 "@amar NDA – amar

+0

의 위반을보고 실패 와서 궁금해 우리 너를 도울 수있어? ","너는 무엇을하려고 하느냐 ","왜 너는 이러는거야? "여기에 전문가와 운영자가 자주받는 의견입니다. 귀하의 의견에 대한 어떤 tq, 내가 좀 더 구체적인 방식으로 내 질문을 수정했습니다, 지금 확인하십시오 :) –

+0

짧은 시간에 특정 솔루션을 줄 수 있다고 생각하지만 포인터 하위 클래스 UIButton 귀하의 algo 및 관련 적절한 추가 상태를 개최하는 것 같아요 반응성 코코아가 도움이 될 것입니다 – amar

답변

2

이 코드를 사용하면 코드가 더 간단 해집니다. IB에 9 개의 사용자 지정 단추 배열을 만들어 콘센트 컬렉션에 추가했습니다. 나는 버튼을 하위 클래스로 만들고 flashWithOnTime : 메서드를 추가하여 버튼 자체가 일반 상태와 강조 표시된 상태 사이를 전환하도록 돌았습니다.

이 버튼 서브 클래스의 메소드이다

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

이 (a 버튼 탭에서) 순서를 시작 뷰 컨트롤러의 코드이다. 셔플보다는 배열에서 임의의 인덱스를 선택한 다음 해당 항목을 삭제하여 다시 선택할 수 없습니다. offImageWithSolidColor 및 onImageWithSolidColor 메서드는 이미지를 만드는 데 사용한 메서드 일뿐입니다. 때때로

@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]; 
} 
+0

답변의 모든 부분을 이해할 수 있었지만 너무 감사합니다. 이유를 이해할 수 없습니다. 충돌 : "- [UIButton flashWithOnTime :] : 인스턴스가 0x97a2bd0으로 전송 된 인식 할 수없는 선택기".... 또한 친절하게도 내 구현 [code] (http://pastebin.com/rFMamu1m)이 맞는지 아닌지 확인하고 다시 한 번 감사드립니다. :) –

+0

@EshwarChaitanya, IB의 일부 또는 모든 버튼 클래스를 TTLFlashingButtons로 변경하지 않았기 때문에 오류가 발생했습니다. 오류는 flashWithOnTime : 메시지가 하위 클래스가 아닌 UIButton으로 전송되고 있다는 것입니다. 코드 구현은 괜찮아 보입니다. – rdelmar

+0

덕분에 도움이되었지만 버튼이 빛나고 있지만 단 한 번만 ......... 계속해서 멈추지 않고 계속해서 멈 춥니 다. 재사용을위한 색인을 제거했지만 더 이상 작업에 지연이 추가됩니다. –