Don't Touch whiteBlock

2016-08-14  本文已影响11人  蓝蓝的白云
随笔写了一个简单实现别踩白块的小demo,具体实现思路如下:创建一个6行4列的button界面,每行采用随机数随机一个button,设置此button的背景颜色为黑色,其他button背景均为黑色。当点击白色button后,弹框显示点击错误,界面重新归0,当点击黑色button后,上一行的黑色button的背景颜色延续到下一行,然后第一行随机一个button的颜色为黑色,其余为白色。实现如下:

1. 创建button按钮

- (void)setupButton
{ 
    for (int i = 0; i<6; i++) {
         NSInteger black =kScreenRandom;
        for (int j = 0; j<4; j++) {
            self.button = [UIButton buttonWithType:(UIButtonTypeCustom)];
            _button.frame = CGRectMake(kScreenWidth/4*j, kScreeHeight/6*i, kScreenWidth/4, kScreeHeight/6);
            _button.layer.borderWidth = 1;
            [_button setBackgroundColor:[UIColor whiteColor]];
            _button.layer.borderColor= [[UIColor blackColor]CGColor];
            _button.tag = 4*i+j+1;
            [self.view addSubview:_button];
            if (j==black) {
                [_button setBackgroundColor:[UIColor blackColor]];
            }
            [_button addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        }
    }
}
// button 点击事件
- (void)buttonAction:(UIButton *)button
{
    if ([button.backgroundColor  isEqual:[UIColor blackColor]]) {
        for (  int i = 24; i>=5; i--) {
            UIButton *button1 = [self.view viewWithTag:i];
            UIButton *button2 = [self.view viewWithTag:i-4];
    // 将上一排button的颜色传递给下一排
            button1.backgroundColor = button2.backgroundColor;
        }
    }else{
        [self whiteAction];
    }
   // 随机将第一排的某一个button设置为黑色     
    int a =kScreenRandom+1;
    for ( int i =1 ; i<5; i++) {
         if(i==a)
         {
            [[self.view viewWithTag:i] setBackgroundColor:[UIColor blackColor]];
         }
        else
        {
          [[self.view viewWithTag:i] setBackgroundColor:[UIColor whiteColor]];
        }
    }
    _count++;
}

2.弹出框

- (void)whiteAction
{
    NSString *string = [NSString stringWithFormat:@"得分:%ld",_count];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:string message:@"闯关失败" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"重新开始" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        // 重新开始
        [self setupButtonRestart];
    }];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
    _count=0;
}

3.重新开始

- (void)setupButtonRestart
{
    for (int i = 0; i<24; i++) {
        [self.view viewWithTag:i+1].backgroundColor = [UIColor whiteColor];
    }
    for (int j = 0; j<6; j++) {
        NSInteger a = arc4random()%3;
    //通过tag找到对应button,设置背景颜色
    [self.view viewWithTag:4*j+a+1].backgroundColor = [UIColor blackColor];
    }  
}
欢迎加群192699811讨论,相互学习
上一篇 下一篇

猜你喜欢

热点阅读