The Big Sparrow Tutorial for Beginners

Holger Weissböck on March 30, 2012

This tutorial is for everyone who wants to create a Sparrow game. It is a comprehensive introduction for beginners and sheds a light on best practices using the example of a small game. Read this 101 and you are up and running in no time!

In this article we will find out what the Sparrow Framework is and what it can do for you. We will learn why it exists and for whom it was built. We will also have a look at it’s features and building blocks and see how they integrate into a small casual game that we are going to create in the course of this article. But before we can do all of that we need to get you up to speed with some preliminary information. There is always a catch, isn’t there? Bear with me: What is Sparrow?

The Sparrow Framework allows you to build interactive 2D games and applications for Apple’s iOS platform. It is built with ease-of-use and performance in mind. It is free, open-source and is - with regards to cleanliness and speed - written solely in the target platform’s native programming language: Objective-C. That is quite a mouthful already and it gets even better!

Who is Sparrow for?

Sparrow is for developers who want to see their 2D games on the iPhone, iPod Touch and iPad: It offers all the necessary tools to create great and successful games. We will have a look at some of these tools later. It is furthermore the number one choice for game developers who are missing a certain API on iOS devices: The Flash/ActionScript display model.

ActionScript brings a lot to the table when it comes to 2D application and games development and what it may lack in performance it compensates with a very intuitive and clean API. Imagine this clean API paired with iOS native performance and you have Sparrow. So why the heck should you start coding square-bracketed Objective-C against that API?

Ask yourself from a developer’s point of view: What is the main obstacle when switching to an unknown platform? The number one answer I get to this question is that a new platform requires us to learn a different programming language. But is learning another language really that hard? Almost all of the current ones obey the same principles and concepts. Syntax, types and namings may be different and sometimes it almost seems as if it was the utmost fun to find new labels for the same thing. Admittedly some languages offer features that others lack due to platform restrictions or design decisions. However, in the end the majority of them tend to be alike. That’s the reason why you can easily grab a language-in-a-nutshell book, page through it and start coding away.

On the other hand the part that will take up most of your time will start but now: You need to find out about the concepts and inner workings of the new platforms APIs. If you skip that exhausting part - and it is quite tempting to do so - you will end up fixing bugs that crawled into your application just because an API did not behave the way you would have expected it to. Sparrow reliefs you from this pain by offering a lightweight, gentle and for many of us already well-known API: It leans towards ActionScript wherever it is reasonable to do so. If you have been coding ActionScript already you will find yourself at home in a heartbeat.

Who uses Sparrow?

At the time of this writing we are aware of over a hundred apps on the AppStore that are based on the Sparrow Framework and these are just those from developers who took the time to publish their games in the Sparrow Wiki. The dark figure may very well be higher. Amongst those great apps are Villain’s cuteness machine Lil’Birds as well as the easy on the eye Roodie Noodies and the Slippery Pole from Complete Control. Furthermore there is the great Gravity Guitar from squarepoet and our very own comic strip generator Kabaam.

Just recently Sparrow became the basis for the no-coding game creation environment iStencyl. In addition to all of this the Sparrow community consists of many a smart developer who contributes to the project with handy extensions like ready-for-use gauges and lists or even joypads and parallax engines. But enough now with the name dropping: Let’s have a look at the nuts and bolts of the Sparrow Framework. Hell, it’s about time!

Layer Cake

iOS allows you to access the iPhone’s and iPad’s graphics chips via OpenGL as well as their audio hardware via OpenAL. While coding OpenGL for a day or two may be informative and fun it becomes cumbersome almost instantly when you start creating a game. At this point it’s much more conducive to obsess with game dynamics than schmutz like vertices, rotational axis and display loops.

Fortunately you don’t need to because Sparrow gets its hands dirty for you: The framework wraps away the bad and the ugly and hands you a clean interface into which you can plug your game or app without coding a single line of OpenGL.

However, if your game has special requirements and/or you feel the need of diving into OpenGL from time to time it’s still possible and even easy to do just that: Sparrow exposes several hooks that allow you to access the OpenGL stack directly. Kabaam for example uses the GLScissorTest to first render the UI and then cut out the comic frames to render them into JPEGs.

The Display Tree

Typically a game is in need of some form of hierarchical structure that allows to group the game’s objects together: A structure that attaches the wheels to the cars and the cars to the highway, the feathers to the birds and the birds to the tree as well as the BFG to your main character. This not only embraces object-oriented design and helps to keep your game’s code maintainable but also reliefs us from other inconvenient duties such as actively tracking all our objects’ movements, rotations and whatnot.

