码迷,mamicode.com
首页 > 其他好文 > 详细

OC实现简单的关灯游戏

时间:2014-08-24 10:21:02      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   for   ar   2014   cti   log   size   

//将灯的图片在视图上布局,5行5列
    for (int i = 0; i < 5; i++) {
        for (int j = 0 ; j < 5; j++) {
            UIButton *lightButton = [UIButton buttonWithType:UIButtonTypeSystem];
            lightButton.frame = CGRectMake(i * 64, 120 + (j *64), 64, 64);
            [lightButton setBackgroundImage:[UIImage imageNamed:@"2.png"] forState:UIControlStateNormal];
            [lightButton addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
            [self.window addSubview:lightButton];
            lightButton.tag = 100 + j + 10 * i;//左右button的tag相差1,上下button的tag相差10
        }
    }

//button的点击事件
- (void)click:(UIButton *)button

{   //定义数组存储所点击的button和他的上下左右的button
    int array[5] = {button.tag , button.tag + 1, button.tag + 10, button.tag - 1, button.tag - 10};
    //判断当前buton的背景图片是不是亮灯(2.png是亮等图片名)
    if ([button.currentBackgroundImage isEqual:[UIImage imageNamed:@"2.png"]]) {
        //遍历数组
        for (int i = 0; i < 5; i++) {
            UIButton *aButton = (UIButton*)[self.window viewWithTag:array[i]];
            //判断所点击button的前后左右button的状态,如果是灭着的灯就将其背景图片变为亮着的灯(1.png是灭着的灯的图片)
            if ([aButton.currentBackgroundImage isEqual:[UIImage imageNamed:@"1.png"]]) {
                [ aButton setBackgroundImage:[UIImage imageNamed:@"2.png"] forState:UIControlStateNormal];
            }  else {
                [aButton setBackgroundImage:[UIImage imageNamed:@"1.png"] forState:UIControlStateNormal];
            }
        }
        //else判断当前buton的背景图片是不是灭灯
    } else  {
        for (int i = 0; i < 5; i++) {
            UIButton *aButton = (UIButton*)[self.window viewWithTag:array[i]];
            if ([aButton.currentBackgroundImage isEqual:[UIImage imageNamed:@"2.png"]]) {
                [ aButton setBackgroundImage:[UIImage imageNamed:@"1.png"] forState:UIControlStateNormal];
            } else
                [aButton setBackgroundImage:[UIImage imageNamed:@"2.png"]  forState:UIControlStateNormal];
        }
        
    }
}

bubuko.com,布布扣

OC实现简单的关灯游戏

标签:blog   http   io   for   ar   2014   cti   log   size   

原文地址:http://blog.csdn.net/canyeyj/article/details/38793759

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!