Commit 736cda54 authored by O'Reilly Media, Inc's avatar O'Reilly Media, Inc
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading
+19 −0
Changes for Day1-NuclearFallout-Finished/Classes/GameAppDelegate.h: 19 added lines, 0 removed lines.
Original line number Diff line number Diff line
//
//  GameAppDelegate.h
//
//  Created by Todd Moore - http://toddmoore.com/
//

#import <UIKit/UIKit.h>

@class RootViewController;

@interface GameAppDelegate : NSObject <UIApplicationDelegate> 
{
	UIWindow			*window;
	RootViewController	*viewController;
}

@property (nonatomic, retain) UIWindow *window;

@end
+157 −0
Changes for Day1-NuclearFallout-Finished/Classes/GameAppDelegate.m: 157 added lines, 0 removed lines.
Original line number Diff line number Diff line
//
//  GameAppDelegate.m
//
//  Created by Todd Moore - http://toddmoore.com/
//

#import "cocos2d.h"

#import "GameAppDelegate.h"
#import "GameConfig.h"
#import "GameScene.h"
#import "RootViewController.h"

@implementation GameAppDelegate

@synthesize window;

- (void) removeStartupFlicker
{
	//
	// THIS CODE REMOVES THE STARTUP FLICKER
	//
	// Uncomment the following code if you Application only supports landscape mode
	//
#if GAME_AUTOROTATION == kGameAutorotationUIViewController

//	CC_ENABLE_DEFAULT_GL_STATES();
//	CCDirector *director = [CCDirector sharedDirector];
//	CGSize size = [director winSize];
//	CCSprite *sprite = [CCSprite spriteWithFile:@"Default.png"];
//	sprite.position = ccp(size.width/2, size.height/2);
//	sprite.rotation = -90;
//	[sprite visit];
//	[[director openGLView] swapBuffers];
//	CC_ENABLE_DEFAULT_GL_STATES();
	
#endif // GAME_AUTOROTATION == kGameAutorotationUIViewController	
}
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
	// Init the window
	window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
	
	// Try to use CADisplayLink director
	// if it fails (SDK < 3.1) use the default director
	if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
		[CCDirector setDirectorType:kCCDirectorTypeDefault];
	
	
	CCDirector *director = [CCDirector sharedDirector];
	
	// Init the View Controller
	viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
	viewController.wantsFullScreenLayout = YES;
	
	//
	// Create the EAGLView manually
	//  1. Create a RGB565 format. Alternative: RGBA8
	//	2. depth format of 0 bit. Use 16 or 24 bit for 3d effects, like CCPageTurnTransition
	//
	//
	EAGLView *glView = [EAGLView viewWithFrame:[window bounds]
								   pixelFormat:kEAGLColorFormatRGB565	// kEAGLColorFormatRGBA8
								   depthFormat:0						// GL_DEPTH_COMPONENT16_OES
						];
	
	// attach the openglView to the director
	[director setOpenGLView:glView];
	
//	// Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
//	if( ! [director enableRetinaDisplay:YES] )
//		CCLOG(@"Retina Display Not supported");
	
	//
	// VERY IMPORTANT:
	// If the rotation is going to be controlled by a UIViewController
	// then the device orientation should be "Portrait".
	//
	// IMPORTANT:
	// By default, this template only supports Landscape orientations.
	// Edit the RootViewController.m file to edit the supported orientations.
	//
#if GAME_AUTOROTATION == kGameAutorotationUIViewController
	[director setDeviceOrientation:kCCDeviceOrientationPortrait];
#else
	[director setDeviceOrientation:kCCDeviceOrientationLandscapeLeft];