Within Sparrow this structure is called the “display tree”. Every display element that is visible to or interacts with the user must reside within the display tree. This means that if we want to show the image of a bird to the player we need not only load that image into memory but also attach it to the display tree, preferably at the right position.

This type of hierarchical representation of your display objects allows us to build more complex setups that combine different types of objects - e.g. a car with four wheels and a chassis - into one branch of the tree. Attaching (or pinning) the four wheels of the car as leaf nodes to its chassis for example allows us to forget about the wheels for our racing game: As soon as we move or rotate the chassis the wheels will follow as we would expect them to.

By the way, at the very root of Sparrow’s display tree resides the SPStage, which is named after the theatre equivalent - obviously. There is only one stage and all other display objects are attached to it.

Display Objects

The display tree can only consist of objects that extend the SPDisplayObject class. Sparrow already brings many different types of built-in display object types like quads, images, buttons and text fields. In addition we can create custom display objects and/or combine them together into more complex setups.

Every display object has several important properties that should be mentioned: First of all we can position display objects within their parents via x/y coordinates (in pixels) as well as apply rotations (in radians). Furthermore we can influence their extents via width/height values and set alpha values for transparency effects. There are - of course - numerous additional properties for the specific types of display objects that need not be explained right now.

The Game

Since we are finally done with the upfront info crash course it’s time to start coding our first game. The game we are going to create is about (sparrow) eggs falling out of a tree: The player has to catch those eggs with a lined basket before they crash into the ground and break. Therefore he will have to move the basket left and right on the screen to position it under the falling eggs. To give it an initial marketing boost we are going to call the game “EggCraft”.

Most of you will probably use Xcode to create your iOS games since it comes with the SDK and is the one IDE that fully integrates with the iOS development cycle. To reduce initial friction when creating new apps the Sparrow source ships with a predefined project structure we call the GameScaffold. You can copy/paste/rename that scaffold and start coding right away without worrying about the setup of the project. However, if you are of the investigative confession there is an extensive step-by-step guide on the Sparrow Framework website that explains how to set up a new Sparrow project from scratch. Let’s for the sake of speed assume that you kopimismed the scaffold and move on to the game code.

Coding Away

Being impatient, as game developers usually are, we could spaghetti-code the whole game into our AppDelegate. However, since that’s a no-go in terms of cleanliness we are in need of a separate class that wraps that management code: The GameScaffold already contains such a class and it has the admittedly unimaginative name “Game”. It will be responsible for creating, managing and releasing the three other necessary objects: A background image, the basket and the falling eggs. We can load the background and basket images using the display object type SPImage and assign them to iVars. In doing that we must not forget to release them when the game gets its dealloc notification. Here is the first version of our Game class:

@interface Game : SPSprite
@end

@implementation Game
{
@private
	SPImage *mBackground;
	SPImage *mBasket;
	NSMutableArray *mEggs;
}

- (id)init
{
	if((self = [super init]))
	{
		//load the background image first, add it to the display tree
		//and keep it for later use
		mBackground = [[SPImage alloc] initWithContentsOfFile:@"background.png"];
		[self addChild:mBackground];
		
		//load the image of the basket, add it to the display tree
		//and keep it for later use
		mBasket = [[SPImage alloc] initWithContentsOfFile:@"basket.png"];
		[self addChild:mBasket];
		
		//create a list that will hold the eggs,
		//which we will add and remove repeatedly during the game
		mEggs = [[NSMutableArray alloc] init];
	}
	return self;
}

- (void)dealloc
{
	[mBackground release];
	[mBasket release];
	[mEggs release];
	[super dealloc];
}

@end

Nice, isn’t it? In a more complex game we would go ahead and create separate classes for the basket and eggs too, but since our demo game is of microscopical proportions we can dispense with that. The game now shows a background image and the basket the player will move around. It’s time to go ahead and make that basket move when the user touches it. Before we can do that we need to take a detour and understand the Sparrow event system. Stay a while and listen…

Events

Do you remember the display tree we’ve met earlier? It allows us to organize our game objects in an hierarchical way in order to elegantly group, move and rotate our simple-to-complex objects. Any object visible to the user is part of the display tree. But guess what: The display tree is capable of more than just showing stuff to the user!

To make the basket move we need to check if the user is touching the basket. Every time he moves his finger on the basket we want the basket to follow that finger left and right. Wouldn’t it be convenient to be able to listen to such a “touch event” and update the x coordinate of the basket accordingly? Thank goodness Sparrow offers a powerful event system that permits us to do just that. Phew!

