#import "ViewController.h" #import "Ball.h" @interface ViewController () @property int score; @property (strong, nonatomic) NSTimer * timer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self.ball addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTouch:)]]; [self startRandomLocationTimer]; [self startScoreTimer]; } // creates a new random location to move the ball to. -(CGPoint)createRandomLocationFor:(CGPoint)currentLocation { CGPoint newLocation = currentLocation; newLocation.y = (float)random() / RAND_MAX * 940 + 32; newLocation.x = (float)random() / RAND_MAX * 704 + 32; NSLog(@"moving to %f %f", newLocation.x, newLocation.y); return newLocation; } // moves the ball to a random location - (void)moveBallToRandomLocation { [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^ { self.ball.center = [self createRandomLocationFor:self.ball.center]; } completion:^(BOOL b) { [self startRandomLocationTimer]; }]; } // increment game score -(void)incrementScore { [self increaseScore:1]; } // starts a timer that will move the ball to a random location - (void)startRandomLocationTimer { self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(moveBallToRandomLocation) userInfo:nil repeats:NO]; } // starts a timer to increment the score while the game is running. - (void)startScoreTimer { [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(incrementScore) userInfo:nil repeats:YES]; } // when the ball is touched -(void)onTouch:(UIGestureRecognizer *)sender { [self moveBallToRandomLocation]; [self stopTimer]; [self increaseScore:2]; } -(void)increaseScore:(int) amount { self.score += amount; self.scoreLabel.text = [NSString stringWithFormat:@"%d", self.score]; } -(void)stopTimer { [self.timer invalidate]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end