IOS开源项目--打地鼠(附源码)

来源:互联网 发布:top域名注册免费 编辑:程序博客网 时间:2024/05/15 10:07

打地鼠想必大家小时候都玩过,下面我们就通过多线程以及代理传值实现一个打地鼠游戏。
首先我们需要一个地鼠类。地鼠类中,需要用到代理。如果有同学对于代理还不够清楚的话,请参考微博:
http://blog.csdn.net/lee727n/article/details/70833160
地鼠类继承uibutton,定义协议,以及协议方法 .h中

@protocol MouseDelegate <NSObject>- (void)successAction;- (void)failAction;@end@interface Mouse : UIButton@property (nonatomic, weak)id<MouseDelegate> delegate;@end

. m 中 重写frame初始化方法

- (instancetype)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self) {        self.backgroundColor = [UIColor redColor];        [self setBackgroundImage:[UIImage imageNamed:@"11"] forState:UIControlStateNormal];        [self addTarget:self action:@selector(clicked) forControlEvents:UIControlEventTouchUpInside];        [self setTitle:@"3" forState:UIControlStateNormal];        [self setTitleColor:[UIColor redColor] forState:UIControlStateNormal];        self.titleLabel.font = [UIFont systemFontOfSize:22];        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{            for (NSInteger i = 0; i < 3; i++) {                [NSThread sleepForTimeInterval:.5];                //判断地鼠是否被删除了 如果删除了就不再修改title                if (!self.superview) {                    break;                }                dispatch_async(dispatch_get_main_queue(), ^{                    int time = [[self titleForState:UIControlStateNormal] intValue] - 1;                    [self setTitle:@(time).stringValue forState:UIControlStateNormal];                    if (time==0) {                        [self removeFromSuperview];                        //失败次数+1                        [self.delegate failAction];                    }                });            }        });    }    return self;}

添加点击方法

- (void)clicked{    [self removeFromSuperview];    //成功次数+1    [self.delegate successAction];}

主界面viewController中,遵守协议,需要两个label记录成功和失败次数

@interface ViewController ()<MouseDelegate>@property (weak, nonatomic) IBOutlet UILabel *failLabel;@property (weak, nonatomic) IBOutlet UILabel *successLabel;

实现代理方法

- (void)successAction{    self.successLabel.text = @(self.successLabel.text.integerValue+1).stringValue;}- (void)failAction{    self.failLabel.text = @(self.failLabel.text.integerValue+1).stringValue;}

每0.8秒生成一个地鼠并且加到view上。

- (void)viewDidLoad {    [super viewDidLoad];    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        while (YES) {            [NSThread sleepForTimeInterval:.8];            dispatch_async(dispatch_get_main_queue(), ^{                Mouse *m = [[Mouse alloc]initWithFrame:CGRectMake(arc4random()%355, arc4random()%647, 50, 50)];                m.delegate = self;                [self.view addSubview:m];            });        }    });}

实现效果如下,每个地鼠有1.5秒的时间去点击,每0.5秒倒数计数-1。点中地鼠成功数+1,倒数计数结束未点击地鼠,失败次数+1。效果参考下图:
这里写图片描述
具体源代码请通过github下载:
https://github.com/lee727n/bit-mouse-game

0 0
原创粉丝点击