首页 > 代码库 > OC实现简单的关灯游戏

OC实现简单的关灯游戏

//将灯的图片在视图上布局,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];
        }
        
    }
}

OC实现简单的关灯游戏