#endif
	
	[director setAnimationInterval:1.0/60];
	[director setDisplayFPS:YES];
	
	
	// make the OpenGLView a child of the view controller
	[viewController setView:glView];
	
	// make the View Controller a child of the main window
	[window addSubview: viewController.view];
	
	[window makeKeyAndVisible];
	
	// Default texture format for PNG/BMP/TIFF/JPEG/GIF images
	// It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
	// You can change anytime.
	[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];

	
	// Removes the startup flicker
	[self removeStartupFlicker];
	
	// Run the intro Scene
	[[CCDirector sharedDirector] runWithScene: [GameScene scene]];		
}


- (void)applicationWillResignActive:(UIApplication *)application {
	[[CCDirector sharedDirector] pause];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
	[[CCDirector sharedDirector] resume];
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
	[[CCDirector sharedDirector] purgeCachedData];
}

-(void) applicationDidEnterBackground:(UIApplication*)application {
	[[CCDirector sharedDirector] stopAnimation];
}

-(void) applicationWillEnterForeground:(UIApplication*)application {
	[[CCDirector sharedDirector] startAnimation];
}

- (void)applicationWillTerminate:(UIApplication *)application {
	CCDirector *director = [CCDirector sharedDirector];
	
	[[director openGLView] removeFromSuperview];
	
	[viewController release];
	
	[window release];
	
	[director end];	
}

