Hour of Code

How many lines of code can you program in hour?

A new campaign in the US that is spreading around internet is called “Hour of Code”, with a great video ad with celebrities and folks of all ages learning to code, and Obama giving a little encouragement.

I checked out HourofCode.org to see what it was all about.  While a big chunk of the campaign is to get schools to teach programming, the thing I was interested in was the learning section.  I decided to do one:  program a game that could be used on iOS, through Make Games With Us.

The program is written in Objective-C, which I have never done before.  So, some things I learned (or think I learned!) about programming a game for iOS / using Objective C:

  • something.h means a class. To import it, include #import something.h.  Not sure what the significance of the # is.  You can import pre-existing classes.
  • Syntax:  Objective C uses {  } to open and close things, and ; at the end of lines.  [ ] seem to be important (even used when they are not an argument for something, just around the whole line).  Seems to have to do with making something execute.
  • To structure a program so it can rub:

@implementation NameOfClassBeingUsedAsScene (I believe)

-(id) init
{
if ((self = [super init])) // this is code to check things have been initialized properly, always            include it in your init method
{

// program code goes here

} // end of the if(self=[super init]

// don’t put any extra code after the if – not sure if this is just for the program-a-game exercise, or if this is all the time.  If all the time, effectively means the program is one big if.

return self;

} // end of the program, the -(id) init.  after returns Self.

// can insert new methods below (i.e. outside) the program, but before the implementation ends.

@end // finishes the implementation

 

  • You can import classes before the -(id) init.  You can also create class level variables before the -(id) init.
  • Objective C distinguishes between primitives and objects.  You must(?) declare what a variable is:  a primitive or an object.  Primitives include int, float, bool, etc…)
  • To declare a primitive:

type NAME (e.g. int Counter).

  • To declare a new object of a class X, must use a *

class * NameOfNewObject;

Can also have it be:

class * NameOfNewObject= [[class alloc] init]

Not sure if the alloc is standard across all classes.  As far as I can figure, this it the command that declares a new object of a class using whatever procedure that class uses to create a new object of that class (e.g. could randomize characteristics).  It appears that it is not necessary to use a method to create an object.  Edit:  Yes, before you use the object, you need to initialize it.  It appears that for the game program, Alloc is what does the initializing.  However, not clear if that is standard.

  • Objective C borrows terms from the movies:  a screen is called a scene, and the Director is a tool that can be used to do certain things.
  • You can use the term “self” to refer to the current scene (possibly?)
  • To add an object to the current scene: [self addChild:NameOfObject]
  • “++” increases a variable by 1
  • From the MakeAGameWithUs tutorial:

Basic Syntax

Objective-C syntax for declaring and calling methods is what makes it look the most different from languages like C++ and Java. The good news is that once you learn how it’s done the Objective-C way it will become clear that these languages follow the same basic principles.

To call a method: [ObjectName methodName]; For example:[hero shoot]; To call a method and pass a parameter:[ObjectName methodName: parameter]; For example:[self addChild: hero];

A base control later is CCLayer.

Method Syntax

Method Syntax

To declare a method in Objective-C, follow the following format:

-(type I return) nameOfMethod: 
(type of first parameter) firstParameter 
continuationOfMethodName:
(type of second parameter) secondParameter

For example, to declare a method that does not return anything and does not accept any parameters:

-(void) doSomething
{
     NSLog(@"Hello World!");
}

Or, to declare a method that returns an int and accepts a string:

-(int) doSomethingWithAString: (NSString*) myString
{
    //returns the length of the string times ten
    return [myString length] * 10; 
}

Or, to declare a method that returns an array and accepts multiple strings:

-(NSArray *) addThisStringToAnArray: (NSString*) firstString 
             andThisString: (NSString*) secondString 
             andAlsoThisString: (NSString*) thirdString
{
    return [NSArray arrayWithObjects: firstString, 
                                     secondString, 
                                     thirdString, nil]; 
}
  • For your game to be dynamic and interactive, it needs to update frequently. Programs do this using a concept called frames, during every frame the entire screen is redrawn, and frames happen 60 times each second!
  • To switch to a different screen (ie. scene), use “replaceScene”), which is called from the CCDirector.

[[CCDirector sharedDirector] replaceScene:  [[NewScene] alloc] init]]

Those are my class notes 🙂  The final code for the project is below.  38 lines of code done, a little over an hour (incl writing this post).

—–

#import “GameplayLayer.h”
#import “Ship.h”
#import “MainCharacter.h”
#import “GameOverLayer.h”

int screenHeight;
int screenWidth;
MainCharacter * hero;

@implementation GameplayLayer

// the code inside the brackets after “-(id) init” is the code that runs once when you run your program. It is the very first thing to run.
-(id) init
{
if ((self = [super init])) // this is code to check things have been initialized properly, always include it in your init method
{

screenHeight = [[CCDirector sharedDirector] screenSize].height;
screenWidth = [[CCDirector sharedDirector] screenSize].width;

//initialize a ship
Ship * ship1 = [[Ship alloc] init];

//add the ship to the scene
[self addChild: ship1];

//increment the game’s number of enemies counter. I assume this is already declared in Gameplaylayer
numEnemies++;

// place the ship
ship1.position = ccp(screenWidth/2, screenHeight/2);

Ship * ship2 = [[Ship alloc] init];
[self addChild: ship2];
numEnemies++;
ship2.position = ccp(screenWidth/3, screenHeight/3);

Ship * ship3 = [[Ship alloc] init];
[self addChild: ship3];
numEnemies++;
ship3.position = ccp(screenWidth/4, screenHeight/4);

Ship * ship4 = [[Ship alloc] init];
[self addChild: ship4];
numEnemies++;
ship4.position = ccp(screenWidth/5, screenHeight/5);

Ship * ship5 = [[Ship alloc] init];
[self addChild: ship5];
numEnemies++;
ship5.position = ccp(screenWidth/6, screenHeight/6);

hero = [[MainCharacter alloc] init];
[self addChild: hero];
hero.position = ccp(screenWidth/2, screenHeight/10);

[self scheduleUpdate];
}
// don’t put any more code here
return self;
}

// put new methods here

-(void) update: (ccTime) dt
{
//this will get called every frame
//but only if the line [self scheduleUpdate] is in the init method

//gets the input object that stores all
//touches that happened this frame
KKInput * input = [KKInput sharedInput];
//get the position of the touch that began this frame
CGPoint touchPosition = [input locationOfAnyTouchInPhase:KKTouchPhaseBegan]; //returns (0.0,0.0) if no touch Position
if(touchPosition.x != 0.0 || touchPosition.y != 0.0)
{
[hero shootAt: ccp(screenWidth/2, screenHeight)];
}

//check victory condition
if(numEnemies == 0)
{
[[CCDirector sharedDirector] replaceScene:
[[GameOverLayer alloc] initWithPlayerName: playerName]];
//we’ve set the variable playerName to be your name 🙂
}

}

@end

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s