用UIBUtton实现关灯小游戏


使用UIButton,实现简单的关灯小游戏,

思路:1.首先用两个循环把UIButon放到View上

2,实现点击按钮,被点击的图片本身及其上下左右(tag值)的灯被点亮(可以用UIButton的UIControlStateNormal,UIControlStateSelected两个状态实现)

3.反转被点击按钮及其四周的状态

4.还可以设置关卡

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    LightOffView *lightView = [[LightOffView alloc] initWithFrame:[UIScreen mainScreen].bounds];

    [self.view addSubview:lightView];

    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 375, 667)];

    image.image = [UIImage imageNamed:@"666.jpg"];

    [lightView addSubview:image];

    [lightView release];

    

       for (int i = 0; i < 6; i ++) {

        for (int j = 0; j < 8; j++) {

            UIButton *lightBtn = [UIButton buttonWithType:UIButtonTypeCustom];lightBtn.frame = CGRectMake(30 + 55 * i, (j + 1) * 55, 55, 55);

            lightBtn.backgroundColor = [UIColor redColor];

            [lightBtn setImage:[UIImage imageNamed:@"1.png"] forState:

             UIControlStateNormal];

            [lightBtn setImage:[UIImage imageNamed:@"2.png"] forState:

             UIControlStateSelected];

            [lightBtn addTarget:self action:@selector(handleButton:) forControlEvents:UIControlEventTouchDown];

            lightBtn.tag = 100 + i + j * 10;

            [self.view addSubview:lightBtn];

//            [self setLevel:@[@102, @101, @103]];

         }

    }

}


- (void)handleButton:(UIButton *)btn{

     btn.selected = !btn.selected;

    UIButton *leftBtn = (UIButton *)[self.view viewWithTag:btn.tag - 1];

    leftBtn.selected = !leftBtn.selected;

    UIButton *rightBtn = (UIButton *)[self.view viewWithTag:btn.tag + 1];

    rightBtn.selected = !rightBtn.selected;

    UIButton *upBtn = (UIButton *)[self.view viewWithTag:btn.tag - 10];

    upBtn.selected = !upBtn.selected;

    UIButton *downBtn = (UIButton *)[self.view viewWithTag:btn.tag + 10];

    downBtn.selected = !downBtn.selected;


}


//可以通过tag值提前让某些灯亮,以此来设置关卡

- (void)setLevel:(NSArray *)buttonsTag{

    for (NSNumber *tag in buttonsTag) {

        UIButton *lightBtn = (UIButton *)[self.view viewWithTag:[tag integerValue]];

        [self handleButton:lightBtn];

    }

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

    if ([self isViewLoaded] && !self.view.window) {

        self.view = nil;

    }

}



@end



注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: