貪喫蛇 for iOS

VC.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

VC.m

#import "ViewController.h"
#import "BackGround.h"
#import "UIView+setGet.h"
typedef NS_ENUM(NSInteger, RefrushType) {
    refrushTypeUp,
    refrushTypeDown,
    refrushTypeLeft,
    refrushTypeRight,
    refrushTypeNewApple
};


@interface ViewController ()
@property (nonatomic ,assign)RefrushType refrushType;
@property (nonatomic ,assign)RefrushType lastRefrushType;

@property (weak, nonatomic) IBOutlet BackGround *backGroundView;

@property (weak, nonatomic) IBOutlet UIButton *beginButton;


@property (nonatomic, assign)aaPoint point;

@property (nonatomic, assign)aaPoint randomPoint;

@property (nonatomic, strong)NSTimer *mainTimer;

@property (nonatomic, assign)BOOL isPlaying;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _backGroundView.delegate = self;
    _refrushType = refrushTypeUp;
    _lastRefrushType = refrushTypeUp;
    [self initAgame];

}

- (void)initAgame {
    _point.X = 4;
    _point.Y = 9;
    [_backGroundView clearAllPoint];
    [_backGroundView overDrawingWithAddPoint:_point];
    [self.backGroundView showAnNewPoint];
}

#pragma mark - 代理方法  BackGroundDelegate
- (void)backGroundSnaxHeadPoint:(CGPoint)point andSnaxBody:(NSArray *)cPoints {
    BOOL eatedSelf = [self eatedBodyWithHead:point andSnaxBody:cPoints];
    if (point.x < space || point.y < space || point.x >= ([UIScreen mainScreen].bounds.size.width - space) || point.y >= ([UIScreen mainScreen].bounds.size.width - space) || eatedSelf) {
        self.mainTimer.fireDate = [NSDate distantFuture];
        _isPlaying = NO;
        _refrushType = refrushTypeUp;
        _lastRefrushType = refrushTypeUp;
        __weak typeof(self) weakSelf = self;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"哎呦" message:@"完蛋" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"醉了!!!" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [_beginButton setTitle:@"開始" forState:UIControlStateNormal];
            [weakSelf initAgame];
        }];
        [alert addAction:action];
        [weakSelf presentViewController:alert animated:YES completion:^{
        }];
    }

}
//咬到自己
- (BOOL)eatedBodyWithHead:(CGPoint)point andSnaxBody:(NSArray *)cPoints {
    if (cPoints.count >= 3) {//大於3就咬到自己
        for (int i = 3; i < cPoints.count; i ++) {
            CGPoint bodyPoint = [[cPoints objectAtIndex:i]CGPointValue];
            if (point.x == bodyPoint.x && point.y == bodyPoint.y) {
                return YES;
            }
        }
    }
    return NO;
}


#pragma mark --按鈕方法
- (IBAction)beginOrPause:(UIButton *)sender {

    if (!_isPlaying) {
        if (!_mainTimer) {
            _mainTimer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
        }
        _mainTimer.fireDate = [NSDate date];
        [sender setTitle:@"暫停" forState:UIControlStateNormal];
    }else
    {
        _mainTimer.fireDate = [NSDate distantFuture];
        [sender setTitle:@"開始" forState:UIControlStateNormal];

    }
    _isPlaying = !_isPlaying;
}

- (void)timerMethod {

    switch (_refrushType) {
        case refrushTypeUp:
        {
            if(_lastRefrushType == refrushTypeDown) {
                _refrushType = refrushTypeDown;
                [self downdown];break;
            }
            _lastRefrushType = refrushTypeUp;
            [self upup];
        }
            break;
            case refrushTypeDown:
        {
            if (_lastRefrushType == refrushTypeUp) {
                _refrushType = refrushTypeUp;
                [self upup];break;
            }
            _lastRefrushType = refrushTypeDown;
            [self downdown];
        }
            break;
            case refrushTypeLeft:
        {
            if (_lastRefrushType == refrushTypeRight) {
                _refrushType = refrushTypeRight;
                [self rightright];break;
            }
            _lastRefrushType = refrushTypeLeft;
            [self leftleft];
        }
            break;
            case refrushTypeRight:
        {
            if (_lastRefrushType == refrushTypeLeft) {
                _refrushType = refrushTypeLeft;
                [self leftleft];break;
            }
            _lastRefrushType = refrushTypeRight;
            [self rightright];
        }
            break;
        default:
            break;
    }
    [_backGroundView showAnNewPoint];
}

- (IBAction)up:(UIButton *)sender {
    if (!_isPlaying) {
        return;
    }
    _refrushType = refrushTypeUp;
}
- (void)upup {
    if (_point.Y < 1) {
        return;
    }
    _point.Y -= 1;
    [_backGroundView drawTheFirstPoint:_point];
}


- (IBAction)left:(UIButton *)sender {
    if (!_isPlaying) {
        return;
    }
    _refrushType = refrushTypeLeft;
}
- (void)leftleft {
    if (_point.X < 1) {
        return;
    }
    _point.X -= 1;
    [_backGroundView drawTheFirstPoint:_point];
}


- (IBAction)down:(UIButton *)sender {
    if (!_isPlaying) {
        return;
    }
    _refrushType = refrushTypeDown;
}
- (void)downdown {
    if (_point.Y > 23) {
        return;
    }
    _point.Y += 1;
    [_backGroundView drawTheFirstPoint:_point];
}


- (IBAction)right:(UIButton *)sender {
    if (!_isPlaying) {
        return;
    }
    _refrushType = refrushTypeRight;
}
- (void)rightright {
    if (_point.X > 23) {
        return;
    }
    _point.X += 1;
    [_backGroundView drawTheFirstPoint:_point];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

BackGround.h

#import <UIKit/UIKit.h>
#import "UIView+setGet.h"
@interface BackGround : UIView

@property (nonatomic, assign)id   delegate;

- (void)overDrawingWithAddPoint:(aaPoint)point;

- (void)clearAllPoint;

- (void)showAnNewPoint;

- (void)drawTheFirstPoint:(aaPoint)point;

@end

@protocol BackGroundDelegate <NSObject>

- (void)backGroundSnaxHeadPoint:(CGPoint)point andSnaxBody:(NSArray *)cPoints;

@end

BackGround.m

#import "BackGround.h"

@interface BackGround()


@property (nonatomic, strong)NSMutableArray *points;

@property (nonatomic, assign)CGPoint applePoint;

@property (nonatomic, assign)CGPoint preparePoint;

@property (nonatomic, assign)CGPoint lastPoint;

@property (nonatomic, assign)BOOL  appleShow;
@end


@implementation BackGround

- (void)clearAllPoint {
    _points = nil;
    _appleShow = NO;
}


- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
        for (int i = 0; i <= self.bounds.size.width / space; i ++) {
            if (i == 0 || i == self.bounds.size.width / space) {
                CGContextSetLineWidth(context, space * 2);
            }
            else
            {
                CGContextSetLineWidth(context, 1);
            }
            //X
            CGPoint aPoints[2];
            aPoints[0] =CGPointMake(0, i * space);
            aPoints[1] =CGPointMake(self.bounds.size.width, i * space);
            CGContextAddLines(context, aPoints, 2);
            CGContextDrawPath(context, kCGPathStroke);
            //Y
            CGPoint bPoints[2];
            bPoints[0] =CGPointMake(i * space, 0);
            bPoints[1] =CGPointMake(i * space, self.bounds.size.width);
            CGContextAddLines(context, bPoints, 2);//添加線
            CGContextDrawPath(context, kCGPathStroke); //根據座標繪製路徑
        }

    CGContextSetLineWidth(context, space);
    for (int i = 0; i <_points.count; i ++) {
        if (i == 0) {
            CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);
        }else{
            CGContextSetRGBStrokeColor(context, 0.5, 0.5, 0.5, 1);
        }


        CGPoint bPoints[2];//座標點 畫��
        bPoints[0] = [[_points objectAtIndex:i]CGPointValue];
        bPoints[1] = bPoints[0];
        bPoints[1].x = bPoints[0].x + space;
        CGContextAddLines(context, bPoints, 2);//添加線
        CGContextDrawPath(context, kCGPathStroke); //根據座標繪製路徑
    }
    if (_appleShow) {//顯示果子
        CGPoint bPoints[2];//座標點
        CGContextSetRGBStrokeColor(context, 1, 1, 1, 1);
        bPoints[0] = _applePoint;
        bPoints[0].x = _applePoint.x + space / 2;
        bPoints[1] = _applePoint;
        bPoints[1].x = _applePoint.x + space / 2;
        CGContextSetLineWidth(context, space * 1.5);
        CGContextSetLineCap(context, kCGLineCapRound);
        CGContextAddLines(context, bPoints, 2);//添加線
        CGContextDrawPath(context, kCGPathStroke); //根據座標繪製路徑
    }
}


//重畫
- (void)overDrawingWithAddPoint:(aaPoint)point {
    if (!_points) {
        _points = [[NSMutableArray alloc]init];
    }
    for (int i = 0; i < 3; i ++) {
        CGPoint beginPoint = CGPointMake((point.X + i) * space, (point.Y + 0.5)*space);
        [_points addObject:[NSValue valueWithCGPoint:beginPoint]];
    }
    [self setNeedsDisplay];
}


//追蹤頭部位置
- (void)drawTheFirstPoint:(aaPoint)point {
    CGPoint firstPoint = [[_points firstObject]CGPointValue];
    _lastPoint = [[_points lastObject]CGPointValue];
    firstPoint = CGPointMake(point.X* space, (point.Y + 0.5)*space);
    [_points removeLastObject];
    [_points insertObject:[NSValue valueWithCGPoint:firstPoint] atIndex:0];
    [self setNeedsDisplay];
    if (_appleShow && firstPoint.x == _applePoint.x && firstPoint.y == _applePoint.y) {
        [_points addObject:[NSValue valueWithCGPoint:_lastPoint]];
        [self setNeedsDisplay];
        _appleShow = NO;
    }
    if ([self.delegate respondsToSelector:@selector(backGroundSnaxHeadPoint: andSnaxBody:)]) {
        [self.delegate backGroundSnaxHeadPoint:firstPoint andSnaxBody:_points];
    }
}

#pragma mark - showApple
//顯示果子
- (void)showAnNewPoint {
    if (_appleShow) {
        return;
    }
    CGPoint eatPoint = [self randomAnPoint];
    for (NSValue * value  in _points) {
        NSValue *point = [NSValue valueWithCGPoint:eatPoint];
        if (value == point) {
            [self showAnNewPoint];
        } else
        {
            _applePoint = eatPoint;
            _appleShow  = YES;
            [self setNeedsDisplay];
        }
    }
}
//隨機果子位置
- (CGPoint)randomAnPoint {
    CGFloat X = arc4random() % 23 + 1;
    CGFloat Y = arc4random() % 23 + 1;
    CGPoint eatPoint = CGPointMake(X * space, (Y + 0.5)*space);
    return eatPoint;
}

代碼已上傳到這裏

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章