//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;
}