打地鼠的小玩意

//1声明属性

//记录随机生成的序号即地鼠钻出来的洞号

@interface ViewController ()

@property(nonatomic, assign)NSInteger index;

//记录是否可以打个地鼠

@property(nonatomic, assign)BOOL flag;

//记录已经打中郭多少地鼠

@property(nonatomic, assign)NSInteger n;

//显示游戏结果

@property(nonatomic, strong)UILabel *label;

//定时器对象

@property(nonatomic, strong)NSTimer *timer;

@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

   //进行数据的初始化

    _index = 100;

    _n = 0;

    //可以打地鼠

    _flag = YES;

    //用于批量创建按钮

    int count = 0;

   //进行界面的初始化

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

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

            UIButton *button = [UIButton

            buttonWithType:UIButtonTypeSystem];

            button.frame = CGRectMake(20+(100+20)*j, 50+(100+20)*i, 100, 100);

            [button setBackgroundImage:[UIImage imageNamed:@"1"] forState:UIControlStateNormal];

            button.tag = 100 + count++;

            [button addTarget:self

                       action:@selector(hitAction:)

             forControlEvents:UIControlEventTouchDragInside];

            

            [self.view addSubview:button];

        }

    }

    self.label = [[UILabel alloc]

                  initWithFrame:CGRectMake(100, 500 , 150, 50)];

    self.label.backgroundColor = [UIColor yellowColor];

    self.label.text = @"亲,还没开始打呢";

    [self.view addSubview:self.label];

    

    //定时器的创建

    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];

    

}


- (void)hitAction:(UIButton *)sender{

    

    //当点击的按钮的tag和生成的随机数是一样大饿,并且是第一次打击的时候有效。

    if((sender.tag == _index)&&_flag){

        [sender setBackgroundImage:[UIImage imageNamed:@"3"] forState:UIControlStateNormal];

        _n++;

        self.label.text = [NSString stringWithFormat:@"打中%ld",_n];

        _flag = NO;

        

    }

}


- (void)timerAction{

    //取到原来的button

    UIButton *button  = (UIButton *)[self.view viewWithTag:_index];

    //将图片还原

    [button setBackgroundImage:[UIImage imageNamed:@"1"] forState:UIControlStateNormal];

    //随机产生一个数

    _index = random() % 6 + 100;

    //根据随机数取到button

    UIButton *but = (UIButton *)[self.view viewWithTag:_index];

    //设置图片

    [but setBackgroundImage:[UIImage imageNamed:@"2"] forState:UIControlStateNormal];

    //标记现在可以进行打地鼠了

    _flag = YES;

    

    

    

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值