My second iphone game

CatchThemAllV0.1.0

Just finished my second iphone game. While I have not tested it on device yet!!

My first iphone game was taking the accelerometer into game play and this game is all about multi-touch. While it is quite straight forward to play, but it holds the ability of being engaging and addictive.

The game play is to choose the color which is displayed maximum times on screen. There are only 5 colours, but then one has to count the number of times. There is a simple counter runs to show how much time one is spending in a particular question. If the counter reaches 1000, the question changes to the next question and the player looses one point. The interesting part of the same is, each of the colours is assigned a different touch input. That means, if the player has to choose a particular colour, he/she may have to touch with 3 fingers, similarly there are 2 finger touch, 4 finger touch etc are available.
The game play is going to be interesting if you are trying out in device, on the simulator, its a waste and boring thing.
Hope, I will test it soon with a real device and come up with my first experience with it.

Code is hosted at Github and the direct location is here.

Happy Gaming :)

Making random numbers in ObjectiveC, the quick and dirty way.

This is another part of my iphone development experience, where I really feel the pain over and again. So putting up my quick way to do get a random number. There are a lot of methods regarding the random number generation in objectiveC and there are even third party attempts to get the best random number possible.
The three most obvious functions are rand(),random() and arc4random(). While a lot can be heard around of not getting a random number by the first two functions, the last options is better. At least I get decent random numbers with it.
Now to get a random number between 2 points, the code would be

//random number between 0 and 5 not 5, till 4
int i=arc4random()%5;
//random number between 10 and 15 not 15, till 14
int j=10 + arc4random()%5;

Hope that makes my next random number creation search leads me to look at this post.
Happy coding :)

Dealing with Touch Events, the Sparrow way.

This is specifically caught me, when I am coming from other object oriented technology. May be because of those environments are all single touch based. And I never have worked in multi-touch based application.
While working in Sparrow-framework, there is a nice event called “SP_EVENT_TYPE_TOUCH” . This is basically used if we want to use the touch based interaction in our game. Once we add an handler to it, the general expectation is it will just fire up once per touch/tap. But actually it will fire up 2 times as we have 2 different events, “touchesBegan” and “touchesEnded” for each touch interaction in the main cocoa/objectiveC framework. And the good news is Sparrow-framework does a nice job of encapsulating the internals of all those two events and gives us one event to deal with, that is “SP_EVENT_TYPE_TOUCH”.
Well, but the catch is getting confused with the event handler code. Lets dive in here.

[self addEventListener:@selector(onUserTouch:) 
	atObject:self forType:SP_EVENT_TYPE_TOUCH];

Now the handler code will look as below

- (void)onUserTouch:(SPTouchEvent*)event
{
        NSLog(@"onUserTouch");
}

When run, this code will generate log messages two times for a single touch! Thats for the reason we discussed earlier. Well, the fix is on the handler. We have to deal the events inside if-else where we will check, whether its single or multi touch as below.

- (void)onUserTouch:(SPTouchEvent*)event
{
        NSLog(@"onUserTouch");
        NSArray *touches = [[event touchesWithTarget:self 
                       andPhase:SPTouchPhaseBegan] allObjects];
	if (touches.count==1) {
		NSLog(@"1 fingure touch ");
               //Do the custom code here for single touch events
	}else if (touches.count==2) {
		NSLog(@"2 fingure touch ");
	}
}

For only single touch the syntax is even smaller

- (void)onUserTouch:(SPTouchEvent*)event
 {
     SPTouch *touch = [[event touchesWithTarget:self 
                 andPhase:SPTouchPhaseBegan] anyObject];
     if (touch)
     {
         SPPoint *touchPosition = [touch locationInSpace:self];
         NSLog(@"Touched position (%f, %f)", 
              touchPosition.x, touchPosition.y);
     }
 }

The only difference being, while handling single touches we can directly use “anyObject” as the last parameter and that will give us a single event and for multi-touch environments we have to use “allObjects” as the last parameter. But all this will happen inside the event handler, which will by default fire up twice.
One has to get the “touch” or “touches” inside the event handler and then process the code according to it. Directly the handler will fire up twice and that must not confuse as to, whats happening around!

Happy coding :)

Category Example by code reference

Well moving ahead with Category and trying my hands on them, I found its better to have some code reference here to serve myself in the need.
I was working with Sparrow framework for my opensource iphone game MathIsFun2. And suddenly I needed to add some functionality to the Sprite class that Sparrow has. This made a situation to have a Category.
The example code here, is not exactly the same as in the game, I changed the Category and code here, so as to best fit for general purpose.
The code and example here is just to make the understanding of Category and not to show how we are going to do a certain task in it (as we are drawing a circle here). There may be better way to do, what we are going to do here (creating a circle), but lets concentrate and see how Categories work.
The point here is, I needed a “draw circle” method in Sparrow’s SPSprite. I went ahead and made a category named “SPSprite+Circle” and the two files are “SPSprite+Circle.h”,”SPSprite+Circle.m”. Lets see how these files look from inside.

