初学UI之关灯游戏

来源:互联网 发布:深圳号码数据 编辑:程序博客网 时间:2024/05/09 10:33

 



#import "light.h"

@implementation light

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //设置当前View的tag值,并设背景颜色为黑色
        self.tag=1000;
        self.layer.backgroundColor=[[UIColor blackColor]CGColor];
        
        //用循环 建36个Button 并设置Tag值
        for (int i=0; i<6; i++) {
            for (int j=0; j<6; j++) {
                UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
                button.frame=CGRectMake(50*i+10, 50*j+50, 50, 50);
                [button setBackgroundImage:[UIImage imageNamed:@"1.jpg"] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"2.jpg"] forState:UIControlStateSelected];
                [button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
                [self addSubview:button];
                button.tag=100+10*(i+1)+(j+1);
            }
        }
        
        //初始随机出几个灯
        [self level];
        
        //关数
        self.x = 1;
    }
    return self;
}


//利用alertview的but来进入下一关
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
    }else{
        [self level];
    }
}

//初始随机亮灯泡,和关卡设置
-(void)level
{
    for (int i = 0; i<3+self.x; i++) {
        [self randomFuncation];
    }
    self.x++;
}

//随机亮一个but
-(void)randomFuncation
{
    UIView *view = [self viewWithTag:1000];
    int x = (arc4random()%6+1)*10;
    int y = arc4random()%6+1;
    UIButton *but = (UIButton*)[view viewWithTag:x+y+100];
    [self action:but];
}

//Button点击触发事件
-(void)action:(UIButton *)button
{
    int tag=button.tag;
    button.selected=!button.selected;
    UIButton *upButton=(UIButton *) [self viewWithTag:tag-10];
    upButton.selected=!upButton.selected;
    UIButton *downButton=(UIButton *) [self viewWithTag:tag+10];
    downButton.selected=!downButton.selected;
    UIButton *rightButton= (UIButton *)[self viewWithTag:tag+1];
    rightButton.selected=!rightButton.selected;
    UIButton *leftButton=(UIButton *)[self viewWithTag:tag-1];
    leftButton.selected=!leftButton.selected;
    [self win];
}

//判断是否成功过关
-(void)win{
    int i=0;
    UIView *view=[self viewWithTag:1000];
    for (UIButton *button in [view subviews]) {
        if ((button.selected==UIControlStateNormal)) {
            i++;
        }
    }if (i==36) {
        UIAlertView *view=[[UIAlertView alloc]initWithTitle:@"闯关成功" message:@"恭喜你,你已经成功闯过这一关" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"下一关", nil];
        [view show];
    }
}

特别注意:如果你要加Label显示当前关数时,请不要加到button视图上. 因为在判断是否成功通关时,label也会判断进去,从而产生崩溃.

原创粉丝点击