iPhoneミニカーあつめる

UIScrollViewを使って、2000×2000の画面の中にちらばったミニカーをあつめるiPhoneゲームを書いてみます。


動作イメージ
XcodeからiOS6 iPhone Simulatorで動かすとこんな感じになります。

サンプルコード

#import “ViewController.h”

#import <QuartzCore/QuartzCore.h>

@interface ViewController () <UIAlertViewDelegate>

@property (strong, nonatomic) UIScrollView *world;

@property (strong, nonatomic) UIView *score;

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    [self createWorld];

    [self hideCars];

    [self createScore];

}

– (void)reloadUI

{

    [self.world removeFromSuperview];

    [self createWorld];

    [self hideCars];

    [self createScore];

}

– (void)createWorld

{

    self.world = [[UIScrollView alloc] initWithFrame:self.view.bounds];

    self.world.contentSize = CGSizeMake(2000, 2000);

    self.world.backgroundColor = [UIColor greenColor];

    [self.view addSubview:self.world];

}

– (void)hideCars

{

    UIImage *car = [UIImage imageNamed:@”car”];

    for (int i=0; i<5; i++) {

        int x =arc4random() % 1800 + 100;

        int y =arc4random() % 1800 + 100;

        UIImageView *iv = [[UIImageView alloc] initWithImage:car];

        [self.world addSubview:iv];

        iv.center = CGPointMake(x, y);

        

        iv.userInteractionEnabled = YES;

        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];

        [iv addGestureRecognizer:tap];

    }

}

– (void)createScore

{

    self.score = [[UIView alloc] initWithFrame:CGRectMake(240, 20, 320, 80)];

    self.score.backgroundColor = [UIColor orangeColor];

    self.score.layer.cornerRadius = 40;

    self.score.layer.borderWidth = 4;

    self.score.layer.borderColor = [UIColor whiteColor].CGColor;

    

    [self.view addSubview:self.score];

}

– (void)tap:(UITapGestureRecognizer*)gr

{

    int count = self.score.subviews.count;

    float x = 60 * count + 50;

    

    [self.score addSubview:gr.view];

    gr.view.center = [self.world convertPoint:gr.view.center toView:self.score];

    

    [UIView animateWithDuration:0.6 animations:^{

        gr.view.transform = CGAffineTransformMakeScale(0.3, 0.3);

        gr.view.center = CGPointMake(x, self.score.center.y20);

        self.score.center = CGPointMake(self.score.center.x40, self.score.center.y);

        

        if (count == 4) {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Clear” message:@”” delegate:self cancelButtonTitle:@”OK” otherButtonTitles:nil];

            [alert show];

        }

    }];

}

– (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

    [self reloadUI];

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end