The interface file “SPSprite+Circle.h”

#import 
#import "Sparrow.h"

@interface SPSprite(Circle)
-(void)makeCircle:(int)radius 
     WithThickness:(int)thickness 
             AndColor:(uint)color;
@end

The implementation file “SPSprite+Circle.m”

#import "SPSprite+Circle.h"

@implementation SPSprite(Circle)
-(void)makeCircle:(int)radius 
      WithThickness:(int)thickness 
              AndColor:(uint)color
{
	for (int i=0; i<=360; i++) {
		SPQuad *q=[SPQuad quadWithWidth:thickness height:3];
		q.color = color;
		q.x=radius*cos(i);
		q.y=radius*sin(i);
		q.rotation=i;
		[self addChild:q];
	}
}
@end

Thats all, I needed a method to draw a circle in my sprite, and made a Category, which handles that. Now where ever I have imported SPSprite, I have to replace that with "SPSprite+Circle". Rest of the implementations remain the same.
Lets see, the usage code

//first import in the interface .h file
#import "SPSprite+Circle.h"

//on the implementation .m file write down the below code
//where you think you want a circle
SPSprite *s=[[SPSprite alloc] init];
		[s makeCircle:50 WithThickness:30 AndColor:0xffffff];
		[self addChild:s];
		
		s.x=80;
		s.y=80;

You can see the clear advantage. We are making an SPSprite and calling the method on it. The same method "makeCircle: WithThickness: AndColor:", which we have declared in our Category now directly available to the SPSprite Object.

Now lets try the more confusing one. I have another class named “SsaumyaSprite”, which is a child class of “SPSprite”.

#import 
#import "Sparrow.h"
@interface SsaumyaSprite : SPSprite 
{
}
- (id)initWithSqare;
-(id)initWithCircle:(int)radius AndThickness:(int)thick;
-(void)makeCircle:(int)radius withThickness:(int)thickness;
@end

So it has all these method implementations in its implementation file as well. Now lets try and call our new method which was added as a Category. The same implementation file will look as below

//first import in the interface .h file
#import "SsaumyaSprite.h"
#import "SPSprite+Circle.h"

//on the implementation .m file write down the below code
//SPSprite *s=[[SPSprite alloc] init];
SsaumyaSprite *s=[[SsaumyaSprite alloc] initWithCircle:100 AndThickness:1];
		[s makeCircle:50 WithThickness:30 AndColor:0xffffff];
		[self addChild:s];
		s.x=80;
		s.y=80;

Looking carefully into the code will show you that now we are not making “SPSprite” object but “SsaumyaSprite” object. Again, after that all the code are the same. The child class also gets the added method to the base class ( by Category ).

I hope that clears out a lot of confusion and shows the potential of Category in objectiveC.
The source code for this example Category are available at Github.
My opensource gameMathIsFun2 is available at Github too.
Hope to see some gaming around it :)

Category and Inheritance on ObjectiveC

While Category is a nice way to add functionality to the base class, people like me who come from other object oriented technology such as Flash, will find a little difficult to understand as to how this thing relates to the inheritance chain. The same question came up to my mind and I did a quick research on the topic.

The final thing is Category does the same thing as it tells about itself. It adds functionality to the base class. If you remember this, then there would be no confusion at all.

Well, for that to understand, lets take an example. Suppose there is a Class A and Class B is a subclass of Class A. In the application Class B is used in a lot of places. Now, there is a need to add some more functionality to Class A, so a new category is written as “A+newRole”. Once this category is written, the new functionality is added to the base class and in this case, Class A. That means, all those classes which are child classes of Class A such as Class B, automatically gets the functionality. Thats freaking cool. One can straight away go ahead and call the new methods added in the Category from the child classes. The only thing necessary here is to import the Category file to the appropriate place.

Getting into web design action

Once we are familiar with the key concepts of the web, browser and how it works, now its time to see how to get started with it. If you have not yet gone through them, here are the links,
1. introduction
2. getting used to the terms
I hope by now you have gone through the above links. This is not mandatory, but then going through them will bring you to the same page with me. Else it will be a little difficult for any one to understand what is being referred in the tutorial here.
Well, lets get into action. By now, you must be knowing to start with a web-page we at least need 3 files (Not mandatory but good way to segregate different functionality in different files, refer to the “getting used to the terms” reference for more on this ). So the 3 files are, one HTML file, one Javascript file and one CSS file. We will start to put the basic code for these.
The HTML file is stored with an extension of “.html”, CSS files are stored as “.css” and javascript files are stored as “.js” files. Lets write our first html file.
The very basic HTML page code will look something like

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">




	