- (void)applicationSignificantTimeChange:(UIApplication *)application {
	[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
}

- (void)dealloc {
	[[CCDirector sharedDirector] release];
	[window release];
	[super dealloc];
}

@end
+26 −0
Changes for Day1-NuclearFallout-Finished/Classes/GameConfig.h: 26 added lines, 0 removed lines.
Original line number Diff line number Diff line
//
//  GameConfig.h
//
//  Created by Todd Moore - http://toddmoore.com/
//

#ifndef __GAME_CONFIG_H
#define __GAME_CONFIG_H

//
// Supported Autorotations:
//		None,
//		UIViewController,
//		CCDirector
//
#define kGameAutorotationNone 0
#define kGameAutorotationCCDirector 1
#define kGameAutorotationUIViewController 2

//
// Define here the type of autorotation that you want for your game
//
#define GAME_AUTOROTATION kGameAutorotationUIViewController


#endif // __GAME_CONFIG_H
 No newline at end of file
+43 −0
Changes for Day1-NuclearFallout-Finished/Classes/GameScene.h: 43 added lines, 0 removed lines.
Original line number Diff line number Diff line
//
//  GameScene.h
//
//  Created by Todd Moore - http://toddmoore.com/
//


// When you import this file, you import all the cocos2d classes
#import "cocos2d.h"

// HelloWorld Layer
@interface GameScene : CCLayer
{
    CCSprite *background;
    CCSprite *tank;
    float move;
    
    // is game playing?
    bool playing;
    
	// nuclear fallout objects
    NSMutableArray *active; // active falling objects
    NSMutableArray *inactive; // objects that should be removed
    
	// round information
    float roundTimer;      // total time in round
    float falloutTimer;    // total time to fallout
    float falloutInterval; // total time to next fallout
    
    // tap to play label
    CCLabelTTF *startLabel;

    // scoring
    float score;
    CCLabelAtlas *scoreLabel;
    
    bool touching;
}

// returns a Scene that contains the Game Scene as the only child
+(id) scene;

@end
+313 −0
Changes for Day1-NuclearFallout-Finished/Classes/GameScene.m: 313 added lines, 0 removed lines.
Original line number Diff line number Diff line
//
//  GameScene.m
//
//  Created by Todd Moore - http://toddmoore.com/
//

// Import the interfaces
#import "GameScene.h"
#import "SimpleAudioEngine.h"

// HelloWorld implementation
@implementation GameScene

+(id) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	GameScene *layer = [GameScene node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if( (self=[super init] )) 
	{
        // enable touch
        self.isTouchEnabled = YES;
        
		// ask director the the window size
		CGSize size = [[CCDirector sharedDirector] winSize];
        
        // create our background
        background = [CCSprite spriteWithFile:@"background.png"];
        background.position = ccp(size.width/2, size.height/2);
        [self addChild: background];
        
        // create our tank
        tank = [CCSprite spriteWithFile:@"tank.png"];
        tank.position = ccp(size.width/2, 5 + tank.contentSize.height/2);
        [self addChild: tank];
        
        // initially hide our tank
		tank.visible = NO;
        
        // create an array of objects
		active = [[NSMutableArray alloc] init];
		inactive = [[NSMutableArray alloc] init];
		
		// create and initialize a Label
		startLabel = [CCLabelTTF labelWithString:@"Tap to Play" fontName:@"STHeitiJ-Light" fontSize:56];
		// position the label on the center of the screen
		startLabel.position = ccp( size.width /2 , size.height/2 );
		// add the label as a child to this Layer
		[self addChild: startLabel];
        
        // scoring
        scoreLabel = [CCLabelAtlas labelWithString:@"0" charMapFile:@"led.png" itemWidth:15 itemHeight:32 startCharMap:'0'];
        scoreLabel.position = ccp(480 - 16 - scoreLabel.contentSize.width, 320 - 32);
        [self addChild: scoreLabel];
        
        // snow effect
        CCParticleSystem *snow = [CCParticleSystemPoint particleWithFile: @"snow.plist"];
        [self addChild: snow];
        
        // preload sounds
		[[SimpleAudioEngine sharedEngine] preloadEffect: @"splash.wav"];
		[[SimpleAudioEngine sharedEngine] preloadEffect: @"explosion.wav"];
        
        // play repeating tank sound as background music but set volume to 0
        [[SimpleAudioEngine sharedEngine] setBackgroundMusicVolume:0];
        [[SimpleAudioEngine sharedEngine] playBackgroundMusic: @"tank.wav"];

        // startup our accelerometer
        [[UIAccelerometer sharedAccelerometer] setDelegate:self];
        [[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 30)];
        
        // schedule our update loop
        [self schedule:@selector(update:)];
	}
	return self;
}

- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{   
    if (touching) return;
    
    // we are landscape mode so the y axis is really our x axis
    move = acceleration.y * 2.0;
    
    // if x is negative we are reversed landscape mode so flip y
    if (acceleration.x < 0) move = -move;
    
    // limit movement to range of -1 to 1
    if (move < -1) move = -1;
    if (move > 1) move = 1;
    
    // filter small values to reduce tank jitter
    if (move > -0.1 && move < 0.1) move = 0;
}


- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{   
    touching = true;
    
    // check for game start
    if (playing == NO)
    {
        // wait until all objects are crashed
        if (active.count == 0)
        {
            // reset all vars
            falloutInterval = 0.5;
            startLabel.visible = NO;
            tank.visible = YES;
            roundTimer = 0;
            playing = YES;
            score = 0;
            
            // start tank sound at lowest volume
            [[SimpleAudioEngine sharedEngine] setBackgroundMusicVolume:0.1];
        }
        return;
    }
    
    // not using multitouch so we can just grab any object
    UITouch *touch = [touches anyObject];
    
    // get location of touch
    CGPoint location = [touch locationInView:[touch view]];
    
    if (location.x < 64) move = -1;
    else if (location.x > 480-64) move = 1;
    else move = 0;
}
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{	
    move = 0;
    touching = false;

}
- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    move = 0;
    touching = false;

}

- (void) createExplosion: (NSString*) name inRect: (CGRect) rect
{
	CCParticleSystem *explosion = [CCParticleSystemPoint particleWithFile: name];
	explosion.position = ccp(rect.origin.x+rect.size.width/2,rect.origin.y+rect.size.height/2);
	explosion.autoRemoveOnFinish = YES;
    [self addChild: explosion];
}