In Sparrow, just like in ActionScript, any display object within the display tree can fire events. Once fired those events travel down along the branches of the display tree and visit every related node until they hit the root node a.k.a. the stage. For example the wheel of a car can fire a FlatTire event: That FlatTire event would immediately start traveling towards the stage. On it’s way it would visit the car object itself which could subsequently react to the event by lighting a red bulb on the car’s dashboard or even more spectacular starting to fishtail off the road, overturn and explode.

There are many different types of events in Sparrow and you are free to create as many custom events as you please but the one you will not be able to dodge in any interactive Sparrow app is the built-in SPTouchEvent. As the name gives away already it tracks the user touches on your iOS device. Since we can add a touch listener to any object in the display tree and wait for the user to touch that object we are going to add one to our game’s basket and listen to it in the Game class. As soon as we receive a touch event we will update the basket’s position to make it follow the user’s finger:

@implementation Game

- (id)init
{
	if((self = [super init]))
	{
		//…
		
		mBasket = [[SPImage alloc] initWithContentsOfFile:@"basket.png"];
		
		//add the touch event listener
		[mBasket addEventListener:@selector(onBasketTouched:) atObject:self forType:SP_EVENT_TYPE_TOUCH];
		[self addChild:mBasket];
		
		//…
	}
	return self;
}

- (void)onBasketTouched:(SPTouchEvent *)event
{
	//fetch the first touch (from the first finger on the device)
	SPTouch *touch = [[event.touches allObjects] objectAtIndex:0];
	
	//find the touch position
	SPPoint *localTouchPosition = [touch locationInSpace:self];
	
	//apply the new x-coordinate to the basket
	mBasket.x = localTouchPosition.x;
}

//…

@end

Our game is now ready to react to user touches and the basket is following our user’s finger! By the way, did you notice that in our onBasketTouched listener method we fetched the first from a whole list of touches? That’s because with iOS we are on a multi-touch system and users can put as many fingers as they want or have onto the device’s screen. Getting a list of all simultaneous touches allows us to create fancy effects like zooming and rotating with two fingers or even track the fingers of multiple players on a single device, e.g. for an air-hockey game.

Now that we’ve met the basic event system we can extend that knowledge a little further to make the eggs fall from the sky.

Frames Per Second

As mentioned earlier there are numerous different event types in Sparrow and to make our game work we will make use of one more: In order to create the impression that eggs are falling from the sky we repeatedly need to create them on top of the screen, move and rotate them to the bottom, check if they have been caught by the user or did break on the ground and remove them again. Therefore we are going to add a listener for SPEnterFrameEvents which is going to get notified once in every frame (preferably 60 times per second). Within that listener we will iterate over our mEggs array, move and rotate the eggs a little further, check for collisions with the ground and the basket and create new eggs in a fixed interval. When an egg smashes into the ground we will replace it with the image of some yolk. It’s code time:

@implementation Game

- (id)init
{
	if((self = [super init]))
	{
		//…
		
		//add an enter frame listener
		[self addEventListener:@selector(onEnterFrame:) atObject:self forType:SP_EVENT_TYPE_ENTER_FRAME];
	}
	return self;
}

- (void)onEnterFrame:(SPEnterFrameEvent *)event
{
	float passedTime = (float)event.passedTime;
	float fallingSpeed = 100 + 5*mTotalTime;
	float fallingDistance = fallingSpeed*passedTime;

	for (SPImage *egg in [[mEggs copy] autorelease])
	{
		//move the egg
		egg.y += fallingDistance;
		egg.rotation += passedTime;

		//check for collisions with the ground and the basket
		BOOL didBreak = egg.y >= mBackground.height - egg.height/2;
		BOOL didGetCaught = [mBasket.bounds intersectsRectangle:egg.bounds];
		if(didBreak)
		{
			//break the egg: replace the egg with a yolk texture
			SPImage *yolk = [SPImage imageWithContentsOfFile:@"yolk.png"];
			yolk.x = egg.x;
			yolk.y = egg.y;
			[self addChild:yolk];
			[self removeChild:egg];
			[mEggs removeObject:egg];
		}
		else if(didGetCaught)
		{
			//just remove the egg
			[self removeChild:egg];
			[mEggs removeObject:egg];
		}
	}

	//create and add new eggs if necessary
	mTotalTime += passedTime;
	if(mTotalTime - mCreationTimeOfLastEgg >= mEggCreationInterval)
	{
		SPImage *egg = [SPImage imageWithContentsOfFile:@"egg.png"];
		[self addChild:egg];
		[mEggs addObject:egg];
	}
}

