Monday, March 4, 2013

Zombie Game (Objective C)


@interface ViewController : UIViewController <UIAlertViewDelegate>
// i.e. i want to listen to the UI Alert View

@property (strong, nonatomic) IBOutlet UILabel *timeLabel;
@property (strong, nonatomic) IBOutlet UILabel *scoreLabel;
- (IBAction)buttonPressed:(id)sender;
@property (strong, nonatomic) IBOutlet UIImageView *staticPea;

@end

-------------------------


@implementation ViewController {
    int score;
    int seconds;
    NSTimer *timer;
    UIImageView *pea;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg2.png"]];
    
    [self setupGame];
    
}

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

-(void)setupGame {
    
    [pea removeFromSuperview];
                
    seconds = 5;
    score = 0;
    
    _timeLabel.text = [NSString stringWithFormat:@"%i", seconds];
    _scoreLabel.text = [NSString stringWithFormat:@"%i", score];
    
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(subtractTime) userInfo:nil repeats:YES];
}


-(void)subtractTime {
    
    seconds--;
    _timeLabel.text = [NSString stringWithFormat:@"%i", seconds];
    
    if (seconds <= 5){
        _timeLabel.textColor = [UIColor redColor];
    }
    
    if (seconds <=0){
        [timer invalidate];
        UIAlertView *alert = [[UIAlertView alloc]
            initWithTitle:@"Game Over!"
            message:[NSString stringWithFormat:@"Game Over! Your score was %i", score]
            delegate:self
            cancelButtonTitle:@"OK"
            otherButtonTitles:@"Restart", nil];
        [alert show];
    }
    
}

-(void)restartGame {
    [timer invalidate]; // just to be safe

    [self setupGame];
}

- (IBAction)buttonPressed:(id)sender {
    
    pea = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pea"]];
    [pea setFrame:CGRectMake(83, 115, 35, 35)];
    [self.view addSubview:pea];
    
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        [pea setFrame:CGRectMake(149, 47, 35, 35)];
    } completion:^(BOOL finished) {
        [pea setFrame:CGRectMake(134, 40, 66, 50)];
        [pea setImage:[UIImage imageNamed:@"pea_splat"]];
        score++;
        _scoreLabel.text = [NSString stringWithFormat:@"%i", score];
    }];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1){
        NSLog(@"Restart Button Selected");
        [self restartGame];
    }
    
    if (buttonIndex == 0)
        NSLog(@"Cancel Button Selected");
}

No comments:

Post a Comment