標準偏差を表示するiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@import SpriteKit;
@interface ViewController () <SKSceneDelegate>
@property (nonatomic, weak) SKScene *scene;
@property (nonatomic) BOOL start;
@end
@implementation ViewController
– (void)viewDidLoad {
[super viewDidLoad];
[self setupScene];
[self createCup];
}
– (void)setupScene {
SKView *sv = [[SKView alloc] initWithFrame:self.view.bounds];
SKScene *s = [SKScene sceneWithSize:sv.frame.size];
s.backgroundColor = [self color:0];
s.delegate = self;
[sv presentScene:s];
[self.view addSubview:sv];
self.scene = s;
}
– (void)createCup {
for (int i=0; i<3; i++) {
SKSpriteNode *bar = [SKSpriteNode spriteNodeWithColor:[self color:1] size:CGSizeMake(20, 300)];
switch (i) {
case 0:
bar.position = CGPointMake(30, CGRectGetMidY(self.view.bounds));
break;
case 1:
bar.position = CGPointMake(CGRectGetMaxX(self.view.bounds) – 30, CGRectGetMidY(self.view.bounds));
break;
case 2:
bar.position = CGPointMake(CGRectGetMidX(self.view.bounds), 200);
bar.zRotation = M_PI * 0.5;
break;
default:
break;
}
bar.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:bar.size];
bar.physicsBody.dynamic = NO;
[self.scene addChild:bar];
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
self.start = YES;
}
– (void)update:(NSTimeInterval)currentTime forScene:(SKScene *)scene
{
if (self.start && self.scene.children.count < 100) {
if ((arc4random() % 30) == 0) {
[self createNumber];
[self showStandardDeviation];
}
}
}
– (void)createNumber {
SKLabelNode *l = [SKLabelNode labelNodeWithText:[NSString stringWithFormat:@”%d”, arc4random_uniform(50) + 50]];
l.name = @”number”;
l.position = CGPointMake(CGRectGetMidX(self.view.bounds) –50 + arc4random_uniform(100), 500);
l.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:20];
l.physicsBody.dynamic = YES;
[self.scene addChild:l];
}
– (void)showStandardDeviation {
NSArray *nums = [self.scene.children filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@”name == %@”, @”number”]];
NSUInteger n = nums.count;
if (n == 0) {
return;
}
int sum = 0;
for (SKLabelNode *l in nums) { sum += [l.text intValue]; }
float m = sum / n;
float sum2 = 0;
for (SKLabelNode *l in nums) { sum2 += pow([l.text intValue] – m, 2); }
float s = sqrtf(sum2 / n);
SKLabelNode *label = (SKLabelNode *)[self.scene childNodeWithName:@”label”];
if (!label) {
label = [SKLabelNode labelNodeWithText:@”0″];
label.position = CGPointMake(CGRectGetMidX(self.view.bounds), 50);
label.name = @”label”;
label.fontSize = 80;
[self.scene addChild:label];
}
label.text = [NSString stringWithFormat:@”%.2f”, s];
}
#define ColorHex(rgb) [UIColor colorWithRed:((rgb & 0xFF0000)>>16)/255.0 green:((rgb & 0xFF00)>>8)/255.0 blue:(rgb & 0xFF)/255.0 alpha:1.0]
– (UIColor *)color:(int)i {
if (i>4) return nil;
int colorCode[] = {0x04BFBF, 0xCAFCD8, 0xF7E967, 0xA9CF54, 0x588F27};
return ColorHex(colorCode[i]);
}
@end