- (void) update: (ccTime) dt 
{
    // add to our round and fallout timers
    roundTimer += dt;
    falloutTimer += dt;
    
    // playing logic (tank still alive)
    if (playing)
    {
        // update score
        score += dt;
        [scoreLabel setString: [NSString stringWithFormat: @"%u", (unsigned int) (score * 1000)]];
        scoreLabel.position = ccp(480 - 16 - scoreLabel.contentSize.width, 320 - 32);
        
        // new round every 4 seconds
        if (roundTimer > 4)
        {
            // next round
            roundTimer = 0;
            falloutInterval -= 0.1;
            if (falloutInterval < 0.1) falloutInterval = 0.1;
        }
        
        // check for next fallout
        if (falloutTimer > falloutInterval)
        {
            // create new fallout
            falloutTimer = 0;
            CCSprite *fallout = [CCSprite spriteWithFile:@"fallout.png"];
            fallout.position = ccp(arc4random() % 480, 320 + fallout.contentSize.height/2);
            [self addChild: fallout];
            [active addObject: fallout];
        }
    }
    
    // create the tank rectangle
    CGRect rectTank = CGRectMake(tank.position.x - tank.contentSize.width / 2.0, 
                                 tank.position.y - tank.contentSize.height / 2.0, 
                                 tank.contentSize.width, 
                                 tank.contentSize.height);

    
    // go through fallout and move them down the screen
    for (CCSprite *fallout in active)
    {
        fallout.position = ccp(fallout.position.x, fallout.position.y - dt * 320.0);
        fallout.rotation += 360.0 * dt;
        if (fallout.position.y < 20)
        {
            // add to inactive list
            [inactive addObject: fallout];
            
        }
        
        if (playing)
        {                   
            // create the fallout rectangle
            CGRect rectFallout = CGRectMake(fallout.position.x - 8, 
                                            fallout.position.y - 8, 
                                            16, 
                                            16);
            
            if (CGRectIntersectsRect(rectTank, rectFallout))
            {
                // kill the tank
                tank.visible = NO;
                playing = NO;
                startLabel.visible = YES;
                
                [self createExplosion: @"tank.plist" inRect: rectTank];
                
                // play tank explosion sound
                [[SimpleAudioEngine sharedEngine] playEffect:@"explosion.wav"];
                
                // start tank sound at lowest volume
                [[SimpleAudioEngine sharedEngine] setBackgroundMusicVolume:0];
            }
        }
    }
    
    // go through inactive and remove and explode
    for (CCSprite *fallout in inactive)
    {
        // create a fallout explosion
        CGRect rectFallout = CGRectMake(fallout.position.x - fallout.contentSize.width/2, 
                                        fallout.position.y - fallout.contentSize.height/2, 
                                        fallout.contentSize.width/2, 
                                        fallout.contentSize.height/2);
        [self createExplosion: @"fallout.plist" inRect: rectFallout ];
        
        // play splash sound
		[[SimpleAudioEngine sharedEngine] playEffect:@"splash.wav"];
        
        // remove from active list and our scene
        [active removeObject: fallout];
        [self removeChild:fallout cleanup:YES];
    }
    
    // clear out inactive queue
    [inactive removeAllObjects];
    
    // if not playing we get out of loop here
    if (playing == false) return;
 
    // move tank based on controls
    float x = tank.position.x;
    
    // move tank so it takes 1 second to get across entire screen
    x += move * dt * 480.0;
    
    // keep tank on the screen
    if (x < 80) x = 80;
    if (x > 400) x = 400;
    
    // update position of tank sprite
    tank.position = ccp(x,tank.position.y);
    
    // set tank sound to be louder when moving
    float volume = 0.1 + fabs(move);
    if (volume > 1) volume = 1;
    [[SimpleAudioEngine sharedEngine] setBackgroundMusicVolume:volume];
}


// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
    // turn off accelerometer
    [[UIAccelerometer sharedAccelerometer] setDelegate: nil];
    
    // unschedule this update loop
    [self unschedule: @selector(update:)];
    [active release];
    [inactive release];
    
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)
	
	// don't forget to call "super dealloc"
	[super dealloc];
}
@end
Loading