//…

@end

Our game just went from meh to yay! The eggs are falling in a more or less believable way and the user is able to catch them with the basket. If he fails to do so they smash into the ground and break.

By the way, it’s a topic open to debate but in my opinion you should be obsessed with your games frame rate: Performance is a key quality in every application and even more so in games. Unfortunately a high frame rate is nothing you will win a price for but a low frame rate and/or choppiness will make a bad impression and can get you bad reviews in the AppStore. Since our onEnterFrame listener method is called within every single frame it is not a good idea to make a copy of the mEggs array every time it gets notified. I did this to circumvent concurrent modifications on the array and still keep the lines of code down. That approach should be replaced with a more efficient algorithm before the game is ready to hit the AppStore to make billions of billions of dollars.

The Juggler and his Tweens

We achieved a lot already! We know how to load images and present them to the user, we met the display tree as well as the display objects and learned how to make use of touch event and enter frame listeners. It’s now time to meet another powerful wrench in the Sparrow toolbox: The tween.

Tweens are busy little helpers that assist us in animating our game objects. Let’s for example add a short animation to the yolk that pours out of the broken eggs: As of now it just lies on the ground in a static and boring way whilst it should actually make the impression of liquid goo, drip downwards and vanish at some point. We could go ahead and animate the width, height and alpha properties of the yolk manually within our onEnterFrame listener, but that would be immensely cumbersome and end up in an exhausting iVar massacre retaining progress and states of the yolk.

Fortunately we can create a tween and tell it what to do with the yolk’s properties. Tweens are able to transition any numeric property (yes, even custom properties) from their start value to a defined end value within a chosen time frame. We can, for example, tell a tween to transition the alpha value of our yolk to zero in two seconds, thus making it vanish gradually. Such a setup would take not more than two lines of code:

SPTween *tween = [SPTween tweenWithTarget:yolk time:2];
[tween animateProperty:@"alpha" targetValue:0];

Now that we are capable of animating the yoke’s properties we can extend that snippet to imitate dripping fluid and execute it every time an egg crashes within the onEnterFrame method. Tweens are a mighty tool and you will encounter them a lot, especially when you forward information to the user by showing game progress, scores, menus and whatnot.

There is, however, one further thing we need to do to unleash our tween: A tween is a lean class holding and updating the progress for the property transitions it manages. Neither does it know the current time nor the frame rate. We need some kind of manager that forwards time intervals (e.g. the passed time of every frame) to all our tweens. That’s where the juggler comes into play: As the name already suggests the juggler is happy to take our tweens and juggle them through the air, ergo feeding them time info, until they are done with their work. It reliefs us from the dull but dangerous challenge of retaining and releasing all our tweens and manually forwarding time intervals to them.

We can create as many jugglers as we like to separate our animations into logical groups: It is for example common practice to create one juggler for the menu system and one for the game itself. That way one is able to easily pause the game while the menu is still being animated. For our game however we don’t need such a separation. The stage is already running a juggler for convenience and we can make use of it:

@implementation Game

- (void)onEnterFrame:(SPEnterFrameEvent *)event
{
	//…
	
	//animate the yolk
	SPTween *tween = [SPTween tweenWithTarget:yolk time:1];
	[tween animateProperty:@"y" targetValue:yolk.y + yolk.height];
	[tween animateProperty:@"height" targetValue:2*yolk.height];
	[tween animateProperty:@"alpha" targetValue:0];
	[self.stage.juggler addObject:tween];
}

@end

The falling eggs are now breaking and their yolk is dripping down and vanishing in the soil of the ground.

There are many things that we’d need to add to the game in order to make it accessible for players, for example a dashboard showing stats, a menu and above all a victory condition. Right now you can play the game indefinitely without ever getting a game over screen, which is a trend in social gaming but will get boring really fast in our case.

In The End

Congratulations! You just finished your first Sparrow game! You know how to setup your project and how to make use of the display tree. You are familiar with the event system and you are able to animate your stage with tweens.

Sparrow brings many more exciting features that I did not cover since that would have gone beyond the scope of this article. I should mention some of them for at least a hint of completeness. The Sparrow can:

Last but not least you can pull the complete game code for EggCraft from github. I hope I was able to get you started with Sparrow and you had a good time reading this. :-) Have fun with Sparrow! Holger out.