summaryrefslogtreecommitdiff
path: root/Wobble/ViewController.m
blob: 0443d4c29b1a6d67f1b24044bb9404127c255fd0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#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