シャッフルボタンを押してみよう。
当たり棒を見つけられるかな?
という感じの子供向けiPhoneゲームのサンプルコードを書いてみた
ポイント
棒のシャッフルは、
入れ替える棒の組み合わせを20回分配列に保持しておいて、
それを、UIViewのanimateWithDurationのcompletionブロックから
再帰呼び出しをすることで、くるくる入れ替えています。
環境
このiPhoneアプリサンプルは、
XcodeのiOS6 iPhone Simulatorで動かしています
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController () {
NSMutableArray *sticks;
int index[40];
}
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self createSticks];
[self createBox];
}
– (void)createSticks
{
int winning = arc4random() % 5;
sticks = [[NSMutableArray alloc] init];
for (int i=0; i<5; i++) {
float x = i * 50 + 50;
float y = 180;
UIView *matchstick = [[UIView alloc] initWithFrame:CGRectMake(x, y, 20, 100)];
matchstick.backgroundColor = [UIColor clearColor];
[self.view addSubview:matchstick];
UIView *bar = [[UIView alloc] initWithFrame:CGRectMake(5, 0, 10, 90)];
bar.backgroundColor = [UIColor brownColor];
[matchstick addSubview:bar];
if (winning == i) {
UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 80, 20, 20)];
head.layer.cornerRadius = 10.0;
head.backgroundColor = [UIColor redColor];
[matchstick addSubview:head];
}
[sticks addObject:matchstick];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pickup:)];
[matchstick addGestureRecognizer:tap];
}
}
– (void)createBox
{
UILabel *box = [[UILabel alloc] initWithFrame:CGRectMake(30, 300, 260, 50)];
box.backgroundColor = [UIColor blackColor];
box.text = @”shuffle”;
box.textColor = [UIColor whiteColor];
box.font = [UIFont boldSystemFontOfSize:40];
box.textAlignment = 1;
[self.view addSubview:box];
box.userInteractionEnabled = YES;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shuffle)];
[box addGestureRecognizer:tap];
}
– (void)shuffle
{
[UIView animateWithDuration:0.4 animations:^{
for (UIView *v in sticks) {
v.transform = CGAffineTransformMakeTranslation(0, 70);
}
}];
for (int i = 0; i<20; i++) {
int a = arc4random() % 5;
int b = arc4random() % 4;
if (b >= a) {
b += 1;
}
index[2*i] = a;
index[2*i +1] = b;
}
[self change:20];
}
– (void)change:(int)number
{
if (number < 0) {
return;
}
UIView *stickA = [sticks objectAtIndex:index[2 * number]];
UIView *stickB = [sticks objectAtIndex:index[2 * number + 1]];
float duration = (arc4random() % 4 + 1) * 0.1;
[UIView animateWithDuration:duration animations:^{
CGPoint nextA = stickB.center;
CGPoint nextB = stickA.center;
stickA.center = nextA;
stickB.center = nextB;
} completion:^(BOOL finished) {
[self change:number – 1];
}];
}
– (void)pickup:(UITapGestureRecognizer*)gr
{
[UIView animateWithDuration:1.0 animations:^{
gr.view.transform = CGAffineTransformIdentity;
}];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end