Continue reading

Category

Coming from an object oriented programming such as actionscript or java this feature may seem a little different. At least it felt different to me. It took sometime for me to get the understanding. It was un-believable for me, at first, and all magical.
In ObjectiveC there is a feature called Category. Its another way to extend a class. If we compare with inheritance, well it can not be compared to that. As one might be knowing that, ObjectiveC itself, provides option for inheritance.
Category adds functionality to the class itself.
What?!! Yes, its that powerful. I must say it again. It adds functionality to the class itself. Its not inheritance. As with inheritance one must use the child class, to get the added functionality. But with “Category” the added functionality is available to the class itself. Wherever one might have used the class, if a new Category is added, that class just gets the functionality. Thats magic!! Yes, kind of. But then its fun and powerful, when you know the real power of it. “I can do that by adding functionality to my class file itself”, there you said it. Lets talk about situations.

Just imagine, you have a class and used it everywhere, and later you wanted to add some functionality to the class itself without ever touching the class file. The situation may arise, that one is using an external library of some kind. That library is maintained by someone else. So, you never worry about it and just use it. What if, you want to add some functionality to some class of that library. Ohh well, “I will change the class”. What if the licensing policy do not allow you to do it? Or better, lets say, if you change it and the library is updated! You have to change the updated class again! And chances are that, the functionality is now written with some other logic in the library, which makes your implementation of the class unusable. You have to re-write it in the class. And thats a lot of work, if you think the library is getting updated regularly.

Lets take a situation, where one subclasses a class and used it. Well, the same thing may happen, that the root lib is updated and used a different approach this time. All the subclass logic need to be updated!

In another scenario, one may need some more functionality to the class. Well, we subclass it again. Nice and fine as long as you have used it in some places you remember. There may be cases one need to remove the first subclass and add the subclass of the first subclass. And thats a lot of work too.

Lastly, what if one needs to add functionality to the base SDK or the parent library. Subclass it and use it, simple. But we have already seen problems with subclassing. One has already used the base class through out the project, but later on it is required to add some functionality to the class. Either some how one has to add the functionality to the base class or subclass it and use the subclass everywhere, the base class was used previously.

Ok, coming back to Category. It allows a user to add functionality to the base class itself. One need not touch the class itself. It can be done even to the original ObjectiveC classes shipped with Apple SDK. That means, if we have used a class and later decide we need to add some more functionality to it, we are safe on with Category. As soon as it is declared, the functionality is available to all the places, where the base class is used.

Lets see how we can do it, some syntaxes and naming conventions.

Defining a Category, is kind of same a defining an ObjectiveC class. One needs 2 files for it. An interface file and an implementation file. The file naming conventions are generally as “ClassName+CategoryName.h” and “ClassName+CategoryName.m”. Where “ClassName” is the name of the class one needs to extend or add functionality to and “CategoryName” is the name of the Category one is defining now.
Each Category in a project must have a different name.
Categories can not define or add instance variables to a class.
Categories can override methods of the parent class.

Lets define a category :

//file name GameAddition+ShadowText.h
#import 
@interface GameAddition (ShadowText) 
-(SPSprite *)makeText:(NSString *)text 
			withColor:(int)colorValue 
			  andSize:(int)size 
	  withShadowColor:(int)shadowColor;
@end

And the implementation file will look as

//file name GameAddition+ShadowText.m
#import "GameAddition+ShadowText.h"
@implementation GameAddition(ShadowText)
-(SPSprite *)makeText:(NSString *)text 
                    withColor:(int)colorValue 
                       andSize:(int)size 
        withShadowColor:(int)shadowColor
{
	//custom code goes here
}
@end

the difference here is both in interface and implementation file the declaration is changed to

@interface ClassName (CategoryName)

instead of just

@interface ClassName 

And same happens with implementation file too, instead of

@implementation ClassName 

the category implementation file will declare it as

@implementation ClassName (CategoryName) 

. The category name will be on parenthesis.

Now thats all to it. Wherever we would have used the class “GameAddition”, a new method is available to it. But then we need some work there too. Just to make the application know we are using the category, wherever we have imported “GameAddition.h”, we have to import “GameAddition+ShadowText.h” instead. And there we go.

Hope that helps someone out there.

References :
1. http://cocoadevcentral.com
2. http://macdevelopertips.com