关灯游戏

TouchView.h

#import <UIKit/UIKit.h>
@interface TouchView : UIView
@property (nonatomic,retain)NSMutableArray * lightArray;
@end

TouchView.m

#import "TouchView.h"
@implementation TouchView
- (void)dealloc
{
    [_lightArray release ];
    _lightArray = nil;
    [super dealloc];
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
          
        _lightArray = [[NSMutableArray alloc]init];
          
    }
      
    [self createButton];//方法调用
    return self;
}
- (void)createButton
{
//每一个button的XY值
float lightX = 8, lightY = 5;
      
for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
          
        UIButton * lightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [lightButton setFrame:CGRectMake(lightX, lightY, 55, 70)];
          
        //正常状态图片
        lightButton.adjustsImageWhenHighlighted = NO;
        [lightButton setBackgroundImage:[UIImage imageNamed:@"LightOff.jpg"] forState:UIControlStateNormal];
          
        //点击状态图片
        [lightButton setBackgroundImage:[UIImage imageNamed:@"No.png"] forState:UIControlStateSelected];
          
        //开始时随机点亮
        if (arc4random()%2) {
            [lightButton setSelected:true];//1
        }else{
            [lightButton setSelected:false];//0
        }
          
          
        //设定TAG值;i:行,j:列;
        lightButton.tag = 100 + 10*i + j;
          
        //添加点击事件
        [lightButton addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
          
        [self addSubview:lightButton];
          
        lightX += 63;
          
    }
      
    lightY += 80;
    lightX = 8;
}
      
    //傻瓜模式;开启傻瓜模式时要把随机关掉
//    [self setLevel:@[@(100),@(111),@(122),@(133),@(144)]];
      
}
//响应事件
- (void)buttonTapped:(UIButton *)selectedButton
{
      
    int tag = selectedButton.tag;
    selectedButton.selected = !selectedButton.selected;//取反
      
    //求出点击BUTTON的上面那个BUTTON
    UIButton * upButton = (UIButton *)[self viewWithTag:tag - 10];
    upButton.selected = !upButton.selected;//取反实现状态更改
    //求出点击BUTTON的下面那个BUTTON
    UIButton * downButton = (UIButton *)[self viewWithTag:tag + 10];
    downButton.selected = !downButton.selected;//取反实现状态更改
    //求出左边的BUTTON
    UIButton * leftButton = (UIButton *)[self viewWithTag:tag - 1];
    leftButton.selected = !leftButton.selected;//取反实现状态更改
    //求出右边的BUTTON
    UIButton * rightButton = (UIButton *)[self viewWithTag:tag + 1];
    rightButton.selected = !rightButton.selected;//取反实现状态更改
      
}
//傻瓜模式;开启傻瓜模式时要把随机关掉
//- (void)setLevel:(NSArray *)buttonsTag
//{
//    for (NSNumber * tag in buttonsTag) {
//        UIButton * lightButton = (UIButton *)[self viewWithTag:[tag integerValue]];
//        [self buttonTapped:lightButton];
//    }
//}
@end


本文出自 “Ghost霍的��博客” 博客,谢绝转载!

你可能感兴趣的:(游戏,import,interface,frame)