CS 491 Lecture 3 – iPopper cont’d
Agenda
- groups
- modeling the bubbles
- redrawing
- handling touches
- multitouch
- audio
- NSMutableArray
- properties
Code
PopperView.m
//
// PopperView.m
// iPopper
//
// Created by Christopher R. Johnson on 9/5/13.
// Copyright (c) 2013 UWEC. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
#import "PopperView.h"
@interface PopperView () {
UIImage *images[2];
BOOL *isPopped;
}
@property int nrows;
@property int ncols;
@property NSMutableArray *players;
@end
@implementation PopperView
@synthesize nrows = _nrows;
@synthesize ncols = _ncols;
@synthesize players = _players;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// do initialization of instance variables
[self setBackgroundColor:[UIColor redColor]];
images[0] = [UIImage imageNamed:@"unpopped"];
images[1] = [UIImage imageNamed:@"popped"];
self.nrows = ceil(self.bounds.size.height / images[0].size.height);
self.ncols = ceil(self.bounds.size.width / images[0].size.width);
isPopped = (BOOL *) malloc(self.nrows * self.ncols * sizeof(BOOL));
for (int r = 0; r < self.nrows; ++r) {
for (int c = 0; c < self.ncols; ++c) {
isPopped[c + r * self.ncols] = NO;
}
}
self.players = [[NSMutableArray alloc] init];
self.multipleTouchEnabled = YES;
}
return self;
}
- (void)drawRect:(CGRect)dirtyRect {
CGContextRef canvas = UIGraphicsGetCurrentContext();
for (int r = 0; r < self.nrows; ++r) {
for (int c = 0; c < self.ncols; ++c) {
CGRect drawIntoRect = CGRectMake(c * images[0].size.width, r * images[0].size.height, images[0].size.width, images[0].size.height);
int i = isPopped[c + r * self.ncols] ? 1 : 0;
CGContextDrawImage(canvas, drawIntoRect, [images[i] CGImage]);
}
}
}
- (void)popAtPoint:(CGPoint)point {
int r = point.y / images[0].size.height;
int c = point.x / images[0].size.width;
if (!isPopped[c + r * self.ncols]) {
isPopped[c + r * self.ncols] = YES;
[self setNeedsDisplay];
int i = arc4random_uniform(3) + 1;
NSString *clipName = [NSString stringWithFormat:@"pop%d", i];
NSString *path = [[NSBundle mainBundle] pathForResource:clipName ofType:@"mp3"];
NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[audioPlayer play];
[self.players addObject:audioPlayer];
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
[self popAtPoint:[touch locationInView:self]];
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
[self popAtPoint:[touch locationInView:self]];
}
}
@end
Haiku
I live by % 2
“Automate this braindead stuff.”
“No magic. Control!”
“Automate this braindead stuff.”
“No magic. Control!”