<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>iConverged &#187; world 2.0</title>
	<atom:link href="http://blog.roychowdhury.org/category/world-20/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.roychowdhury.org</link>
	<description></description>
	<lastBuildDate>Thu, 05 Jan 2012 22:06:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Thanks Steve</title>
		<link>http://blog.roychowdhury.org/2011/10/07/thanks-steve/</link>
		<comments>http://blog.roychowdhury.org/2011/10/07/thanks-steve/#comments</comments>
		<pubDate>Fri, 07 Oct 2011 12:24:41 +0000</pubDate>
		<dc:creator>Arjun</dc:creator>
				<category><![CDATA[Arjun Roychowdhury]]></category>
		<category><![CDATA[general technology]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[world 2.0]]></category>
		<category><![CDATA[iconic]]></category>
		<category><![CDATA[legend]]></category>
		<category><![CDATA[steve jobs]]></category>
		<category><![CDATA[thanks steve]]></category>

		<guid isPermaLink="false">http://blog.roychowdhury.org/?p=648</guid>
		<description><![CDATA[Image tribute designed by Jonathan Mark Even if you never met the man, if his visionary products helped your child to read and write at an early age, let grandparents see their grandchildren across thousands of miles without having to crowd around a computer, led the transformation of the mobile and music industry that pays your salary today, made product companies rethink their priorities towards customers, and most importantly made many of us want to make even a fraction of a dent he has made to this industry and shape our careers accordingly, its not surprising that on his passing you&#8217;d think you knew him very well and to ask yourself &#8216;What do you want to do before you go&#8217;?]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.roychowdhury.org/wp-content/uploads/2011/10/ht_steve_jobs_apple_jonathan.jpg"><img class="alignnone size-full wp-image-650" title="ht_steve_jobs_apple_jonathan" src="http://blog.roychowdhury.org/wp-content/uploads/2011/10/ht_steve_jobs_apple_jonathan.jpg" alt="" width="478" height="269" /></a></p>
<p><em><span style="color: #888888;">Image tribute designed by <a href="http://jmak.tumblr.com/post/9377189056"> Jonathan Mark</a></span></em></p>
<p>Even if you never met the man, if his visionary products helped your child to read and write at an early age, let grandparents see their grandchildren across thousands of miles without having to crowd around a computer, led the transformation of the mobile and music industry that pays your salary today, made product companies rethink their priorities towards customers, and most importantly made many of us want to make even a fraction of a dent he has made to this industry and shape our careers accordingly, its not surprising that on his passing you&#8217;d think you knew him very well and to ask yourself &#8216;What do you want to do before you go&#8217;?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.roychowdhury.org/2011/10/07/thanks-steve/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>(Book Review) Cocos2D – Its raining books, Hallelujah!</title>
		<link>http://blog.roychowdhury.org/2011/01/17/cocos2d-its-raining-books-hallelujah/</link>
		<comments>http://blog.roychowdhury.org/2011/01/17/cocos2d-its-raining-books-hallelujah/#comments</comments>
		<pubDate>Mon, 17 Jan 2011 10:19:17 +0000</pubDate>
		<dc:creator>Arjun</dc:creator>
				<category><![CDATA[Arjun Roychowdhury]]></category>
		<category><![CDATA[Gaming]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[world 2.0]]></category>
		<category><![CDATA[book review]]></category>
		<category><![CDATA[cocos2d]]></category>
		<category><![CDATA[guide]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.roychowdhury.org/?p=553</guid>
		<description><![CDATA[Till just a few weeks ago, there were no real books one could read on Cocos2D game programming. While there are an almost infinite number of web tutorials, a book has a different charm &#8211; it is usually more structured and hopefully better researched. A few weeks ago, the first book on Cocos2D surfaced, &#8220;Learn iPhone and iPad cocos2D game development&#8221; by Steffen Itterheim. I bought it on day 1 of its release, and posted my review here. In short, it was well written and, well, the very first book for cocos2D, so it had that first mover advantage. The other book I am eagerly waiting for is Rod Strougo and Ray Wenderlich&#8217;s book &#8220;Learning Cocos2D&#8220;. The book is yet to be released, but I get the feeling it will be more &#8216;advanced&#8217; than the other available books. In the mean time, I was contacted by another company, Packt Publishing who sent me an email to review a new book from them: Cocos 2D for iPhone 0.99 &#8211; Beginners Guide by Pablo Ruiz. Here is the introduction of the book, in the Preface: &#8220;This book will teach you the fundamentals of how to write games with this framework. As this<a href="http://blog.roychowdhury.org/2011/01/17/cocos2d-its-raining-books-hallelujah/"> <br /><br /> (Read More...)</a>]]></description>
			<content:encoded><![CDATA[<p><a href="https://www.packtpub.com/cocos2d-games-for-iphone-0-99-beginners-guide/book"><img class="alignleft size-full wp-image-559" title="Screen shot 2011-01-17 at 4.04.16 PM" src="http://blog.roychowdhury.org/wp-content/uploads/2011/01/Screen-shot-2011-01-17-at-4.04.16-PM.png" alt="" width="200" height="260" /></a>Till just a few weeks ago, there were no real books one could read on Cocos2D game programming. While there are an almost infinite number of web tutorials, a book has a different charm &#8211; it is usually more structured and hopefully better researched. A few weeks ago, the first book on Cocos2D surfaced, &#8220;<a href="http://www.amazon.com/Learn-iPhone-iPad-Cocos2D-Development/dp/1430233036">Learn iPhone and iPad cocos2D game development</a>&#8221; by Steffen Itterheim. I bought it on day 1 of its release, and posted my review <a href="http://www.amazon.com/review/R2SJL7ABLJS76P/ref=cm_cr_pr_viewpnt#R2SJL7ABLJS76P">here</a>. In short, it was well written and, well, the very first book for cocos2D, so it had that first mover advantage.</p>
<p>The other book I am eagerly waiting for is Rod Strougo and Ray Wenderlich&#8217;s book &#8220;<a href="http://www.amazon.com/gp/product/0321735625/ref=pd_lpo_k2_dp_sr_1?pf_rd_p=486539851&amp;pf_rd_s=lpo-top-stripe-1&amp;pf_rd_t=201&amp;pf_rd_i=1430233036&amp;pf_rd_m=ATVPDKIKX0DER&amp;pf_rd_r=1YCAE9GQ0CRD32H0WJ3N">Learning Cocos2D</a>&#8220;. The book is yet to be released, but I get the feeling it will be more &#8216;advanced&#8217; than the other available books.</p>
<p>In the mean time, I was contacted by another company, Packt Publishing who sent me an email to review a new book from them: <a href="https://www.packtpub.com/cocos2d-games-for-iphone-0-99-beginners-guide/book">Cocos 2D for iPhone 0.99</a> &#8211; Beginners Guide by Pablo Ruiz.</p>
<p><span id="more-553"></span></p>
<p>Here is the introduction of the book, in the Preface:</p>
<p><em>&#8220;This book will teach you the fundamentals of how to write games with this framework. As this book is meant to give you a basic knowledge of the most important aspects of Cocos2d, it will cover a lot of subjects very quickly. However, do not worry! Almost every chapter will include tasks for you to complete and examples for you to practice. Throughout this book, we&#8217;ll make three different games and each chapter will build on the previous one, but can also be considered independently, so feel free to skip to any chapter that interests you.&#8221;</em></p>
<p>So this post is a review of this new book by Pablo.</p>
<p><em>Full Disclosure:</em> I was contacted by the company to review their book &#8211; they gave me a free e-copy so I could read and comment. Beyond this, I have no monetary or any other form of profit/benefit from this post. In other words, if I thought this book is crap, I can call it crap. If I think its good, I can call it good.</p>
<p><strong>So how is Pablo Ruiz&#8217;s </strong>&#8220;<strong>Cocos2D for iPhone 0.99&#8243; ?</strong></p>
<p><em>The Good</em></p>
<ol>
<li>Its 350 pages of relevant content. The author dives into topics quickly and gets to code examples very soon.</li>
<li>It covers the usual topics like fiddling with sprites, more details on actions, scene and menu management, particle systems, cocosdenshion</li>
<li>I liked the fact that the examples Pablo chose of games are better than &#8216;stupid games that only prove a concept&#8217;. For example, &#8220;Chapter 2:Playing with Sprites&#8221; is a 54 (approx) page chapter which incrementally goes about building a board game where you align stones based on color by swapping them around and then when you align them, the stones destroy themselves. In this 50 page chapter, he goes through the basics of CCSprite, using CCTouchDispatcher for touch management, using Zwoptex to create Sprite Sheets,using CCTextureCache to pre load images for faster response time and even a few lines of OpenGL (basic stuff like drawing a box around an item you select)</li>
<li>He continues the same board game across Chapters 3&amp;4 (another 55 odd pages), where he embellished the game with actions (the usual CC actions along with the ease in action effects). There is a nice page in his book that shows the animation path of each ease action. It looks like it was copy pasted from some standards reference &#8211; if so, then you may already know about it &#8211; but to me, it was nice to see the easein/out effects on one page. Finally, in Chapter 4, he shows us how to add fonts and text labels to the game and goes through the basics on how to create your own font with CCBitmapFontAtlas.</li>
<li>While the board game was interesting, I was getting bored. Fortunately, at Chapter 5, Pablo stars a new game that basically is called &#8220;Aerial Gun&#8221; which is a shooting game. You control an airplane while enemies approach you &#8211; you have to kill em. In this chapter his focus is on the basics of the game &#8211; sprite movement, handling accelerometer based movements, how to fire bullets (bullets stored in an array so you see a spurt of them), collision detection</li>
<li>Then, in chapter 6, he adds options and other menus to the game, including telling us how to use the basis NSUserDefault class to store preferences</li>
<li>Finally, in chapter 7,he integrates the Cocos2D particle system into his game to give explosion effects. One thing I liked was it covers the meaning of all the attributes of a particle system (again at a cursory level). Specifically, I liked the section where he covers how to give an explosion effect when your enemy is hit including telling us how to make the particles move correctly. All of this is directly by manipulating the particle parameters he briefly explained earlier. And then he finishes off with using ParticleDesigner, which is pretty much the defacto particle design tool, it seems</li>
<li>In Chapter 8, he covers background panning using tilemaps. Nothing new or unique here. But if you don&#8217;t know tilemaps, here it is.</li>
<li>Chapter 9 covers the CC Sound engine. He covers both SimpleAudioEngine and CDSoundEngine</li>
<li>What stands out from the others in this book is the chapter on Chipmunk.  Chipmunk is a physics engine that can add realism to your games (like the toppling monuments in angry birds).  Most tutorials and books cover Box2D (even Steffen&#8217;s book I reviewed  earlier). Box2D seems more able, but is reasonably more complicated. And  I really wanted a good reference to chipmunk (as a beginner). I was  very happy to see Pablo cover chipmunk. Just for that, I&#8217;d give him  kudos. And also, he goes through several pages in building a relevant game &#8211; a totem block, that rests on top of various blocks of different shapes. Your goal is to remove the blocks without the totem falling on the floor.</li>
<li>There is also a chapter on <a href="http://www.openfeint.com/">OpenFeint</a> &#8211; I liked it. Frankly, I never knew about it. OpenFeint  is a software library you can link your code with that allows your game  to become &#8220;social&#8221;. In other words, you get access to leader boards,  get notifications on new scores from your buddies in your network,  connect and post messages to Face Book and more. Yep, you guessed it. It  can also become a nightmarish tool if you choose to abuse it (remember  those beyond irritating messages from all your friends in facebook about  some idiotic occurrence in some mafia game they were playing etc.) Used properly, OpenFeint looks like a very nice tool and Pablo covers it well.</li>
</ol>
<p><em>The Bad</em></p>
<ol>
<li>The book is hurried. Just too hurried. When you start focusing on a topic into the next level of detail, you feel like the author is trying to complete a race in record time. While at first glance, it looks like he has spent time with details, when you really want to understand something new, you feel he should have spent more time with details.</li>
<li>Code level commentary is high-level and has errors. Consider for example, the chapter on Chipmunk. This was my first point of interest, so I decided to actually try out his examples. I was not given his resource file zips, so I had to type them in myself. The instructions were cursory at best:
<ol>
<li>Example, he just says &#8220;rename HelloWorld&#8221; to &#8220;GameScene&#8221; (no further instructions, and it is not just renaming &#8211; you have to rename more than one part, and refactoring was a better approach as far as I feel)</li>
<li>He says &#8220;in init method of GameLayer class, change space gravity to 0,-200&#8243; without saying where that line would be and what are we looking for. Again, basic stuff &#8211; if you know your stuff, you don&#8217;t have an issue. But if you are a beginner, you are left wondering</li>
<li>Finally, he asks us to introduce a line declaring a totem variable, which never compiles because the instructions forgot to tell us to declare it first (and there too, he says in another example &#8220;declare an ivar&#8221; &#8211; thats all). Again, not an issue for those who know, but if you are really a beginner, you will feel lost at his pace and choice to ignore details.</li>
<li>So basically, you either describe it well enough and the reader can figure out errors on their own, or, you describe it at a high level but make sure the code has no errors. <em>Again, like I said &#8211; I did not get enough time to actually try his other examples. Unfortunately, the first chapter I did try to get into details (chipmunk) left me floundering (remember I am a beginner to cocos2d, and am supposed to be a target audience for his book as per the preface)</em></li>
</ol>
</li>
<li>There may be other issues, I am on travel, so I could not do a thorough read.</li>
</ol>
<p><strong>Verdict &#8211; Better than Steffen Itterheims Cocos2d book?</strong></p>
<p>Frankly, from what I read so far, I don&#8217;t think so. While Pablo&#8217;s book covers more topics, the one chapter I actually decided to dive into came out with several errors.  Steffen&#8217;s book is more thought out and not hurried at all. And I&#8217;d say there i around 60-70% intersection of topics between the books. And unless  I try out more of Pablo&#8217;s code in the book, I can&#8217;t honestly say it is <em>the book </em> for beginners.</p>
<p>But besides that, it covers enough topics to be of interest. I think if Pablo spent more time with details on the book, it would be a treasure trove. Also, there is limited (or no) handling of the more advanced Cocos2D functions like isometric tilemaps, Cocos2D Camera, Parallax scrolling etc.</p>
<p>Having said all of the above, I think the author will likely improve the quality of the book in future versions.</p>
<p><strong>Should you buy it?</strong></p>
<p>Well, if it was the first book, I would buy it. Since I already have one book and I will surely buy the one by Rod  &amp; Ray (just because of the reputation), it makes buying this book a not-so-easy-choice. For those who choose to buy it, it will give you lots of help and a great head start. But be expected to be rushed and brace yourselves for errors in code.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.roychowdhury.org/2011/01/17/cocos2d-its-raining-books-hallelujah/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tutorial: iPhone Game Programming- professional Bricks (Part III)</title>
		<link>http://blog.roychowdhury.org/2010/10/27/tutorial-iphone-game-programming-professional-bricks-part-iii/</link>
		<comments>http://blog.roychowdhury.org/2010/10/27/tutorial-iphone-game-programming-professional-bricks-part-iii/#comments</comments>
		<pubDate>Wed, 27 Oct 2010 19:59:32 +0000</pubDate>
		<dc:creator>Arjun</dc:creator>
				<category><![CDATA[Arjun Roychowdhury]]></category>
		<category><![CDATA[Gaming]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[world 2.0]]></category>
		<category><![CDATA[bricks]]></category>
		<category><![CDATA[game programming]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[quartz2D]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[uikit]]></category>

		<guid isPermaLink="false">http://blog.roychowdhury.org/?p=431</guid>
		<description><![CDATA[Click here for Part I Click here for Part II In Part II, we dove in to the implementation of pretty much every function except the core gameplaying logic. This part will now discuss the implementation of the core game playing logic and how I handle touch detections. Before we do that, here is the video again of what we are implementing. Game On! Update: After I posted this code, in a subsequent update, I separated the direction variable from the speed variable. That makes code handling cleaner.In this version you will see the ball getting messed up in some situations. I&#8217;ll leave it to you to fix that part. I also added 10 levels and a high score list &#8211; easy to do &#8211; not part of the code I posted here Well, what can I say. I&#8217;ve already commented the code well enough. Do I really need to explain more below? Brick Collision Logic starts here Lets stop here. Basically, the game logic starts with me iterating through each brick (double-for-loop). Why? Because the bricks are the center of the game. Everything (except for ball hits paddle/misses paddle) centers around the bricks. First thing I do is that<a href="http://blog.roychowdhury.org/2010/10/27/tutorial-iphone-game-programming-professional-bricks-part-iii/"> <br /><br /> (Read More...)</a>]]></description>
			<content:encoded><![CDATA[<p><span style="color: #ff0000;"><span style="color: #888888;">Click here for <a href="http://blog.roychowdhury.org/2010/10/25/tutorial-iphone-game-programming-professional-bricks-part-i/">Part I</a></span></span></p>
<p><span style="color: #ff0000;"><span style="color: #888888;">Click here for <a href="http://blog.roychowdhury.org/2010/10/26/tutorial-iphone-game-programming-professional-bricks-part-ii/">Part II</a></span></span></p>
<p>In <a href="http://blog.roychowdhury.org/2010/10/25/tutorial-iphone-game-programming-professional-bricks-part-ii/">Part II</a>, we dove in to the implementation of pretty much every function except the core gameplaying logic. This part will now discuss the implementation of the core game playing logic and how I handle touch detections.</p>
<p><span id="more-431"></span></p>
<p>Before we do that, here is the video again of what we are implementing.</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="480" height="385" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/YpK0OmGjiIE?fs=1&amp;hl=en_US&amp;rel=0" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="480" height="385" src="http://www.youtube.com/v/YpK0OmGjiIE?fs=1&amp;hl=en_US&amp;rel=0" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<h1>Game On!</h1>
<p><span style="color: #993300;">Update: After I posted this code, in a subsequent update, I separated the direction variable from the speed variable. That makes code handling cleaner.In this version you will see the ball getting messed up in some situations. I&#8217;ll leave it to you to fix that part. I also added 10 levels and a high score list &#8211; easy to do &#8211; not part of the code I posted here </span>
<pre class="brush: objc; title: ; notranslate">
//=============================================================================
// This is the heart of the game. Checks for collisions, hits, misses etc. Can be cleaned up better
- (void) playGame:(NSTimer *)timer
{
	static int hack_hit_count = 0;
	if (kGamePause) {return;}

	//First Check for brick collision
	// basically, we iterate through the array of bricks
	// and compare if the ball location intersects with any of the bricks location
	// From a display perspective, we are not really deleting the brick. We are simply making its alpha (transparency)
	// to 0 so it looks like its gone. Therefore, when we check if the ball has hit a brick, we also need to check if
	// the brick is not transparent. If it is, its been hit before.
</pre>
<p>Well, what can I say. I&#8217;ve already commented the code well enough. Do I really need to explain more below?</p>
<h2>Brick Collision Logic starts here</h2>
<pre class="brush: objc; title: ; notranslate">
#pragma mark Brick Collision logic

	int youWin=1;	   // if this is 0, then there is atleast one brick that has not been hit. If 1, all bricks
					   // have been hit.
	for (int y=0; y&lt;BRICKS_ROWS; y++)
	{
		for (int x=0; x&lt;BRICKS_COLUMNS; x++)
		{

			// make sure the ball intersects the brick propoerly.
			// since the ball is circular,  take a hit only if its 3x1 pixels into the brick intersection
			CGRect brick_inside = bricks[y][x].frame;
			brick_inside.size.width -=3;
			brick_inside.size.height-=1;
			brick_inside.origin.x +=3;
			brick_inside.origin.y +=1;

                         int ballHitBrick = CGRectIntersectsRect(ball.frame, brick_inside);
			int missileHitBrick = (CGRectIntersectsRect(missileView.frame, bricks[y][x].frame));
</pre>
<p>Lets stop here. Basically, the game logic starts with me iterating through each brick (double-for-loop). Why? Because the bricks are the center of the game. Everything (except for ball hits paddle/misses paddle) centers around the bricks.  First thing I do is that for each brick, I check if the ball location intersects with the brick. How? I use the convenient &#8220;CGRectIntersectsRect&#8221; function that basically returns a yes or no depending on whether two frames intersect at any co-ordinate points. However, remember that the ball is a sphere &#8211; so is it possible it may not actually have hit and the edge of the frame of the ball hit the edge of the frame of the brick. To make it it a little more precise, I actually checking if the ball hit a &#8220;sub-frame&#8221; of the brick which is 3 pixels by 1 pixel inside (X:Y) the brick frame. While playing the game, I felt this avoid some situations where other bricks get exploded even though you feel they should have been left alone. I suppose it would be more accurate if I computed the ball radius, matched it up with the distance of intersection etc. but that was too much work. This seemed to be pretty effective too&#8230;.  So anyway, ballHitBrick will be a 1 if the ball hit the &#8220;inside&#8221; of the brick as explained above. Similarly, we also need to know if the missile hit the brick. Same logic &#8211; but now with the missile position.
<pre class="brush: objc; title: ; notranslate">
if ((bricks[y][x].alpha==1) &amp;&amp; (brick_description[y][x]&gt;=NORMAL_BRICK))
{
</pre>
<p>Let&#8217;s see what&#8217;s going on here.  First, we need to do all the collision processing only if:  a) The brick alpha is 1  b) the brick is described to be a normal brick, steel brick or super brick  Why?  Because if the alpha is not 1, that means we have hit it before (you will see that when we hit a brick, we slowly reduce its alpha to 0 using animation. So theoretically, if the ball hit a brick and a missile hit it immediately after &#8211; its not 2 hits, because you already hit it). Finally, if the brick is not a normal brick, steel brick or super brick, then what is it? Its a &#8220;no brick&#8221; (i.e. the brick_description array described that that brick should not be displayed &#8211; no brick). From a display perspective that brick is not shown, but when checking the array, its still there, with transparency 0. So we skip these conditions.
<pre class="brush: objc; title: ; notranslate">

				if (brick_description[y][x] !=METAL_BRICK) {youWin=0;}

				 if (ballHitBrick || (missileHitBrick) &amp;&amp; (missileView.hidden==NO))
				 {
</pre>
<p>If the ball hit the brick, or the missile hit the brick, then we&#8217;ve got a hit!
<pre class="brush: objc; title: ; notranslate">
					// Coming here means that the ball has hit a brick that has not been hit before
					 // or, the missile hit a brick

					if ((brick_description[y][x]==NORMAL_BRICK) || (brick_description[y][x]&gt;=SUPER_BRICKS))
					{
</pre>
<p>Remember I said this game grew in spurts? I never thought of super bricks first. I only had a normal brick (value 1). Then I added a steel brick (value 2)  Then I added super bricks. As it turns out, a normal brick can explode, and so can all super bricks but not a steel brick. So, we need to show explosion only for  these kinds of bricks but skip steel bricks&#8230;
<pre class="brush: objc; title: ; notranslate">
						NSLog(@&quot;YOU HIT:%d:%d&quot;,y,x);
						if (kHackHitCount) {hack_hit_count++;}
						//NSLog (@&quot;HACK HIT COUNT %d &amp; kHack:%d&quot;, hack_hit_count, kHackHitCount);
						score += 10;
						labelScore.text = [NSString stringWithFormat:@&quot;%d&quot;, score];
</pre>
<p>So you hit a brick thats not steel, thats not transparent. You deserve a pat and a +10 in score.
<pre class="brush: objc; title: ; notranslate">

						if (missileHitBrick)
						{
							NSLog(@&quot;MISSILE HIT&quot;);
							missileView.hidden=YES; // after a hit, hide the missile
							kMissileFiring=0;	// allow other missiles to be fired
						}

						[self playAudio:explodeSound];
						[self explodeBrick :y :x];
</pre>
<p>In addition to checking if the ball hit that brick, lets also see if the missile hit the brick. Yeah, no score addition for this. Real men don&#8217;t use missiles.  But anyway, lets play the awesome explosion sound and explode the brick. We pass the col &amp; row of the brick that was hit to explodeBrick. what explodeBrick does then is animate the explosion image centering it on bricks[y][x].center &#8211; in other words right at the center of the hit brick.
<pre class="brush: objc; title: ; notranslate">
						bricks[y][x].alpha -= 0.1; // reduce alpha right away by a pt.
												  // just in case you hit it again before anim begins....
						[UIView beginAnimations:@&quot;fadebrick&quot; context:nil];
						[UIView setAnimationCurve:UIViewAnimationCurveLinear];
						[UIView setAnimationDuration:0.8];
						[UIView setAnimationDelegate:self];
						bricks[y][x].alpha=0;
						[UIView commitAnimations]; // fade out killed brick
</pre>
<p>And while the explosion plays out, let&#8217;s also animate the brick to fade out in parallel. We can use beginAnimation here because as the brick is fading out, we don&#8217;t need to know its current fade state or anything. Being extra paranoid, before I start the animation, I reduce the alpha by 0.1 anyway so that theoretically, if something else hits that brick immediately before the animation begins to reduce alpha the hit won&#8217;t count again. Maybe this is not necessary.
<pre class="brush: objc; title: ; notranslate">

						if (brick_description[y][x]==LIFE_BRICK) // this means you get a life
						{

							if (livesleft&lt;LIVES)
							{
								lives[livesleft].alpha=1;
								lives[livesleft].transform = CGAffineTransformIdentity;
								++livesleft;
								[self playAudio:gotlifeSound];

							}
							NSLog(@&quot;you got a life&quot;);
						}
</pre>
<p>If you hit a super brick which is a life brick, lets add to your lives (if you are already at max lives, we don&#8217;t add again).  Remember the lives array shows your current lives? Each time you lose a life, we reduce the opacity of one icon of the total lives to 0. So when you get a new life, we turn the opacity of the most recent life lost back to 1 so it shows up on the screen.
<pre class="brush: objc; title: ; notranslate">
						else if (brick_description[y][x]==MISSILE_BRICK) // you get a few missiles
						{
							kMissilesLeft+=5;
							haveMissileView.hidden=NO;
							NSLog(@&quot;You have 5 more missiles. Your missile count is %d&quot;, kMissilesLeft);
						}

					} // normal brick
</pre>
<p>If you hit a missile superbrick, we just add 5 more to your available missiles. These compound. So if you hit two missile bricks, you get 10. Also, we want to show you when you have missile power.  So on the lower right, we enable the display of a small missile icon (it is created and positioned as hidden in interface builder initially)
<pre class="brush: objc; title: ; notranslate">
					else
					{ // you hit a steel bar
						[self playAudio:metalSound];
						tBallSpeedX = 5 + arc4random() % 5; // let the ball 'shoot' out faster if it hits metal
						//if (ballSpeed.x &lt; 0) {tBallSpeedX = -tBallSpeedX;}
						NSLog(@&quot;You hit steel. Ball speed temporarily upped to %d&quot;,tBallSpeedX);
					}
</pre>
<p>But if you hit a steel brick, play a clang sound, and add a &#8220;random&#8221; delta to the X speed of the ball so when the ball bounces it will act like it just darts out instead of a normal bounce out.  This delta is reset to 0 when it bounces off the screen boundaries, so the feeling you get is that the ball shot out after hitting a steel brick and then resumes normal operation on next bounce
<pre class="brush: objc; title: ; notranslate">
					if (!missileHitBrick) //don't reverse ball direction if a missile hit
					{
						if ((ballSpeed.x&gt;0) &amp;&amp; (ballSpeed.y&gt;0)) { ballSpeed.y = -ballSpeed.y;}
						else if ((ballSpeed.x&gt;0) &amp;&amp; (ballSpeed.y&lt;0)) { ballSpeed.y = -ballSpeed.y;}
						else if ((ballSpeed.x&lt;0) &amp;&amp; (ballSpeed.y&gt;0)) { ballSpeed.x = -ballSpeed.x;}
						else if ((ballSpeed.x&lt;0) &amp;&amp; (ballSpeed.y&lt;0)) { ballSpeed.y = -ballSpeed.y;}

						if (ballSpeed.x &lt;0) tBallSpeedX = -tBallSpeedX;
						if (ballSpeed.y &lt;0) tBallSpeedY = -tBallSpeedY;
					}

				} // CGRectIntersect
			} // if you hit a solid brick
		} //x
	} //y
</pre>
<p>Now, finally, if your ball hit a brick, it needs to &#8216;bounce off&#8217; the brick too. It can&#8217;t keep going on the same trajectory as before it hit the brick. the above lines do just that. Of course, if the missile hit the brick you don&#8217;t want the ball to bounce (Okay, I think there are some issues here &#8211; it may be possible both hit the same brick at the same time, which I am ignoring&#8230;)</p>
<h2>Do we have a winner here?</h2>
<pre class="brush: objc; title: ; notranslate">
#pragma mark Winning Logic
	/*********** You've won **********************/
	if ((kHackHitCount) &amp;&amp; (hack_hit_count&gt;=HACK_HITCOUNT))
	{
		hack_hit_count=0;
		youWin=1;
		NSLog(@&quot;**Hack hitcount reached&quot;);
	}
</pre>
<p>After we&#8217;ve checked all the bricks, time to check for other conditions. This fragment checks if you have &#8220;Hack mode&#8221; enabled. If it is (kHackHitCount is 1) and you&#8217;ve made 4 hits to bricks (we increment hack_hit_count by 1 each time you hit a brick &#8211; see brick collision code) then the flag youWin is set to 1 (which means the level is complete). If you check the brick collision logic earlier, if we detect that there is no brick left with opacity 1, then we also set this flag to 1 (we don&#8217;t count steel bricks as they can&#8217;t be killed)
<pre class="brush: objc; title: ; notranslate">
	if (youWin) // all bricks over
	{
		NSLog(@&quot;Inside youWin&quot;);
		[self resetAlphasforLives:-1 forBricks:0]; // remove all bricks, don't touch lives
		[self playAudio:clapSound];
		if (gameLevel == GAME_LEVELS)
		{
			NSLog(@&quot;*************Inside game over***************&quot;);
			labelGameOver.text = @&quot;You Rock!&quot;;
			labelGameOver.hidden=NO;						 // this will display the Game Over message
			[gameTimer invalidate];	gameTimer=nil;				// kill all timers - game is over
			[backgroundTimer invalidate]; backgroundTimer=nil;
			[harderTimer invalidate]; harderTimer=nil;
			return;
		}
		else {
			NSLog(@&quot;Inside move to next nevel&quot;);
			labelGameOver.text = [NSString stringWithFormat:@&quot;Level %d&quot;, gameLevel+1];
			labelGameOver.hidden=NO;
			[gameTimer invalidate];	gameTimer=nil;
			[backgroundTimer invalidate]; backgroundTimer=nil;
			[harderTimer invalidate]; harderTimer=nil;
			return;
		}
	}
</pre>
<p>So after that check, if youWin is 1, you have won. If there are pending levels, we skip to the next level, else show a game over text. In either case, we disable all timers so the game stops. When the user taps, we either reset the game or move to the next level. You will see this part of the code when we discuss the part of the code that detects user taps.</p>
<h2>Strike?</h2>
<pre class="brush: objc; title: ; notranslate">#pragma mark Paddle hits ball logic

	// Now lets check if the paddle hit the ball

	if (CGRectIntersectsRect(ball.frame, paddle.frame) &amp;&amp; ball.center.y&lt;paddle.center.y)
	{

		[self playAudio:hitSound];
		NSLog(@&quot;HIT&quot;);
		ballSpeed.y = -ballSpeed.y;

		// let's check if the paddle hit the ball on its edge. If so, we want to make sure
		// the ball bounces correctly (example, nudge from left edge of paddle should cause the
		// ball to bounce back up and left, not right. And so forth)

		float edge = ball.center.x-paddle.center.x;
		// if this value is 20 or more, its an edge hit. I found this threshold out
		// by priniting the difference between paddle center and ball center for various hits.
		// Pretty unscientific, I'll admit.
</pre>
<p>The other thing we need to check is if the ball hit the paddle (if it did not, you lose a life. If it did, the ball needs to bounce up back to the bricks  So that&#8217;s what we check here. CGRectIntersectsRect again. Very convenient function, huh?  We also want to spice up the bounce a bit. If the user hits the ball with the edge of the paddle, then we want the ball to bounce differently (if I left nudge I want the ball to go to the left and if its a right nudge it should bounce to the right). To do that, we calculate the distance of the center of the ball from the center of the paddle. If this difference is less, then the ball hit close to the center of the paddle. The larger the distance, that would mean its closer to the edge of the paddle. That&#8217;s the logic here of the edge variable
<pre class="brush: objc; title: ; notranslate">
#pragma mark Edge hit logic
		if (abs(edge)&gt;=20)
		{
			NSLog(@&quot;Edge Hit Detected&quot;);
			int paddleCenterWidth = paddle.frame.size.width/2;
			if (    (paddle.center.x+paddleCenterWidth &lt; self.view.bounds.size.width-10)
				 &amp;&amp; (paddle.center.x - paddleCenterWidth &gt; 10))
			{
				ballSpeed.x = (edge&lt;0)? -kBallSpeedX:kBallSpeedX;
				NSLog(@&quot;Edge skew activated:Ball Speed set to %f&quot;,ballSpeed.x);
			}
		}
		tBallSpeedX = 0; tBallSpeedY =0;
		labelScore.text = [NSString stringWithFormat:@&quot;%d&quot;, score];

	}
</pre>
<p>So if it did hit the edge, we basically change the X direction to point correctly so that the ball moves in the direction of the nudge.</p>
<h2>And then there is the bounce check</h2>
<pre class="brush: objc; title: ; notranslate">
#pragma mark Ball bouncing off screen check

	// now check if the ball is going beyond screen boundaries, if so,
	// bring it back
	if (ball.center.x+ballSpeed.x&gt;self.view.bounds.size.width-4 || ball.center.x+ballSpeed.x-4&lt;0)

	{[self playAudio: boingSound]; ballSpeed.x = -ballSpeed.x; tBallSpeedX=0; tBallSpeedY=0;}
	if (ball.center.y+ballSpeed.y-4 &gt;self.view.bounds.size.height || ball.center.y+ballSpeed.y-4 &lt;0)
		{ballSpeed.y = -ballSpeed.y;[self playAudio: boingSound]; tBallSpeedX=0; tBallSpeedY=0;}

	int x,y;
	x= ball.center.x+ballSpeed.x+tBallSpeedX;
	y = ball.center.y+ballSpeed.y+tBallSpeedY;
	if (x&lt;0) { x = 0;}
	if (y&lt;0) { y = 0;}
	// catchall
	if (x&gt;self.view.bounds.size.width-4) { x=self.view.bounds.size.width-4;}
	if (y&gt;self.view.bounds.size.height-4) { y=self.view.bounds.size.height-4;}
	ball.center = CGPointMake(x, y);
</pre>
<p>The next thing to check is if the ball has hit any of the boundaries. self.view.bounds.size.(width or height) are convenient ways to access the width and height of the current view (which in our case is the full screen). Its better to use this than to hard code values 320 and 480, for example. The code above is quite simple &#8211; if the ball has hit the edge of the screen, change X or Y of the ball to bounce off.</p>
<h2>Miss!</h2>
<p>And then, we finally need to check if we missed the ball. If we missed the ball, then you need to:  a) reduce lives  b) take of a life paddle display on the top left  c) We also want to add a cute rotation to the life that is being taken away (you will see the life paddle do a quick spin to death)  d) And if that was your last life, game gets over
<pre class="brush: objc; title: ; notranslate">
#pragma mark Paddle missing the ball logic
	// When you miss the ball, we want the ball to fall off the screen, not just disappear immediately
	// when your paddle misses. So we set this youmissed flag to 1 when the paddle misses and the ball keeps going down
	// till it reaches the edge of the screen. When it does, we decrease the score, kill a life and play sound
	static int youmissed=0;
	if ((ball.center.y &gt; paddle.center.y) &amp;&amp; (youmissed==0))
	{
		youmissed=1;
		labelScore.text = [NSString stringWithFormat:@&quot;%d&quot;, score];

	}
</pre>
<p>One more thing. When you miss, we want the ball to go all the way to the end of the screen. So when we detect the miss, we set a flag (youmissed=1). Then when the ball falls of the screen with youmissed set to 1, that is when we do all the stuff we need to do when you miss.
<pre class="brush: objc; title: ; notranslate">
if (ball.center.y &gt;= self.view.bounds.size.height-4) // have we run off screen?
	{
		score -= 10;
		labelScore.text = [NSString stringWithFormat:@&quot;%d&quot;, score];
		--livesleft;

		// if you lose a life, lets rotate the life icon around and then make it disappear
		[UIView beginAnimations:nil context:nil];
		[UIView setAnimationDuration:0.2];
		[UIView setAnimationCurve:UIViewAnimationCurveLinear];
		[UIView setAnimationDelegate:self];
		[UIView setAnimationDidStopSelector:@selector(lifeDeathAnimeDidStop)];
		CGAffineTransform transform1 = CGAffineTransformMakeScale(1,1);
		CGAffineTransform transform2 = CGAffineTransformMakeRotation(179.9 * M_PI /180.0);
		lives[livesleft].transform = CGAffineTransformIdentity;
		lives[livesleft].transform = CGAffineTransformConcat(transform1, transform2);
		[UIView commitAnimations];

		// After you die, set ball back to center
		ball.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2+30);
		// and make sure the ball goes down
		ballSpeed.y = kBallSpeedY;
		[self playAudio:missSound];
		youmissed=0;
		kGamePause = 1; // lets freeze the game till he taps
		labelPause.hidden = NO;
</pre>
<p>And then here we check if the ball&#8217;s Y co-ordinate reached the bottom of the screen. If it did, then we need to lose a life. If you notice, we don&#8217;t just remove the life icon. We want to rotate it out. So we use CGAffineTransform. Basically, the way this Animation works is that you start an &#8216;animation block&#8217; by saying &#8216;beginAnimations&#8217; and then after that statement, specify the positions of your UIView objects. You specify the start and the stop by simply specifying the same property twice (odd, I know). For example, here I say, first set lives[livesleft].transform to &#8220;no transformation&#8221; (thats whatCGAffineTransformIdentity means). Immediately after that I say set lives[livesleft].transform to a combination of scaling it and rotating it (CGAffineTransformConcat). Then when I say commitAnimation, IOS takes care of transitioning from the first setting to the second setting based on rules you specify. Where are the rules? Its the lines that say
<pre class="brush: objc; title: ; notranslate">
[UIView beginAnimations:nil context:nil];
		[UIView setAnimationDuration:0.2];
		[UIView setAnimationCurve:UIViewAnimationCurveLinear];
</pre>
<p>Which basically says Animate from start to end in 0.2 seconds and do the animation in constant speed (thats what Linear means)  And boom. There you have it. The lives paddle smoothly disappears in rotating bliss&#8230;.. (I am not using the scale property &#8211; I first thought I will scale and rotate &#8211; it looked crappy so I reset scale to 1 &#8211; which means original size)  Finally, after you kill a life with the fantastic animation above, you reset the ball to the center and pause the game so that we wait for input before we go on (give the user time to reset his hands). But where is the pause? We are just setting a flag. Well, if you recall, we exit the playGame callback if the pause flag is on. That effectively pauses the game, as all animation and game detection logic freezes.</p>
<h2>Tap strategy</h2>
<p>Lets briefly discuss what we use taps for in our game:  a) When the game is paused, a tap will bring it out of pause mode  b) When you tap and drag your finger on the screen, the paddle needs to move to where your finger is  c) When you double tap your paddle, you will shoot a missile (if you have a missile)  d) And finally, we have a bunch of controls at the bottom of the screen that you can tap to enable. They are: 1) Volume on off 2) Help screen 3) Triple tap on the lower left to enable &#8216;hack mode&#8217; we talked about earlier.  So we basically need to multiplex all these functions into our touch detection function
<pre class="brush: objc; title: ; notranslate">
/=============================================================================
// used to detect any touches on the screen and trigger different operations

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	// I am not forcing you to touch the paddle. You can touch and drag anywhere to move the paddle
	// example, its easier to drag below the paddle that way you see the paddle as well
	UITouch *mytouch = [[event allTouches] anyObject];
</pre>
<p>This part returns the coordinates of the touch location in the variable mytouch. Great, now we can use that location to detect everything we need
<pre class="brush: objc; title: ; notranslate">
	touch = paddle.center.x - [mytouch locationInView:mytouch.view].x;
	NSArray *allTouches = [touches allObjects];

	// Did you tap on the info view ?
	if (CGRectContainsPoint(infoView.frame, [[allTouches objectAtIndex:0] locationInView:self.view]))
	{
		if (helpView.hidden=YES)
		{

			helpView.hidden=NO;
			[self.view bringSubviewToFront:helpView];

			kGamePause=1; // pause the game when you show help
			return;
		}

	}
</pre>
<p>Here we use CGRectContainsPoint to detect if our touch point falls inside the info icon. If it does, then we need to show the help screen.
<pre class="brush: objc; title: ; notranslate">
// did you tap on the help screen after it was displayed?
	if ((CGRectContainsPoint(helpView.frame, [[allTouches objectAtIndex:0] locationInView:self.view]) &amp;&amp;(helpView.hidden==NO)))
	{
		helpView.hidden=YES;
		return;
	}
</pre>
<p>And then if we tap the help screen after it is displayed, we need to get back to the game (so all we do is hide the help screen).
<pre class="brush: objc; title: ; notranslate">
// did you tap on the volume icon?
	if (CGRectContainsPoint(volumeView.frame, [[allTouches objectAtIndex:0] locationInView:self.view]))
	{
		NSLog(@&quot;Volume tapped&quot;);
		kVolumeIsOn ^=1;
		// toggle the volume image and status on and off with each tap
		if (kVolumeIsOn)
		{
			[volumeView setImage:[UIImage imageNamed: @&quot;volumeon.png&quot;]];
		}
		else {
			[volumeView setImage:[UIImage imageNamed: @&quot;volumeoff.png&quot;]];
		}
		return;

	}
</pre>
<p>Same logic, but for the volume icon. Also, we toggle between a volumeon and volumeoff image as we tap on the volume icon.
<pre class="brush: objc; title: ; notranslate">
if (labelGameOver.hidden == NO) // game was over so restart if user touches anywhere
	{

		if ((gameLevel == GAME_LEVELS) || (livesleft == 0) )
		// game is over, so restart from level 1
		{
			NSLog(@&quot;After touch: Game is over, reset&quot;);
			labelGameOver.hidden = YES;
			// reset all parameters of the game and lets go again
			[self resetAlphasforLives:1 forBricks:-1];
			[self resetGame];
			ball.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2+30);
			// make the ball go down
			if (ballSpeed.y &lt; 0) ballSpeed.y = -ballSpeed.y;
			labelScore.text = [NSString stringWithFormat:@&quot;%d&quot;, score];

		// we need to restart the timers, because we killed them when the game got over
		//[self initTimer];
		}
</pre>
<p>Then, if in the gamelogic we display &#8220;GameOver&#8221; (that&#8217;s what labelGameOver.hidden==NO means), then it means after a tap, we need to reset the game and go back to level 1. That&#8217;s what we are doing here.
<pre class="brush: objc; title: ; notranslate">
	else // go to next level
		{
			NSLog(@&quot;inside touchesBegan:next level&quot;);
			gameLevel++;
			[backgroundImageView setImage:[UIImage imageNamed: backgroundArray[gameLevel-1]]];
			labelCurrentLevel.text = [NSString stringWithFormat:@&quot;%d&quot;,gameLevel];
			labelGameOver.hidden=YES;
			ball.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2+30);
			[self initTimer];
			[self remapBricks];
		}
	}
</pre>
<p>Otherwise, it means the tap will take us to the next level (the game paused after you finished the level and you need to go to the next level)
<pre class="brush: objc; title: ; notranslate">
if (kGamePause) // if so, then I need to resume with touch
	{
		[harderTimer invalidate]; // if you paused, don't keep the timer for making it harder alive.
		kGamePause = 0;
		labelPause.hidden=YES;
		[self.view bringSubviewToFront:helpView];
		harderTimer = [NSTimer scheduledTimerWithTimeInterval:kMakeItHarder target:self selector:@selector(makeItHarder:) userInfo:nil repeats:YES];

	}
</pre>
<p>And here, we check if the game was paused. IF it was, we just hide the pause text and let the game continue after the tap. The other thing we do is reset the harderTimer. Why? Because if the timer makes the game harder after 60 seconds and you paused in between for 45 seconds, we don&#8217;t want the difficulty to go up in 15 seconds of game play. So to keep it simple, we just reset the count.
<pre class="brush: objc; title: ; notranslate">
else
	{
		// double tapping shoots a missile
		if ([mytouch tapCount] == 2)
		{
			NSLog(@&quot;Tap Twice - Missile Launch&quot;);
			[self launchMissile];
		}

		// triple tapping in the lower left part of the screen toggles 'hack mode'
		else if (([mytouch tapCount]==3) &amp;&amp;
				 (CGRectContainsPoint(hackView.frame, [[allTouches objectAtIndex:0] locationInView:self.view])))
		{
			NSLog(@&quot;Tap thrice - HACK MODE!!&quot;);
			kHackHitCount ^=1;
			if (kHackHitCount) {hackView.hidden=NO;} else {hackView.hidden=YES;}

		} // tapcount=3

	} // not paused

}
</pre>
<p>Finally, here we detect the double and triple taps. tapCount returns the # of taps. two taps means missile lauch and  3 taps enables hack mode</p>
<h2>That was touch, how about drag?</h2>
<pre class="brush: objc; title: ; notranslate">
// this is called when I drag my finger after first touching the screen
// this will move the paddle
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
	UITouch *mytouch = [[event allTouches] anyObject];
	float distance = ([mytouch locationInView:mytouch.view].x + touch) - paddle.center.x;
	float newx = paddle.center.x + distance;

	// we want to make sure the paddle is not dragged off screen, so limit its movement to a point
	// where the full paddle is visible when dragged
	int paddleCenterWidth = paddle.frame.size.width/2;
	if (newx &lt; paddleCenterWidth) {newx=paddleCenterWidth;}
	if (newx &gt; self.view.bounds.size.width-paddleCenterWidth) {newx=self.view.bounds.size.width-paddleCenterWidth;}
	paddle.center = CGPointMake(newx, paddle.center.y);
}
</pre>
<p>There you go. touchesMoved is called when you drag your finger across. the logic here is as you drag, we get the location of your finger and set the paddle there. This is relative to where you first touched (that location is recorded in the previous function).</p>
<h2>There has to be an Accelerometer too</h2>
<pre class="brush: objc; title: ; notranslate">

// Another way to move the paddle. Just rotate the phone...
- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)accel
{
	float newPaddleX= paddle.center.x + (accel.x *12);
	int paddleCenterWidth = paddle.frame.size.width/2;
	if (newPaddleX &gt; paddleCenterWidth &amp;&amp; newPaddleX &lt; self.view.bounds.size.width-paddleCenterWidth)
		paddle.center=CGPointMake(newPaddleX, paddle.center.y);
}
</pre>
<p>Remember when we said in the .h file that we implement the accelerometer protocol as well? This API is called when the accelerometer detects movement. The paddle moves as you  tilt the phone. This is really just to show off. For a game like bricks, the accelerometer based control is horrid. IF you are lying down and trying to play, the paddle keeps tilting away as well. But hey, it has sex appeal. Honestly, I&#8217;d disable this.</p>
<h1>And now what you really want: The project and the source</h1>
<p><span style="color: #0000ff;">Grab it <a href="http://blog.roychowdhury.org/downloads/Bricks_source_Oct272010.zip">HERE</a>.</span> <span style="color: #0000ff;"> </span> To the best of my knowledge all WAV files included have a public domain license and I can include it. If not, do let me know and I&#8217;ll be happy to remove it. All images are from openclipart as I said before. I&#8217;ve removed background.mp3 which plays the backround image. You can put in your own mp3 there and call it background.mp3</p>
<h1>Where to next?</h1>
<p>I plan to add network gaming and network scoring. And upload to the appstore. How much will it take to make a million on appstore if I put it at $0.99? Hmm about 1.4 million purchases. Crud!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.roychowdhury.org/2010/10/27/tutorial-iphone-game-programming-professional-bricks-part-iii/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Tutorial: iPhone Game Programming- professional Bricks (Part II)</title>
		<link>http://blog.roychowdhury.org/2010/10/26/tutorial-iphone-game-programming-professional-bricks-part-ii/</link>
		<comments>http://blog.roychowdhury.org/2010/10/26/tutorial-iphone-game-programming-professional-bricks-part-ii/#comments</comments>
		<pubDate>Tue, 26 Oct 2010 20:12:40 +0000</pubDate>
		<dc:creator>Arjun</dc:creator>
				<category><![CDATA[Arjun Roychowdhury]]></category>
		<category><![CDATA[Gaming]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[world 2.0]]></category>
		<category><![CDATA[bricks]]></category>
		<category><![CDATA[coreanimation]]></category>
		<category><![CDATA[game tutorial]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[quartz2D]]></category>
		<category><![CDATA[uikit]]></category>

		<guid isPermaLink="false">http://blog.roychowdhury.org/?p=413</guid>
		<description><![CDATA[Click here for Part I Click here for Part III In Part I, we discussed the approach to implement a professional looking Bricks game for the iphone. We also described the basic design approach and broke down the header file in detail so you get an idea of how things will be. This part will now discuss the implementation. Before we do that, here is the video again of what we are implementing. As I wrote earlier, this being a pretty small game, the entire logic is stuff into BricksViewController.m. Let&#8217;s first take a look at it in totality and then I&#8217;ll proceed to break it up. Click on the &#8220;show source&#8221; box below to expand it. Breaking up the implementation in parts Declare, property and synthesize dance What you basically see here is a whole bunch of @synthesize statements, the goal of which is to automatically have xcode generate the required accessor functions that allow us developers to read and write settings via accessor functions. Things to do when the game loads Let&#8217;s discuss what we are doing here &#8211; its pretty straightforward &#8211; this function is called when the game first loads (only once, remember that). First off,<a href="http://blog.roychowdhury.org/2010/10/26/tutorial-iphone-game-programming-professional-bricks-part-ii/"> <br /><br /> (Read More...)</a>]]></description>
			<content:encoded><![CDATA[<p><span style="color: #ff0000;"><span style="color: #888888;">Click here for <a href="http://blog.roychowdhury.org/2010/10/25/tutorial-iphone-game-programming-professional-bricks-part-i/">Part I</a></span></span></p>
<p><span style="color: #ff0000;"><span style="color: #888888;">Click here for <a href="http://blog.roychowdhury.org/2010/10/27/tutorial-iphone-game-programming-professional-bricks-part-iii/">Part III</a></span></span></p>
<p>In <a href="http://blog.roychowdhury.org/2010/10/25/tutorial-iphone-game-programming-professional-bricks-part-i/">Part I</a>, we discussed the approach to implement a professional looking Bricks game for the iphone. We also described the basic design approach and broke down the header file in detail so you get an idea of how things will be. This part will now discuss the implementation.  Before we do that, here is the video again of what we are implementing.</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="480" height="385" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/YpK0OmGjiIE?fs=1&amp;hl=en_US&amp;rel=0" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="480" height="385" src="http://www.youtube.com/v/YpK0OmGjiIE?fs=1&amp;hl=en_US&amp;rel=0" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<p>As I wrote earlier, this being a pretty small game, the entire logic is stuff into BricksViewController.m.  Let&#8217;s first take a look at it in totality and then I&#8217;ll proceed to break it up. Click on the &#8220;show source&#8221; box below to expand it.<span id="more-413"></span></p>
<pre class="brush: objc; collapse: true; light: false; title: ; toolbar: true; notranslate">

//
//  BricksViewController.m
//  Bricks
//
//  Created by Arjun on 10/15/10.
//  All rights reserved.
//

#import &quot;BricksViewController.h&quot;
#import &quot;GBMusicTrack.h&quot;

@implementation BricksViewController

@synthesize ball;
@synthesize paddle;
@synthesize cloud;
@synthesize labelScore;
@synthesize labelCurrentLevel;
@synthesize labelPause;
@synthesize labelGameOver;
@synthesize explodeView;
@synthesize backgroundImageView;
@synthesize missileView;
@synthesize haveMissileView;
@synthesize hackView;
@synthesize volumeView;
@synthesize infoView;
@synthesize helpView;
@synthesize hitSound;
@synthesize missSound;
@synthesize explodeSound;
@synthesize clapSound;
@synthesize boingSound;
@synthesize booSound;
@synthesize holycowSound;
@synthesize metalSound;
@synthesize gotlifeSound;
@synthesize missileSound;
@synthesize gameTimer;
@synthesize backgroundTimer;
@synthesize harderTimer;
@synthesize rainDrops;

//=============================================================================
- (void)viewDidLoad {

	NSLog(@&quot;Inside ViewDidLoad&quot;);
	[super viewDidLoad];

	//************************
	kHackHitCount=0;				// 1=skip levels quickly. 0=normal play
	//************************

	kBallSpeedX = 4;
	kBallSpeedY = 4;
	tBallSpeedX = 0;
	tBallSpeedY = 0;
	kMakeItHarder = 10;				// Time in seconds to make things harder in the game
	kGamePause = 1;
	gameTimer = nil;
	backgroundTimer = nil;
	harderTimer = nil;
	gameLevel =1;
	kMissileFiring=0;
	kMissilesLeft=0;
	kVolumeIsOn=1;
	kMakeItHarder = 60;				// Time in seconds to make things harder in the game

	backgroundArray[0]=@&quot;level1.png&quot;;
	backgroundArray[1]=@&quot;level2.png&quot;;
	backgroundArray[2]=@&quot;level3.png&quot;;
	backgroundArray[3]=@&quot;level4.png&quot;;
	[backgroundImageView setImage:[UIImage imageNamed: backgroundArray[gameLevel-1]]];

	// set up the accelerometer - I want to use it to move my paddle
	UIAccelerometer *myAccel = [UIAccelerometer sharedAccelerometer];
	myAccel.updateInterval = 1.0f/30.0f;
	myAccel.delegate=self;

	ballSpeed = CGPointMake(kBallSpeedX,kBallSpeedY);
	score = 0;
	livesleft = LIVES;

	// Initialize all the audio streams that we will be playing

	UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
	AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,
							 sizeof (sessionCategory),
							 &amp;sessionCategory);

	[self initAudioStreams:&amp;hitSound :@&quot;hitme&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;booSound :@&quot;boo&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;missSound :@&quot;die&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;clapSound :@&quot;applause&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;explodeSound :@&quot;explode&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;boingSound :@&quot;boing&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;holycowSound :@&quot;holycow&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;metalSound :@&quot;metalsound&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;gotlifeSound :@&quot;gotlife&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;missileSound :@&quot;missile&quot; :@&quot;wav&quot;];

	// I am blindly using GBMusicTrack for now based on their instructions...
	song = [[GBMusicTrack alloc] initWithPath:[[NSBundle mainBundle] pathForResource:@&quot;background&quot; ofType:@&quot;mp3&quot;]];
	//[song setRepeat:YES];
	//[song play];

	[self initBricks];		// fill in and display all the bricks
	[self initLives];
	[self initExplosion];	// pre-load explosion array
	[self initRain];		// pre-load rain array
	[self initTimer];		// start game timers and we are on our way!

	UIImage *image = [UIImage imageNamed:@&quot;missile.png&quot;];
	missileView = [[[UIImageView alloc] initWithImage:image] autorelease];
	missileView.hidden=YES;		// load the missile image, hide it for now
	[self.view addSubview:missileView];

	ball.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2+30);

}

//=============================================================================
// play sounds only if volume is not muted
-(void) playAudio: (SystemSoundID) soundId
{
	if (kVolumeIsOn) {AudioServicesPlaySystemSound(soundId);}
}
//=============================================================================
// convenience function. Pass it a reference to the SystemSoundID handle, the file and its type and it
// creates an audio stream ready to play
- (void) initAudioStreams: (SystemSoundID *)soundId :(NSString *)soundFile  :(NSString *) type
{
	NSString *audioPath=[[NSBundle mainBundle] pathForResource:soundFile ofType:type];
	CFURLRef audioURL = (CFURLRef) [NSURL fileURLWithPath:audioPath];
	AudioServicesCreateSystemSoundID(audioURL, soundId);
}

//=============================================================================
// pre-load the explosion effect into an array.
- (void) initExplosion
{
	explodeImages = [[NSMutableArray alloc] initWithCapacity: 34];
	for (int i = 1; i &lt;= 34; i++)
	{
		NSString *imageName = [NSString stringWithFormat:@&quot;boom%d.png&quot;,i];
		UIImage *image = [UIImage imageNamed:imageName ];
		[explodeImages addObject: image];
	}
}

//=============================================================================
// load bricks layout. This array controls what sort of bricks show at each
// cell of the brick matrix

- (void) initBrickLayout
{
	NSLog(@&quot;init brick layout&quot;);
	NSLog(@&quot;Current Game Level is %d&quot;,gameLevel);

	// You can modify these arrays to respresent the bricks
	// as you want for each level. Each block is for a particular level.
	// 0 = no brick at this cell
	// 1 = normal brick - you hit it, it explodes and you add to your score
	// 2 = metal brick - you can't kill it - the ball will hit and bounce off faster
	// 3 = super brick - you hit it, it explodes and you will get a new life (if you are not at max)
	// 4 = missile brick - you get 5 missiles each time you hit this one

	int bricklevel[GAME_LEVELS][BRICKS_ROWS][BRICKS_COLUMNS] = {
	{
			// level 1
			{2,0,0,1,0,0,2},
			{0,0,1,1,1,0,0},
			{0,1,4,0,4,1,0},
			{1,1,3,0,3,1,1},
			{1,1,1,0,1,1,1},
			{0,1,3,0,3,1,0},
			{0,0,4,1,4,0,0},
			{2,0,0,1,0,0,2},
	},
	{
			// level 2
			{3,2,1,1,1,2,3},
			{1,1,1,1,1,1,1},
			{2,1,1,1,1,1,2},
			{1,1,1,1,1,1,1},
			{1,1,2,3,2,1,1},
			{4,1,1,2,1,1,4},
			{1,2,1,1,1,2,1},
			{2,1,1,1,1,1,2},
	},
	{

			// level 3
			{0,0,0,3,0,0,0},
			{0,0,1,1,1,0,0},
			{0,0,1,1,1,0,0},
			{0,2,1,1,1,2,0},
			{0,1,1,1,1,1,0},
			{2,1,1,1,1,1,2},
			{1,4,1,1,1,4,1},
			{1,1,2,1,2,1,1},
	},
	{
			// level 4
			{0,1,0,3,0,1,0},
			{2,1,1,1,1,4,2},
			{0,1,1,1,1,1,0},
			{0,0,1,1,1,0,0},
			{0,0,1,1,1,0,0},
			{0,1,1,1,1,1,0},
			{2,4,1,3,1,1,2},
			{1,0,1,0,1,0,1},
	},
	};

	NSLog (@&quot;Copying level %d(-1) to bricks description&quot;, gameLevel);
	memcpy (brick_description, bricklevel[gameLevel-1], sizeof(brick_description)); // C still rocks. W00t :-)
}

//=============================================================================
// init rain array
- (void) initRain
{
	NSLog(@&quot;Inside initRain&quot;);
	NSMutableArray *array = [[NSMutableArray alloc] init];
	self.rainDrops = array;
	[array release];

	UIImage *rainImage = [UIImage imageNamed:@&quot;raindrop.png&quot;];
    UIImageView *rainView;

	// randomly place 50 rain drops across the screen
    for (int i = 0; i&lt; 50; i++)
	{
        rainView= [[UIImageView alloc] initWithImage:rainImage];
		rainView.alpha=0.3;
		rainView.hidden=YES;

        int x = arc4random()% (int)self.view.bounds.size.width;
        int y = arc4random()% (int)self.view.bounds.size.height;
        rainView.center = CGPointMake (x,y);

		// the background image is at index 0, make rain at 1,
		// so it is behind the bricks
        [self.view insertSubview:rainView atIndex:1];
        [self.rainDrops addObject: rainView];
        [rainView release];
	}
}

// we need to hide the rain for layers that don't have rain
- (void) hideRain
{
	for (UIImageView *rain in rainDrops)
	{
		rain.hidden=YES;
	}
}

// animate the rain across the screen
-(void)moveRain{

	for (UIImageView *rain in rainDrops) {

		CGPoint newCenter = rain.center;
		newCenter.y = newCenter.y +2;
		newCenter.x = newCenter.x +1;
		rain.hidden = NO;

		if (newCenter.y &gt; self.view.bounds.size.height){
			newCenter.y=0;
			newCenter.x = arc4random()%(int)self.view.bounds.size.width;
		}
		if (newCenter.x &gt; self.view.bounds.size.width){
			newCenter.x =0;
		} else if (newCenter.x &lt; 0) {
			newCenter.x = self.view.bounds.size.width;
		}

		rain.center = newCenter;

	}
}

//=============================================================================
// launches a missile
// you would think we can use Core Graphics animate to automatically do this
// but we can't as we also need to detect if it hit a brick with CGRectIntersect
// The automatic animation does not allow for detection if intersects, so we need
// to do it ourselves, or, use auto animation in small steps.

- (void) launchMissile;
{
	if (!kMissilesLeft) {NSLog(@&quot;You don't have missiles&quot;);return;}
	if (kMissileFiring) {return;} // only allow 1 missile at a time
	haveMissileView.hidden=NO;
	kMissileFiring=1;

	missileView.hidden=NO;
	[self playAudio:missileSound];
	missileView.center=CGPointMake(paddle.center.x, paddle.center.y-10);
	kMissilesLeft--;
	if (!kMissilesLeft) {haveMissileView.hidden=YES;}

	NSLog(@&quot;You have %d missiles left&quot;,kMissilesLeft);
}

-(void) missileFinished
{
	missileView.hidden=YES;
	kMissileFiring=0;
}

//=============================================================================
// load the bricks images and create the bricks matrix. Also create the lives display
- (void) initBricks
{
	NSLog(@&quot;Inside initBricks&quot;);

	brickImages[0]=@&quot;brick2.png&quot;; //normal
	brickImages[1]=@&quot;brick2.png&quot;;
	brickImages[2]=@&quot;steel.png&quot;;  // cant destroy
	brickImages[3]=@&quot;brick3.png&quot;; // special powers - life
	brickImages[4]=@&quot;brick1.png&quot;; // special powers - missiles

	[self initBrickLayout];

	for (int rows=0; rows self.view.bounds.size.width+80) {newposx=-64;}	// wrap it around
		cloud.center = CGPointMake(newposx, cloud.center.y);
	}
	else
	{
		cloud.hidden=YES;
		[self moveRain];
	}

	if (kMissileFiring)
	{

		int missileY;
		missileY=missileView.center.y-10;
		if (missileY&lt;0)
		{
			[self missileFinished];
		}

		else
		{
			missileView.center=CGPointMake(missileView.center.x, missileY);
		}

	} // kMissileFiring
}

//=============================================================================
// resets game back to normal.
-(void) resetGame
{
	NSLog(@&quot;Inside reset Game&quot;);
	score = 0;
	livesleft = LIVES;
	kBallSpeedX = 4;
	kBallSpeedY = 4;
	ballSpeed = CGPointMake(kBallSpeedX,kBallSpeedY);
	gameLevel = 1;
	labelCurrentLevel.text = [NSString stringWithFormat:@&quot;%d&quot;,gameLevel];
	labelScore.text = [NSString stringWithFormat:@&quot;%d&quot;, score];
	kMissileFiring=0;
	kMissilesLeft=0;
	haveMissileView.hidden=YES;

	for (UIImageView *rain in rainDrops) { rain.hidden = YES; }
	[backgroundImageView setImage:[UIImage imageNamed: backgroundArray[gameLevel-1]]];

	NSLog(@&quot;Calling initBricks with level:%d&quot;,gameLevel);
	[self remapBricks];
	[self initTimer];

	kGamePause=1;
	ball.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2+30);
	NSLog(@&quot;*****GAME RESET***********&quot;);

}

//=============================================================================
// This is the heart of the game. Checks for collisions, hits, misses etc. Can be cleaned up better
- (void) playGame:(NSTimer *)timer
{
	static int hack_hit_count = 0;
	if (kGamePause) {return;}

	//First Check for brick collision
	// basically, we iterate through the array of bricks
	// and compare if the ball location intersects with any of the bricks location
	// From a display perspective, we are not really deleting the brick. We are simply making its alpha (transparency)
	// to 0 so it looks like its gone. Therefore, when we check if the ball has hit a brick, we also need to check if
	// the brick is not transparent. If it is, its been hit before.

#pragma mark Brick Collision logic

	int youWin=1;	   // if this is 0, then there is atleast one brick that has not been hit. If 1, all bricks
					   // have been hit.
	for (int y=0; y=NORMAL_BRICK))
			{
				if (brick_description[y][x] !=METAL_BRICK) {youWin=0;}

				 if (ballHitBrick || (missileHitBrick) &amp;&amp; (missileView.hidden==NO))
				 {

					// Coming here means that the ball has hit a brick that has not been hit before
					 // or, the missile hit a brick

					if ((brick_description[y][x]==NORMAL_BRICK) || (brick_description[y][x]&gt;=SUPER_BRICKS))
					{
						NSLog(@&quot;YOU HIT:%d:%d&quot;,y,x);
						if (kHackHitCount) {hack_hit_count++;}
						//NSLog (@&quot;HACK HIT COUNT %d &amp; kHack:%d&quot;, hack_hit_count, kHackHitCount);
						score += 10;
						labelScore.text = [NSString stringWithFormat:@&quot;%d&quot;, score];

						if (missileHitBrick)
						{
							NSLog(@&quot;MISSILE HIT&quot;);
							missileView.hidden=YES; // after a hit, hide the missile
							kMissileFiring=0;	// allow other missiles to be fired
						}

						[self playAudio:explodeSound];
						[self explodeBrick :y :x];

						bricks[y][x].alpha -= 0.1; // reduce alpha right away by a pt.
												  // just in case you hit it again before anim begins....
						[UIView beginAnimations:@&quot;fadebrick&quot; context:nil];
						[UIView setAnimationCurve:UIViewAnimationCurveLinear];
						[UIView setAnimationDuration:0.8];
						[UIView setAnimationDelegate:self];
						bricks[y][x].alpha=0;
						[UIView commitAnimations]; // fade out killed brick

						if (brick_description[y][x]==LIFE_BRICK) // this means you get a life
						{

							if (livesleft0) &amp;&amp; (ballSpeed.y&gt;0)) { ballSpeed.y = -ballSpeed.y;}
						else if ((ballSpeed.x&gt;0) &amp;&amp; (ballSpeed.y&lt;0)) { ballSpeed.y = -ballSpeed.y;}
						else if ((ballSpeed.x&lt;0) &amp;&amp; (ballSpeed.y&gt;0)) { ballSpeed.x = -ballSpeed.x;}
						else if ((ballSpeed.x&lt;0) &amp;&amp; (ballSpeed.y&lt;0)) { ballSpeed.y = -ballSpeed.y;}

						if (ballSpeed.x &lt;0) tBallSpeedX = -tBallSpeedX;
						if (ballSpeed.y &lt;0) tBallSpeedY = -tBallSpeedY;
					}

				} // CGRectIntersect
			} // if you hit a solid brick
		} //x
	} //y

#pragma mark Winning Logic
	/*********** You've won **********************/
	if ((kHackHitCount) &amp;&amp; (hack_hit_count&gt;=HACK_HITCOUNT))
	{
		hack_hit_count=0;
		youWin=1;
		NSLog(@&quot;**Hack hitcount reached&quot;);
	}
	if (youWin) // all bricks over
	{
		NSLog(@&quot;Inside youWin&quot;);
		[self resetAlphasforLives:-1 forBricks:0]; // remove all bricks, don't touch lives
		[self playAudio:clapSound];
		if (gameLevel == GAME_LEVELS)
		{
			NSLog(@&quot;*************Inside game over***************&quot;);
			labelGameOver.text = @&quot;You Rock!&quot;;
			labelGameOver.hidden=NO;						 // this will display the Game Over message
			[gameTimer invalidate];	gameTimer=nil;				// kill all timers - game is over
			[backgroundTimer invalidate]; backgroundTimer=nil;
			[harderTimer invalidate]; harderTimer=nil;
			return;
		}
		else {
			NSLog(@&quot;Inside move to next nevel&quot;);
			labelGameOver.text = [NSString stringWithFormat:@&quot;Level %d&quot;, gameLevel+1];
			labelGameOver.hidden=NO;
			[gameTimer invalidate];	gameTimer=nil;
			[backgroundTimer invalidate]; backgroundTimer=nil;
			[harderTimer invalidate]; harderTimer=nil;
			return;
		}
	}

#pragma mark Paddle hits ball logic

	// Now lets check if the paddle hit the ball

	if (CGRectIntersectsRect(ball.frame, paddle.frame) &amp;&amp; ball.center.y=20)
		{
			NSLog(@&quot;Edge Hit Detected&quot;);
			int paddleCenterWidth = paddle.frame.size.width/2;
			if (    (paddle.center.x+paddleCenterWidth &lt; self.view.bounds.size.width-10)
				 &amp;&amp; (paddle.center.x - paddleCenterWidth &gt; 10))
			{
				ballSpeed.x = (edge&lt;0)? -kBallSpeedX:kBallSpeedX;
				NSLog(@&quot;Edge skew activated:Ball Speed set to %f&quot;,ballSpeed.x);
			}
		}
		tBallSpeedX = 0; tBallSpeedY =0;
		labelScore.text = [NSString stringWithFormat:@&quot;%d&quot;, score];

	}

#pragma mark Ball bouncing off screen check

	// now check if the ball is going beyond screen boundaries, if so,
	// bring it back
	if (ball.center.x+ballSpeed.x&gt;self.view.bounds.size.width-4 || ball.center.x+ballSpeed.x-4&lt;0)

	{[self playAudio: boingSound]; ballSpeed.x = -ballSpeed.x; tBallSpeedX=0; tBallSpeedY=0;}
	if (ball.center.y+ballSpeed.y-4 &gt;self.view.bounds.size.height || ball.center.y+ballSpeed.y-4 &lt;0)
		{ballSpeed.y = -ballSpeed.y;[self playAudio: boingSound]; tBallSpeedX=0; tBallSpeedY=0;}

	int x,y;
	x= ball.center.x+ballSpeed.x+tBallSpeedX;
	y = ball.center.y+ballSpeed.y+tBallSpeedY;
	if (x&lt;0) { x = 0;}
	if (y&lt;0) { y = 0;}
	// catchall
	if (x&gt;self.view.bounds.size.width-4) { x=self.view.bounds.size.width-4;}
	if (y&gt;self.view.bounds.size.height-4) { y=self.view.bounds.size.height-4;}
	ball.center = CGPointMake(x, y);

#pragma mark Paddle missing the ball logic
	// When you miss the ball, we want the ball to fall off the screen, not just disappear immediately
	// when your paddle misses. So we set this youmissed flag to 1 when the paddle misses and the ball keeps going down
	// till it reaches the edge of the screen. When it does, we decrease the score, kill a life and play sound
	static int youmissed=0;
	if ((ball.center.y &gt; paddle.center.y) &amp;&amp; (youmissed==0))
	{
		youmissed=1;
		labelScore.text = [NSString stringWithFormat:@&quot;%d&quot;, score];

	}

	if (ball.center.y &gt;= self.view.bounds.size.height-4) // have we run off screen?
	{
		score -= 10;
		labelScore.text = [NSString stringWithFormat:@&quot;%d&quot;, score];
		--livesleft;

		// if you lose a life, lets rotate the life icon around and then make it disappear
		[UIView beginAnimations:nil context:nil];
		[UIView setAnimationDuration:0.2];
		[UIView setAnimationCurve:UIViewAnimationCurveLinear];
		[UIView setAnimationDelegate:self];
		[UIView setAnimationDidStopSelector:@selector(lifeDeathAnimeDidStop)];
		CGAffineTransform transform1 = CGAffineTransformMakeScale(1,1);
		CGAffineTransform transform2 = CGAffineTransformMakeRotation(179.9 * M_PI /180.0);
		lives[livesleft].transform = CGAffineTransformIdentity;
		lives[livesleft].transform = CGAffineTransformConcat(transform1, transform2);
		[UIView commitAnimations];

		// After you die, set ball back to center
		ball.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2+30);
		// and make sure the ball goes down
		ballSpeed.y = kBallSpeedY;
		[self playAudio:missSound];
		youmissed=0;
		kGamePause = 1; // lets freeze the game till he taps
		labelPause.hidden = NO;

#pragma mark You lost logic
		/*********** You've lost **********************/

		if (livesleft == 0)
		{
			NSLog(@&quot;inside no lives left&quot;);
			// all lives over, so pop the message out and stop timers
			// game is frozen
			labelGameOver.text = @&quot;Bad Luck!&quot;;
			labelGameOver.hidden=NO;
			labelPause.hidden=YES;
			[gameTimer invalidate]; gameTimer = nil;
			[backgroundTimer invalidate]; backgroundTimer = nil;
			[harderTimer invalidate]; harderTimer = nil;

			[self playAudio:booSound];

		} // livesleft

	} // if ball.center.y

} // playgame

// called after death rotation animation completes
- (void)lifeDeathAnimeDidStop{
	if ((livesleft=0)) lives[livesleft].alpha = 0;

}

//=============================================================================
// used to detect any touches on the screen and trigger different operations

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	// I am not forcing you to touch the paddle. You can touch and drag anywhere to move the paddle
	// example, its easier to drag below the paddle that way you see the paddle as well
	UITouch *mytouch = [[event allTouches] anyObject];

	touch = paddle.center.x - [mytouch locationInView:mytouch.view].x;
	NSArray *allTouches = [touches allObjects];

	// Did you tap on the info view ?
	if (CGRectContainsPoint(infoView.frame, [[allTouches objectAtIndex:0] locationInView:self.view]))
	{
		if (helpView.hidden=YES)
		{
			helpView.hidden=NO;
			[self.view bringSubviewToFront:helpView];

			kGamePause=1; // pause the game when you show help
			return;
		}

	}

	// did you tap on the help screen after it was displayed?
	if ((CGRectContainsPoint(helpView.frame, [[allTouches objectAtIndex:0] locationInView:self.view]) &amp;&amp;(helpView.hidden==NO)))
	{
		helpView.hidden=YES;
		return;
	}

	// did you tap on the volume icon?
	if (CGRectContainsPoint(volumeView.frame, [[allTouches objectAtIndex:0] locationInView:self.view]))
	{
		NSLog(@&quot;Volume tapped&quot;);
		kVolumeIsOn ^=1;
		// toggle the volume image and status on and off with each tap
		if (kVolumeIsOn)
		{
			[volumeView setImage:[UIImage imageNamed: @&quot;volumeon.png&quot;]];
		}
		else {
			[volumeView setImage:[UIImage imageNamed: @&quot;volumeoff.png&quot;]];
		}
		return;

	}

	if (labelGameOver.hidden == NO) // game was over so restart if user touches anywhere
	{

		if ((gameLevel == GAME_LEVELS) || (livesleft == 0) )
		// game is over, so restart from level 1
		{
			NSLog(@&quot;After touch: Game is over, reset&quot;);
			labelGameOver.hidden = YES;
			// reset all parameters of the game and lets go again
			[self resetAlphasforLives:1 forBricks:-1];
			[self resetGame];
			ball.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2+30);
			// make the ball go down
			if (ballSpeed.y &lt; 0) ballSpeed.y = -ballSpeed.y;
			labelScore.text = [NSString stringWithFormat:@&quot;%d&quot;, score];

		// we need to restart the timers, because we killed them when the game got over
		//[self initTimer];
		}
		else // go to next level
		{
			NSLog(@&quot;inside touchesBegan:next level&quot;);
			gameLevel++;
			[backgroundImageView setImage:[UIImage imageNamed: backgroundArray[gameLevel-1]]];
			labelCurrentLevel.text = [NSString stringWithFormat:@&quot;%d&quot;,gameLevel];
			labelGameOver.hidden=YES;
			ball.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2+30);
			[self initTimer];
			[self remapBricks];
		}
	}

	if (kGamePause) // if so, then I need to resume with touch
	{
		[harderTimer invalidate]; // if you paused, don't keep the timer for making it harder alive.
		kGamePause = 0;
		labelPause.hidden=YES;
		[self.view bringSubviewToFront:helpView];
		harderTimer = [NSTimer scheduledTimerWithTimeInterval:kMakeItHarder target:self selector:@selector(makeItHarder:) userInfo:nil repeats:YES];

	}
	else
	{
		// double tapping shoots a missile
		if ([mytouch tapCount] == 2)
		{
			NSLog(@&quot;Tap Twice - Missile Launch&quot;);
			[self launchMissile];
		}

		// triple tapping in the lower left part of the screen toggles 'hack mode'
		else if (([mytouch tapCount]==3) &amp;&amp;
				 (CGRectContainsPoint(hackView.frame, [[allTouches objectAtIndex:0] locationInView:self.view])))
		{
			NSLog(@&quot;Tap thrice - HACK MODE!!&quot;);
			kHackHitCount ^=1;
			if (kHackHitCount) {hackView.hidden=NO;} else {hackView.hidden=YES;}

		} // tapcount=3

	} // not paused

}

// this is called when I drag my finger after first touching the screen
// this will move the paddle
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
	UITouch *mytouch = [[event allTouches] anyObject];
	float distance = ([mytouch locationInView:mytouch.view].x + touch) - paddle.center.x;
	float newx = paddle.center.x + distance;

	// we want to make sure the paddle is not dragged off screen, so limit its movement to a point
	// where the full paddle is visible when dragged
	int paddleCenterWidth = paddle.frame.size.width/2;
	if (newx &lt; paddleCenterWidth) {newx=paddleCenterWidth;}
	if (newx &gt; self.view.bounds.size.width-paddleCenterWidth) {newx=self.view.bounds.size.width-paddleCenterWidth;}
	paddle.center = CGPointMake(newx, paddle.center.y);
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

// Another way to move the paddle. Just rotate the phone...
- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)accel
{
	float newPaddleX= paddle.center.x + (accel.x *12);
	int paddleCenterWidth = paddle.frame.size.width/2;
	if (newPaddleX &gt; paddleCenterWidth &amp;&amp; newPaddleX &lt; self.view.bounds.size.width-paddleCenterWidth)
		paddle.center=CGPointMake(newPaddleX, paddle.center.y);
}

// This is called when the ball hits a solid brick. It shows an explosion
-(void) explodeBrick: (int) y : (int) x
{

	NSLog(@&quot;Explosion!!!!!&quot;);

	// Position the explosion so it is properly centered on the brick
	explodeView.center = CGPointMake(bricks[y][x].center.x, bricks[y][x].center.y);
	// bring the explosion view to the front
	[self.view bringSubviewToFront:explodeView];

	explodeView.animationImages = explodeImages;
	explodeView.animationDuration = 1;
	explodeView.animationRepeatCount = 1;
	[explodeView startAnimating];

}

// resets alphas of images of the game. This is just a convenience function
// that I can call from different places to display or hide the lives left and
// the bricks opacity
- (void) resetAlphasforLives:(int) livesVal forBricks:(int) bricksVal
{
	NSLog(@&quot;Inside resetAlphaseforLives&quot;);
	if (bricksVal != -1)
	{
		for (int rows=0; rows&lt;BRICKS_ROWS; rows++)
		{
			for (int columns=0; columns&lt;BRICKS_COLUMNS; columns++)
			{

				CGRect myFrame = bricks[rows][columns].frame;
				//myFrame.size.width=60;
				//myFrame.size.height=16;
				bricks[rows][columns].frame= myFrame;
				bricks[rows][columns].alpha = MIN(bricksVal,brick_description[rows][columns]);

			}
		}
	} //if
	if (livesVal != -1)
	{
		for (int i=0; i&lt;LIVES; i++)
		{
			lives[i].alpha=livesVal;
			lives[i].transform = CGAffineTransformIdentity;
		}
	} //if
}

// called by App delegate when the app is interrupted (home key pressed..)
- (void) saveState
{
	NSLog(@&quot;interrupted&quot;);
	kGamePause=1;
	labelPause.hidden = NO;

}

- (void)viewDidUnload {
}

- (void)dealloc {
	[ball release];
    [paddle release];
	[labelScore release];
	[song release];
	[explodeImages release];
	[rainDrops release];

	AudioServicesDisposeSystemSoundID(hitSound);
	AudioServicesDisposeSystemSoundID(missSound);
	AudioServicesDisposeSystemSoundID(clapSound);
	AudioServicesDisposeSystemSoundID(explodeSound);
	AudioServicesDisposeSystemSoundID(booSound);
	AudioServicesDisposeSystemSoundID(holycowSound);
	AudioServicesDisposeSystemSoundID(boingSound);
	AudioServicesDisposeSystemSoundID(metalSound);
	AudioServicesDisposeSystemSoundID(gotlifeSound);
	AudioServicesDisposeSystemSoundID(missileSound);

	// anything else that I missed?
	[super dealloc];

}

@end
</pre>
<h1>Breaking up the implementation in parts</h1>
<h2>Declare, property and synthesize dance</h2>
<pre class="brush: objc; title: ; notranslate">
#import &quot;BricksViewController.h&quot;
#import &quot;GBMusicTrack.h&quot;

@implementation BricksViewController

@synthesize ball;
@synthesize paddle;
@synthesize cloud;
@synthesize labelScore;
@synthesize labelCurrentLevel;
@synthesize labelPause;
@synthesize labelGameOver;
@synthesize explodeView;
@synthesize backgroundImageView;
@synthesize missileView;
@synthesize haveMissileView;
@synthesize hackView;
@synthesize volumeView;
@synthesize infoView;
@synthesize helpView;
@synthesize hitSound;
@synthesize missSound;
@synthesize explodeSound;
@synthesize clapSound;
@synthesize boingSound;
@synthesize booSound;
@synthesize holycowSound;
@synthesize metalSound;
@synthesize gotlifeSound;
@synthesize missileSound;
@synthesize gameTimer;
@synthesize backgroundTimer;
@synthesize harderTimer;
@synthesize rainDrops;
</pre>
<ol>
<li>What you basically see here is a whole bunch of @synthesize statements, the goal of which is to automatically have xcode generate the required accessor functions that allow us developers to read and write settings via accessor functions.</li>
</ol>
<h2>Things to do when the game loads</h2>
<pre class="brush: objc; title: ; notranslate">

//=============================================================================
- (void)viewDidLoad {

	NSLog(@&quot;Inside ViewDidLoad&quot;);
	[super viewDidLoad];

	//************************
	kHackHitCount=0;				// 1=skip levels quickly. 0=normal play
	//************************

	kBallSpeedX = 4;
	kBallSpeedY = 4;
	tBallSpeedX = 0;
	tBallSpeedY = 0;
	kMakeItHarder = 10;				// Time in seconds to make things harder in the game
	kGamePause = 1;
	gameTimer = nil;
	backgroundTimer = nil;
	harderTimer = nil;
	gameLevel =1;
	kMissileFiring=0;
	kMissilesLeft=0;
	kVolumeIsOn=1;
	kMakeItHarder = 60;				// Time in seconds to make things harder in the game

	backgroundArray[0]=@&quot;level1.png&quot;;
	backgroundArray[1]=@&quot;level2.png&quot;;
	backgroundArray[2]=@&quot;level3.png&quot;;
	backgroundArray[3]=@&quot;level4.png&quot;;
	[backgroundImageView setImage:[UIImage imageNamed: backgroundArray[gameLevel-1]]];

	// set up the accelerometer - I want to use it to move my paddle
	UIAccelerometer *myAccel = [UIAccelerometer sharedAccelerometer];
	myAccel.updateInterval = 1.0f/30.0f;
	myAccel.delegate=self;

	ballSpeed = CGPointMake(kBallSpeedX,kBallSpeedY);
	score = 0;
	livesleft = LIVES;

	// Initialize all the audio streams that we will be playing

	UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
	AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,
							 sizeof (sessionCategory),
							 &amp;sessionCategory);

	[self initAudioStreams:&amp;hitSound :@&quot;hitme&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;booSound :@&quot;boo&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;missSound :@&quot;die&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;clapSound :@&quot;applause&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;explodeSound :@&quot;explode&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;boingSound :@&quot;boing&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;holycowSound :@&quot;holycow&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;metalSound :@&quot;metalsound&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;gotlifeSound :@&quot;gotlife&quot; :@&quot;wav&quot;];
	[self initAudioStreams:&amp;missileSound :@&quot;missile&quot; :@&quot;wav&quot;];

	// I am blindly using GBMusicTrack for now based on their instructions...
	song = [[GBMusicTrack alloc] initWithPath:[[NSBundle mainBundle] pathForResource:@&quot;background&quot; ofType:@&quot;mp3&quot;]];
	//[song setRepeat:YES];
	//[song play];

	[self initBricks];		// fill in and display all the bricks
	[self initLives];
	[self initExplosion];	// pre-load explosion array
	[self initRain];		// pre-load rain array
	[self initTimer];		// start game timers and we are on our way!

	UIImage *image = [UIImage imageNamed:@&quot;missile.png&quot;];
	missileView = [[[UIImageView alloc] initWithImage:image] autorelease];
	missileView.hidden=YES;		// load the missile image, hide it for now
	[self.view addSubview:missileView];

	ball.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2+30);

}
</pre>
<ol>
<li>Let&#8217;s discuss what we are doing here &#8211; its pretty straightforward &#8211; this function is called when the game first loads (only once, remember that).</li>
<li>First off, we set some variables to the right values &#8211; most of these were explained earlier in the .h file in part I</li>
<li>Some notes: kBallSpeedX and kBallSpeedY will have integral values that decide the next increment of the ball. later you will see in the game logic that that we change these values + or &#8211; to take care of bounces, hitting objects etc. That way after these variables are changed based on what the ball hits, when we add these to the current X and Y position of the ball, the ball will move around the screen</li>
<li>You will also see that I set the timers to nil. I am taking a short-cut here &#8211; you will see later that when a game ends or pauses, I reset some timers and start them again. But instead of having to figure out which timers are alive or not, I call the &#8220;stop&#8221; timer on them anyway and setting them to nil is important here. Objective C guarantees that I can invokes messages on nil without crashing, so I don&#8217;t need to write extra code later to check their status. Some argue this is bad programming. To me, since I know what I am doing, I think its a great convenience</li>
<li>backgroundArray is initialized with different images. Basically, these images will be set to the background depending on which level you are in later</li>
<li>I then go ahead and set up some standard operations to enable and detect the accelerometer. Basically, I have requested that I be notified once in 30 seconds about accelerometer movements. When it detects accelerometer changes, it will invoke my touchesMoved function discussed later</li>
<li>You will also notice that I initialize a bunch of different sounds and assign them handles. initAudioStreams is a convenience function I created to implement the necessary code to initialize a handle to load a wav file and make it ready to play. Basically I am using AudioSystemSound APIs to play them as they are all small sounds. It is easy to use, but also has disadvantages (like no volume control on a per sound basis etc.). The names have already been explained in the .h file in part 1</li>
<li>Next up, in addition to playing sounds , I also wanted to play background music. I could explore and use the AV foundation myself for this, but I chanced upon Jake peterson&#8217;s excellent GBMusic track that you can simply point to an mp3 and away it goes. I later commented it because I got bored of continuous music</li>
<li>Needless to say, before you access wav files, png files etc. make sure you copy them to the resources folder of your project otherwise your program won&#8217;t find them</li>
<li>Next up, I call messages to initialize the bricks display, lives display, initialize the explosion sprites, rain animation and start the timers (I will explain it all later). The timers are critical &#8211; thats where the game logic is controlled</li>
</ol>
<h2>Some other helper functions</h2>
<pre class="brush: objc; title: ; notranslate">

//=============================================================================
// play sounds only if volume is not muted
-(void) playAudio: (SystemSoundID) soundId
{
	if (kVolumeIsOn) {AudioServicesPlaySystemSound(soundId);}
}
//=============================================================================
// convenience function. Pass it a reference to the SystemSoundID handle, the file and its type and it
// creates an audio stream ready to play
- (void) initAudioStreams: (SystemSoundID *)soundId :(NSString *)soundFile  :(NSString *) type
{
	NSString *audioPath=[[NSBundle mainBundle] pathForResource:soundFile ofType:type];
	CFURLRef audioURL = (CFURLRef) [NSURL fileURLWithPath:audioPath];
	AudioServicesCreateSystemSoundID(audioURL, soundId);
}

//=============================================================================
// pre-load the explosion effect into an array.
- (void) initExplosion
{
	explodeImages = [[NSMutableArray alloc] initWithCapacity: 34];
	for (int i = 1; i &lt;= 34; i++)
	{
		NSString *imageName = [NSString stringWithFormat:@&quot;boom%d.png&quot;,i];
		UIImage *image = [UIImage imageNamed:imageName ];
		[explodeImages addObject: image];
	}
}
</pre>
<ol>
<li>initAudioStreams invokes the steps necessary to associate a handle to wav files. It follows the apple procedures exactly</li>
<li>playAudio simply invokes AudioServicesPlaySystemSound but only if kVolumeIsOn variable is 1. You will see later that you can tap on the volume icon on the game to enable/disable sound. This action will toggle kVolumeIsOn between 0 and 1 and the respective sound will be played or not played. It is worthwhile to note that when sounds are played, they are done asynchronously which is great because you can animate while the sound plays in the background</li>
<li>initExplosion basically creates an array of 34 UIImages. Each UIImage will hold an image of an explosion in progress. Later, when a ball or missile hits a brick, I will use UIKit animation APIs to iterate through each image quickly to make it look like a real explosion</li>
</ol>
<h2>The 2D Arrays that define the brick layout and their powers</h2>
<pre class="brush: objc; title: ; notranslate">

//=============================================================================
// load bricks layout. This array controls what sort of bricks show at each
// cell of the brick matrix

- (void) initBrickLayout
{
	NSLog(@&quot;init brick layout&quot;);
	NSLog(@&quot;Current Game Level is %d&quot;,gameLevel);

	// You can modify these arrays to respresent the bricks
	// as you want for each level. Each block is for a particular level.
	// 0 = no brick at this cell
	// 1 = normal brick - you hit it, it explodes and you add to your score
	// 2 = metal brick - you can't kill it - the ball will hit and bounce off faster
	// 3 = super brick - you hit it, it explodes and you will get a new life (if you are not at max)
	// 4 = missile brick - you get 5 missiles each time you hit this one

	int bricklevel[GAME_LEVELS][BRICKS_ROWS][BRICKS_COLUMNS] = {
	{
			// level 1
			{2,0,0,1,0,0,2},
			{0,0,1,1,1,0,0},
			{0,1,4,0,4,1,0},
			{1,1,3,0,3,1,1},
			{1,1,1,0,1,1,1},
			{0,1,3,0,3,1,0},
			{0,0,4,1,4,0,0},
			{2,0,0,1,0,0,2},
	},
	{
			// level 2
			{3,2,1,1,1,2,3},
			{1,1,1,1,1,1,1},
			{2,1,1,1,1,1,2},
			{1,1,1,1,1,1,1},
			{1,1,2,3,2,1,1},
			{4,1,1,2,1,1,4},
			{1,2,1,1,1,2,1},
			{2,1,1,1,1,1,2},
	},
	{

			// level 3
			{0,0,0,3,0,0,0},
			{0,0,1,1,1,0,0},
			{0,0,1,1,1,0,0},
			{0,2,1,1,1,2,0},
			{0,1,1,1,1,1,0},
			{2,1,1,1,1,1,2},
			{1,4,1,1,1,4,1},
			{1,1,2,1,2,1,1},
	},
	{
			// level 4
			{0,1,0,3,0,1,0},
			{2,1,1,1,1,4,2},
			{0,1,1,1,1,1,0},
			{0,0,1,1,1,0,0},
			{0,0,1,1,1,0,0},
			{0,1,1,1,1,1,0},
			{2,4,1,3,1,1,2},
			{1,0,1,0,1,0,1},
	},
	};

	NSLog (@&quot;Copying level %d(-1) to bricks description&quot;, gameLevel);
	memcpy (brick_description, bricklevel[gameLevel-1], sizeof(brick_description)); // C still rocks. W00t :-)
}
</pre>
<ol>
<li>Right, this is why I am using a 2D array for the bricks. It is just visually easy. Each level has a 2D array (hence brick_level[levels][rows][col]. Each number represents a brick type.</li>
<li>So basically, depending on the value of gameLevel, I copy the right array index into brick_description and then display the bricks based on these numbers</li>
<li>If you want to add levels, just add another matrix here and increase GAME_LEVELS #define in the .h  file</li>
</ol>
<h2>Making it a rainy day</h2>
<pre class="brush: objc; title: ; notranslate">

//=============================================================================
// init rain array
- (void) initRain
{
	NSLog(@&quot;Inside initRain&quot;);
	NSMutableArray *array = [[NSMutableArray alloc] init];
	self.rainDrops = array;
	[array release];

	UIImage *rainImage = [UIImage imageNamed:@&quot;raindrop.png&quot;];
    UIImageView *rainView;

	// randomly place 50 rain drops across the screen
    for (int i = 0; i&lt; 50; i++)
	{
        rainView= [[UIImageView alloc] initWithImage:rainImage];
		rainView.alpha=0.3;
		rainView.hidden=YES;

        int x = arc4random()% (int)self.view.bounds.size.width;
        int y = arc4random()% (int)self.view.bounds.size.height;
        rainView.center = CGPointMake (x,y);

		// the background image is at index 0, make rain at 1,
		// so it is behind the bricks
        [self.view insertSubview:rainView atIndex:1];
        [self.rainDrops addObject: rainView];
        [rainView release];
	}
}

// we need to hide the rain for layers that don't have rain
- (void) hideRain
{
	for (UIImageView *rain in rainDrops)
	{
		rain.hidden=YES;
	}
}

// animate the rain across the screen
-(void)moveRain{

	for (UIImageView *rain in rainDrops) {

		CGPoint newCenter = rain.center;
		newCenter.y = newCenter.y +2;
		newCenter.x = newCenter.x +1;
		rain.hidden = NO;

		if (newCenter.y &gt; self.view.bounds.size.height){
			newCenter.y=0;
			newCenter.x = arc4random()%(int)self.view.bounds.size.width;
		}
		if (newCenter.x &gt; self.view.bounds.size.width){
			newCenter.x =0;
		} else if (newCenter.x &lt; 0) {
			newCenter.x = self.view.bounds.size.width;
		}

		rain.center = newCenter;

	}
}
</pre>
<ol>
<li>These are the &#8216;rain animation&#8217; functions. Basically, initRain randomly creates 50 rain drops on the screen. It is set to appear at index 1 which is right above the background image at index 0 so it falls below the bricks</li>
<li>Depending on the level, I either show the rain or hide the rain (rain.hidden  = YES | NO)</li>
<li>moveRain just increments the co-ords of each drop so they animate by</li>
</ol>
<h2>Launching the missile</h2>
<pre class="brush: objc; title: ; notranslate">
//=============================================================================
// launches a missile
// you would think we can use Core Graphics animate to automatically do this
// but we can't as we also need to detect if it hit a brick with CGRectIntersect
// The automatic animation does not allow for detection if intersects, so we need
// to do it ourselves, or, use auto animation in small steps.

- (void) launchMissile;
{
	if (!kMissilesLeft) {NSLog(@&quot;You don't have missiles&quot;);return;}
	if (kMissileFiring) {return;} // only allow 1 missile at a time
	haveMissileView.hidden=NO;
	kMissileFiring=1;

	missileView.hidden=NO;
	[self playAudio:missileSound];
	missileView.center=CGPointMake(paddle.center.x, paddle.center.y-10);
	kMissilesLeft--;
	if (!kMissilesLeft) {haveMissileView.hidden=YES;}

	NSLog(@&quot;You have %d missiles left&quot;,kMissilesLeft);
}

-(void) missileFinished
{
	missileView.hidden=YES;
	kMissileFiring=0;
}
</pre>
<ol>
<li>I explained this earlier &#8211; like everything else that moves in this game, the missile is again just a UIView that moves up the screen when you fire it. You fire it by tapping twice on the paddle. That calls launchMissile. When the missile goes to the top of the screen, or, hits a brick first (you will see this in the collision logic part), its job is done.</li>
</ol>
<h2>Initializing the Bricks  &amp; Lives Display</h2>
<pre class="brush: objc; title: ; notranslate">
//=============================================================================
// load the bricks images and create the bricks matrix. Also create the lives display
- (void) initBricks
{
	NSLog(@&quot;Inside initBricks&quot;);

	brickImages[0]=@&quot;brick2.png&quot;; //normal
	brickImages[1]=@&quot;brick2.png&quot;;
	brickImages[2]=@&quot;steel.png&quot;;  // cant destroy
	brickImages[3]=@&quot;brick3.png&quot;; // special powers - life
	brickImages[4]=@&quot;brick1.png&quot;; // special powers - missiles

	[self initBrickLayout];
</pre>
<p>We load up the bricks array with the correct images and then call initBrickLayout which copies the correct brick matrix description to the brick_description array.<br />
The logic will be that based on the brick_array matrix description for the level, we will show the right brick at the right place</p>
<pre class="brush: objc; title: ; notranslate">

	for (int rows=0; rows&lt;BRICKS_ROWS; rows++)
	{

		for (int columns=0; columns&lt;BRICKS_COLUMNS; columns++)
		{
			int imageType = brick_description[rows][columns];
			UIImage *image = [UIImage imageNamed:brickImages[imageType]];
			bricks[rows][columns] = [[[UIImageView alloc] initWithImage:image] autorelease];
			CGRect myFrame = bricks[rows][columns].frame;

			myFrame.size.width=30;
			myFrame.size.height=10;
			// position the bricks so there is some space between them
			myFrame.origin = CGPointMake(columns*42+5,rows*17+80);
			//NSLog(@&quot;Width:%f, height:%f&quot;,myFrame.size.width, myFrame.size.height);

			bricks[rows][columns].frame= myFrame;
			bricks[rows][columns].alpha = MIN(1,brick_description[rows][columns]);
			// every brick is a subview - show it

			[self.view addSubview:bricks[rows][columns]];
		} //cols
	} //rows
}
</pre>
<p>Some laziness on my part. I drew the bricks to be originally larger than what I am displaying. I then found them too easy to kill, so I just changed their size in code (see myFrame.size.width/height lines). Ideally, you should not waste resources.<br />
Anyway, so now, we iterate through the bricks matrix and display them according to the brick type in brick_description. As far as  the MIN(1, brick_description&#8230;.) line goes, all it is doing is saying &#8220;display any bricks that don&#8217;t have a 0 in the description matrix (since 0 means no brick there)&#8221;. Whether the brick is a normal brick (1) or a super brick (2,3,4), they will all be displayed, so have an alpha of 1 (alpha determines opacity. 0 = transparent. 1 = opaque)</p>
<p>Finally, each brick is actually displayed on the screen as a new view (self.view addSubview)</p>
<pre class="brush: objc; title: ; notranslate">

//=============================================================================
// load the bricks images and create the bricks matrix. Also create the lives display
- (void) remapBricks
{
	NSLog(@&quot;Inside remapBricks&quot;);

	[self initBrickLayout];

	for (int rows=0; rows&lt;BRICKS_ROWS; rows++)
	{

		for (int columns=0; columns&lt;BRICKS_COLUMNS; columns++)
		{
			int imageType = brick_description[rows][columns];
			[bricks[rows][columns] setImage:[UIImage imageNamed: brickImages[imageType]]];
			bricks[rows][columns].alpha = MIN(1,brick_description[rows][columns]);
		} //cols
	} //rows
}
</pre>
<p>I could have probably merged this into initBricks but thought it better to be separate. Basically, initBricks is only called once when the game loads.<br />
After that, the brick layers have already been created, so we don&#8217;t need to create new UIViews etc. All we need to do to move up and down levels<br />
is simply to copy a new matrix of brick descriptions, change the brick image at the relevant positon to a new brick image and change its alpha based on the new matrix.<br />
So remapBricks is called after that to move up levels, reset to level 1 after death etc.</p>
<pre class="brush: objc; title: ; notranslate">
//=============================================================================
// Initializes  the lives display on top left
- (void) initLives
{
	NSLog(@&quot;Inside initLives&quot;);
	// load lives array and create the lives display
	for (int i=0; i&lt;LIVES;i++)
	{
		UIImage *image = [UIImage imageNamed:@&quot;lives.png&quot;];
		lives[i] = [[[UIImageView alloc] initWithImage:image] autorelease];
		CGRect myFrame = lives[i].frame;
		// position the lives so there is some place between them
				myFrame.origin = CGPointMake(i*40 % 160 ,20+(20* (i/4)));
		lives[i].frame= myFrame;
		// every life is a subview - show it
		[self.view addSubview:lives[i]];
	}
}
</pre>
<p>This function basically displays a small paddle for each life you have remaining at the top left. It breaks up the # of lives in rows of 4 each.</p>
<h2>The main game timers</h2>
<pre class="brush: objc; title: ; notranslate">

//=============================================================================
// Initializes  all timers,
// gameTimer: The core timer that controls game logic
// backgroundTimer: animates the background elements
// harderTimer: after X seconds, it makes the game harder
- (void) initTimer
{
	NSLog(@&quot;Inside initTimer&quot;);
	[gameTimer invalidate];
	[backgroundTimer invalidate];
	[harderTimer invalidate];

	gameTimer=[NSTimer scheduledTimerWithTimeInterval:1.0/30.0 target:self selector:@selector(playGame:) userInfo:nil repeats:YES];
    backgroundTimer=[NSTimer scheduledTimerWithTimeInterval:1.0/30.0 target:self selector:@selector(adjustBackground:) userInfo:nil repeats:YES];
	harderTimer = [NSTimer scheduledTimerWithTimeInterval:kMakeItHarder target:self selector:@selector(makeItHarder:) userInfo:nil repeats:YES];

}
</pre>
<p>The entire game logic is really happening inside the gameTimer callback function (Which happens to be playGame). Basically, gameTime is called once in 30 seconds. So every<br />
1/30 seconds my program checks where is the ball, where are the missiles, where is the paddle, who hit whom and update scores and status accordingly.</p>
<p>BackgroundTimer takes care of animating some non essential stuff (the cloud moving and the moveRain functions are processed in BackgroundTimer callback. The backgroundTimer callback does however do one important game related function &#8211; it moves the missile too. More on that later</p>
<h2>When life just got harder</h2>
<pre class="brush: objc; title: ; notranslate">

//=============================================================================
// This is the callback that is called when the game needs to get harder
- (void) makeItHarder:(NSTimer *)timer
{

	if (kGamePause) {return;}

	[self playAudio:holycowSound];
	NSLog (@&quot;TIME TO MAKE IT HARDER FOR LEVEL:%d&quot;, gameLevel);

	//NSLog(@&quot;*********************Inside MakeItHarder, bumping up ball speed&quot;);

	NSLog(@&quot;Original SpeedX:%d, SpeedY:%d&quot;,kBallSpeedX,kBallSpeedY);
	if (kBallSpeedX&lt;8) {kBallSpeedX++;}
	if (kBallSpeedY&lt;8) {kBallSpeedY++;}

	ballSpeed.x = (ballSpeed.x &lt;0) ? kBallSpeedX:-kBallSpeedX;
	ballSpeed.y = (ballSpeed.y &lt;0) ? kBallSpeedY:-kBallSpeedY;

	NSLog(@&quot;Inside MakeItHarder, bumping up ball speed to X:Y %d:%d&quot;, kBallSpeedX, kBallSpeedY);
	ballSpeed = CGPointMake(kBallSpeedX,kBallSpeedY);

}
</pre>
<p>There are many ways you can make a level harder. I used to hate those ping pong players who would always play defensive and waste time. Once in a while, I&#8217;d try and force them into a smash round. Same here. After this timer ticks off, I increase the ball speed. You can add more features here, like possibly moving the bricks down every few seconds etc (if you do, you will need to add another collision logic later to see if the paddle hit the bricks (which is currently impossible)</p>
<h2>Background Animation and Missile Animation</h2>
<pre class="brush: objc; title: ; notranslate">

//=============================================================================
// This is the callback that backgroundTimer calls at every interval
- (void) adjustBackground: (NSTimer *)timer

{
	//if (kGamePause) {return;}
</pre>
<p>I originally did not allow the background to animate if the game was paused. Then I thought it to be cooler if it still did, so I commented it out</p>
<pre class="brush: objc; title: ; notranslate">

	if (gameLevel % 2)
	{
		float newposx;
		cloud.hidden=NO;
		[self hideRain];

		newposx = cloud.center.x+0.3;  // move cloud image across the screen smoothly
		if (cloud.center.x &gt; self.view.bounds.size.width+80) {newposx=-64;}	// wrap it around
		cloud.center = CGPointMake(newposx, cloud.center.y);
	}
	else
	{
		cloud.hidden=YES;
		[self moveRain];
	}
</pre>
<p>So I am basically either moving clouds or showing rain for every alternate level. Short-cuts. Short-cuts.</p>
<pre class="brush: objc; title: ; notranslate">
	if (kMissileFiring)
	{

		int missileY;
		missileY=missileView.center.y-10;
		if (missileY&lt;0)
		{
			[self missileFinished];
		}

		else
		{
			missileView.center=CGPointMake(missileView.center.x, missileY);
		}

	} // kMissileFiring
}
</pre>
<p>Remember I said the missile firing is also handled here? Well, right here. If kMissileFiring is on, then we know we need to animate the missile up. All we do here is decrease the Y co-ord of the missile so it keeps moving up. Once it moves up the screen, we hide it (self missileFinished). The missile launch happens elsewhere. This is just moving it, once it is fired.</p>
<p>Now, you may ask why do we need to do this? Can&#8217;t we just use the CGTransform functions to automatically and cool-ly move it up? Yes you can. But here is the deal. If you do, you will not be able to detect when it hits anything. If you read up on CG Transform functions, you first specify a start, then an end (so you specify missile Y = some value and then again missile Y = 0 one after the other and then invoke start animation. iOS takes care of transitioning from &#8220;some value&#8221; to &#8220;0&#8243; but to everyone else outside of the animation module, the position of the missile is already 0 (it has already reached its destination). So net-net you can&#8217;t use CG Intersect Rect etc. to detect collisions with auto-animation of this type. Boo.</p>
<h2>Reset</h2>
<pre class="brush: objc; title: ; notranslate">

//=============================================================================
// resets game back to normal.
-(void) resetGame
{
	NSLog(@&quot;Inside reset Game&quot;);
	score = 0;
	livesleft = LIVES;
	kBallSpeedX = 4;
	kBallSpeedY = 4;
	ballSpeed = CGPointMake(kBallSpeedX,kBallSpeedY);
	gameLevel = 1;
	labelCurrentLevel.text = [NSString stringWithFormat:@&quot;%d&quot;,gameLevel];
	labelScore.text = [NSString stringWithFormat:@&quot;%d&quot;, score];
	kMissileFiring=0;
	kMissilesLeft=0;
	haveMissileView.hidden=YES;

	for (UIImageView *rain in rainDrops) { rain.hidden = YES; }
	[backgroundImageView setImage:[UIImage imageNamed: backgroundArray[gameLevel-1]]];

	NSLog(@&quot;Calling initBricks with level:%d&quot;,gameLevel);
	[self remapBricks];
	[self initTimer];

	kGamePause=1;
	ball.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2+30);
	NSLog(@&quot;*****GAME RESET***********&quot;);

}
</pre>
<p>Nothing much. Very similar to what I do when the game loads. Reset all the variables etc. So logically, this is called when the game gets over (You die, or, you finish all levels)</p>
<h2>Explosion Time!!</h2>
<pre class="brush: objc; title: ; notranslate">
// This is called when the ball hits a solid brick. It shows an explosion
-(void) explodeBrick: (int) y : (int) x
{

	NSLog(@&quot;Explosion!!!!!&quot;);

	// Position the explosion so it is properly centered on the brick
	explodeView.center = CGPointMake(bricks[y][x].center.x, bricks[y][x].center.y);
	// bring the explosion view to the front
	[self.view bringSubviewToFront:explodeView];

	explodeView.animationImages = explodeImages;
	explodeView.animationDuration = 1;
	explodeView.animationRepeatCount = 1;
	[explodeView startAnimating];

}
</pre>
<p>My favorite function. (Ok, objective C wants me to call it a message, but I prefer function. I grew up on em).<br />
Remember the explosion array we init&#8217;d during ViewDidLoad? Time to play it. All we do is get the center X and Y co-ordinate of the brick that was hit and use the UIView animation to animate through all the 34 images in  1 second to give a great animation of an explosion</p>
<h2>Goodbye and thanks for the fish</h2>
<pre class="brush: objc; title: ; notranslate">
- (void)viewDidUnload {
}

- (void)dealloc {
	[ball release];
    [paddle release];
	[labelScore release];
	[song release];
	[explodeImages release];
	[rainDrops release];

	AudioServicesDisposeSystemSoundID(hitSound);
	AudioServicesDisposeSystemSoundID(missSound);
	AudioServicesDisposeSystemSoundID(clapSound);
	AudioServicesDisposeSystemSoundID(explodeSound);
	AudioServicesDisposeSystemSoundID(booSound);
	AudioServicesDisposeSystemSoundID(holycowSound);
	AudioServicesDisposeSystemSoundID(boingSound);
	AudioServicesDisposeSystemSoundID(metalSound);
	AudioServicesDisposeSystemSoundID(gotlifeSound);
	AudioServicesDisposeSystemSoundID(missileSound);

	// anything else that I missed?
	[super dealloc];

}

@end
</pre>
<p>Finally, I deallocate stuff when its time to say goodbye.</p>
<h2>Huh ? Where is the GAME!?!</h2>
<p>As it turns out, wordpress barfs with long posts. So the playGame function and  the code for detecting touches is in <a href="http://blog.roychowdhury.org/2010/10/27/tutorial-iphone-game-programming-professional-bricks-part-iii/">part III</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.roychowdhury.org/2010/10/26/tutorial-iphone-game-programming-professional-bricks-part-ii/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Tutorial: iPhone Game Programming- professional Bricks (Part I)</title>
		<link>http://blog.roychowdhury.org/2010/10/25/tutorial-iphone-game-programming-professional-bricks-part-i/</link>
		<comments>http://blog.roychowdhury.org/2010/10/25/tutorial-iphone-game-programming-professional-bricks-part-i/#comments</comments>
		<pubDate>Mon, 25 Oct 2010 14:46:45 +0000</pubDate>
		<dc:creator>Arjun</dc:creator>
				<category><![CDATA[Arjun Roychowdhury]]></category>
		<category><![CDATA[Gaming]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[world 2.0]]></category>
		<category><![CDATA[coreanimation]]></category>
		<category><![CDATA[game development]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[quartz2D]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[uikit]]></category>

		<guid isPermaLink="false">http://blog.roychowdhury.org/?p=377</guid>
		<description><![CDATA[(Read Part II here) Bricks &#8211; my all time favorite game (just after Tetris). So this post is a tutorial on how to write your own &#8216;bricks&#8217; for iphone But&#8230;. What&#8217;s a game tutorial that: a) Does not look professional? b) Does not have multiple levels? c) Does not have ghastly sound effects? d) Does not have explosions? e) Does not have  missiles? f) Does not have a &#8220;Hack Mode&#8221;? (w00t) Before we get anywhere, lets take a look at what we will be building. Its a 3:30 min video which I strongly recommend you see first so you can related explanations easier. (And also, it took me all of 10 minutes to create it, so you better spend 3:30 admiring it :-D) History &#38; Disclaimer I am by no means an iPhone developer. Actually, I am by no means a developer. While I&#8217;ve been involved in technology very deeply, my work does not require me to code, and so, I&#8217;ve mostly been out of coding for the past 12 years (with the exception of the occasional perl coding for personal projects).  But there is just too much going on in the mobile space for me not to get my<a href="http://blog.roychowdhury.org/2010/10/25/tutorial-iphone-game-programming-professional-bricks-part-i/"> <br /><br /> (Read More...)</a>]]></description>
			<content:encoded><![CDATA[<p>(Read Part II <a href="http://blog.roychowdhury.org/2010/10/26/tutorial-iphone-game-programming-professional-bricks-part-ii/">here</a>)</p>
<p>Bricks &#8211; my all time favorite game (just after Tetris). So this post is a tutorial on how to write your own &#8216;bricks&#8217; for iphone</p>
<p>But&#8230;.</p>
<p>What&#8217;s a game tutorial that:</p>
<p><em>a) Does not look professional?</em></p>
<p><em>b) Does not have multiple levels?</em></p>
<p><em>c) Does not have ghastly sound effects?</em></p>
<p><em>d) Does not have explosions?</em></p>
<p><em>e) Does not have  missiles?</em></p>
<p><em>f) Does not have a &#8220;Hack Mode&#8221;? (w00t)</em></p>
<p>Before we get anywhere, lets take a look at what we will be building. Its a 3:30 min video which I strongly recommend you see first so you can related explanations easier. (And also, it took me all of 10 minutes to create it, so you better spend 3:30 admiring it :-D)</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="480" height="385" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/YpK0OmGjiIE?fs=1&amp;hl=en_US&amp;rel=0" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="480" height="385" src="http://www.youtube.com/v/YpK0OmGjiIE?fs=1&amp;hl=en_US&amp;rel=0" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<h1><strong>History &amp; Disclaimer</strong></h1>
<p>I am by no means an iPhone developer. Actually, I am by no means a developer. While I&#8217;ve been involved in technology very deeply, my work does not require me to code, and so, I&#8217;ve mostly been out of coding for the past 12 years (with the exception of the occasional perl coding for personal projects).  But there is just too much going on in the mobile space for me not to get my hands dirty again. So, with that in mind, I took it upon myself to learn basic iPhone programming and what better way than to define a project? My project was &#8220;Bricks&#8221;.</p>
<p>The disclaimer part: Since this is pretty much my first attempt, I can&#8217;t comment on this tutorial being a &#8220;good approach&#8221;. All I can say is,  <em>&#8220;if I can code for iPhone, you can too&#8221; !</em></p>
<p><em>Finally, this is not a &#8220;from scratch how to code for iphone&#8221; tutorial. I assume you know about Xcode, Views, Interface Builder etc.</em></p>
<p><em><span id="more-377"></span><br />
</em></p>
<h1><strong>Tutorial Credits</strong></h1>
<p>When you go about learning, google is your friend. A lot of what I gleaned came from different sites and one book. While I based my initial game on things I learned from them, once I got the basic approach, I took off on my own. For that I thank them:</p>
<ol>
<li><a href="http://icodeblog.com/2009/01/15/iphone-game-programming-tutorial-part-1/">Ping Pong</a> tutorial</li>
<li><a href="http://www.amazon.com/Beginning-iPhone-Games-Development-Cabrera/dp/1430225998">Beginning iPhone game programming</a> by Apress (they also have a super elementary bricks game, but I think I found the ping pong tutorial better. I found the book useful to understand CoreAnimation/Quartz 2D)</li>
<li>And the biggest thanks goes to <a href="http://stackoverflow.com/">StackOverflow</a> &#8211; whenever I faced a problem I could be sure this site had an answer :)</li>
</ol>
<h1><strong>Resource Credits</strong></h1>
<p>The tutorial includes images, sounds and a special background music class. Here are their credits directly from my .h file</p>
<pre class="brush: objc; title: ; notranslate">
// Explosion sprites credit:
// http://homepage.ntlworld.com/david.howe50
//
// Other tutorial credits:
// http://icodeblog.com/2009/01/15/iphone-game-programming-tutorial-part-1/
// and Beginning iPhone Game Development by Apress
//
// Background images:
// http://openclipart.org
//
// Music:
// Jake Peterson's GBMusicTrack for background MP3 (classical music is &quot;Minuet in G Major&quot; by Bach from my personal collection)
// clap: http://www.pacdv.com/sounds/applause-sounds.html
// other sounds: http://www.wavsource.com/sfx/sfx3.htm
// http://simplythebest.net/sounds/WAV/sound_effects_WAV
</pre>
<h1><strong>Screen Elements</strong></h1>
<p>Let&#8217;s first look at the screen layout of the game to give you an idea of the elements of the game. (Click on image for larger version)</p>
<p><a href="http://blog.roychowdhury.org/wp-content/uploads/2010/10/screen-elements.png"><img class="alignnone size-medium wp-image-384" title="screen elements" src="http://blog.roychowdhury.org/wp-content/uploads/2010/10/screen-elements-300x293.png" alt="" width="300" height="293" /></a></p>
<p>So as you see, the game has several things going on that we want to achieve (well, some you don&#8217;t see above, so I&#8217;ll just tell you)</p>
<ol>
<li>This is a multi-layer game &#8211; when you kill all the bricks, we will move the player to the next level</li>
<li>To differentiate between levels, we would like to use a different background image and some animation of the background (right now, I switch between &#8220;rain&#8221; and &#8220;clouds moving&#8221;)</li>
<li>You see bricks have different &#8220;powers&#8221; &#8211; the red bricks are normal. We also want bricks that give you missile power (these are the green bricks). Then there are yellow patterned bricks that give you an extra life. Finally, there are steel bricks, who  can&#8217;t be killed (the metal ones)</li>
<li>We want explosions each time a missile or the ball hits the screen</li>
<li>At the bottom row of the game, we want to enable several icons that do special stuff:
<ol>
<li>If you triple tap the lower left corner, we want to enable a &#8216;hack mode&#8217; &#8211; when on, you can skip levels by killing 4 bricks</li>
<li>We want to enable/disable sound by tapping on the volume icon</li>
<li>We want to see how to play the game (as if its hard!) by tapping the info button</li>
<li>When we get missile power, we want to know that we have missile power! (so the missile icon on the lower right)</li>
</ol>
</li>
<li>And finally, we want SOUND EFFECTS! What&#8217;s a game without some blood curdling sound?</li>
</ol>
<h2>Game Controls</h2>
<p>Here is the help screen directly from the game so you get a feel of the controls we plan to use to play this game</p>
<p><a href="http://blog.roychowdhury.org/wp-content/uploads/2010/10/help.png"><img class="alignnone size-full wp-image-396" title="help" src="http://blog.roychowdhury.org/wp-content/uploads/2010/10/help.png" alt="" width="300" height="440" /></a></p>
<h2><strong>Creating your images</strong></h2>
<p>When I showed the game to some colleague with a crappy looking line for a paddle and no background and simple bricks, their reaction was &#8220;Ah, nice because its your first game&#8221;. When I added all the images, suddenly, they looked amazed at how professional the game looked and that it should be on the app store (well, that&#8217;s their opinion). I cannot stress how important it is to select the right images.</p>
<p>There are some great resource available on the net. However, before you swipe them, remember to check their copyright information and what you can/cannot do with them. In my case, I designed the paddle, ball and bricks myself. For the level backgrounds and icons, I used images from <a href="http://www.openclipart.org/">http://www.openclipart.org/ </a>. As the credits earlier state, I took the explosion image from <a href="http://homepage.ntlworld.com/david.howe50">here</a>. There are around 100 images there in the sequence &#8211; I cut it down to 34 for my game by deleting interim sprites.</p>
<p><span style="text-decoration: underline;">On creating the ball and bricks:</span></p>
<p>You can transform a simple pattern to a convincing brick very easily. Once you have a pattern made, simply apply a &#8220;Beveled&#8221; edge filter effect and it looks like a brick. (All photo editors have a bevel filter &#8211; gimp, Photoshop are the ones I&#8217;ve used)</p>
<p>As far as the ball goes, really simple. Draw an ellipse, fill it with a radial gradient from red to dark red. Then add a while spot somewhere to show reflection. That&#8217;s all.</p>
<p>For the paddle, I started with a rounded rectangle, filled it with a vertical gradient of blue and dark blue, then drew two yellow lines on each side and finally applied a texture on top. Finished off with a bevel effect.</p>
<p>I know I&#8217;ve skimmed through the details here, but I want to get to the main code tutorial sooner.</p>
<h2>Creating your sounds</h2>
<p>I first went down the path of recording my own voice. Not good. There are excellent resource available for sounds. Check the credits for where I got them from.</p>
<h3>Most .WAV files will not work when you take them to the iPhone</h3>
<p>I am probably skipping ahead, but I wanted to mention that most of the sites I visited had great sound. I am using AudioServicesPlaySystemSound to play my sound. But when I imported the sounds to my project most of them just would not play! I found out later that this is because many of the WAV files are recorded as a Mono track, while AudioServicesPlaySystemSound works with Stereo track WAV files (or, I don&#8217;t know enough of the API to make it work with mono). Anyway, what works for me, works. To make all the sounds work for my game, all I had to do was convert the mono tracks to stereo. And how do you do that? With just a few clicks, thanks to Audacity. Here is now:</p>
<p>a) Load the WAV file in <a href="http://audacity.sourceforge.net/">audacity</a></p>
<p>b) Project-&gt;New Audio Track. (This will create an empty audio track below your mono track</p>
<p>c) Click on the old audio track, cmd+a, cmd+c (copy the full track)</p>
<p>d) Click on new audio track, cmd+v (paste)</p>
<p>e) Click on the &#8220;down arrow&#8221; on the top left of the old audio track (right next to the name) and select &#8220;Make Stereo Track&#8221;</p>
<p>f) Export as Wav.</p>
<p>Ta-dah. You now have great working sound you can use with your iphone.</p>
<p>As a side note, I also wanted some background music to play continuously. I just took J<a href="http://www.idevgames.com/forum/showthread.php?t=15280">ake Peterson&#8217;s GBMusic Track .m and .h</a> files and imported it into my project. All you need to do is point it at any mp3 and away it goes. I later disabled background music &#8211; got too boring for me :-) but its in the code and you can enable it. Jake&#8217;s class is great. It just works (not in the simulator though) and I could focus on the game right away.</p>
<p><em>Now, with all your images and sounds loaded into the project, lets get started on the game logic</em></p>
<h1><strong>So which graphics engine do I use?</strong></h1>
<p>The iPhone SDK gives you various options for graphics. You can use:</p>
<ol>
<li>UIKit</li>
<li>Quartz 2D</li>
<li>Open GL ES</li>
</ol>
<p>This game has been developed completely using UIKit and a bit of Quartz 2D to animate some UI Views. I&#8217;ve not even begun to explore the rest. Why did I select UIKit? Because it seemed perfect for this game (and likely many games like this), is simple to understand and very high level. At an abstract level, when you use UIKit, all your graphics  are represented as &#8220;Image Views&#8221;.  Think of each Image View as a &#8220;sheet&#8221;. Each &#8220;sheet&#8221; can consist of one or more images and each &#8220;sheet&#8221; can be stack on top of each other, moved around and/or animated. If you are used to photoshop or Gimp, the concept of layers will be natural to you. Then, to tie things in nicely, iPhone SDK also ties in Quartz 2D with the UIKit very well &#8211; you can do some pretty advanced animation automatically simply by defining a &#8220;start state&#8221; , &#8220;end state&#8221; and &#8220;transition logic&#8221; for a UIView and let the Quartz 2D engine take care of the animation from start to end with the requested logic. More on that later.</p>
<h1><strong>A few words on the game logic</strong></h1>
<p>When you start reading the code, you will notice a few things upfront:</p>
<ol>
<li>I am (was) a C coder. Whenever I get the chance, I use as much C as possible.</li>
<li>The game grew in spurts. I started off by wanting to make a simple ball-hit-brick game but then I decided to add powers, missiles, etc. later. I did not necessarily think the design through. If I were to do it again (I won&#8217;t), I&#8217;d probably make a better design. Further, my complete lack of knowledge of Objective C also accounted for the choices I made (learn as you go).</li>
</ol>
<p>Having said all of that, the lines of code is pretty small and you should not have issues following it.</p>
<h1><strong>Game Design</strong></h1>
<p>This is a small game. It was created as a &#8220;view controller&#8221; based game in Xcode and all the code is stuffed into &#8220;BricksViewController.h&#8221; and &#8220;BrickViewController.m&#8221;. All other files in the project are wav files for sound, png for images and one mp3 for the background music (you will also see GBMusicTrack.h and .m which are Jake&#8217;s files for background music playback)</p>
<h2>BricksAppDelegate.m</h2>
<p>Well, there is a teeny-weeny bit of code that I added to BricksAppDelegate.m. It is not critical, but makes the game better. Let me discuss that first. Basically, I want my game to pause if the application is interrupted (example, you hit the home button). While iphone freezes the game by default, what happens is that if I don&#8217;t pause the game, the moment you switch back to the game, the ball moves. You may not have enough time to react. So, instead, I override some key callbacks so that the iphone tells my app when I am pushed out of the front view. When I get this notification, I quickly put the game in pause mode.</p>
<p>As it turns out, when IOS4 introduced background support, it changed the callback that is invoked. So, to make sure it works for IOS 3.x and 4.x, I just put in the same code in both APIs</p>
<pre class="brush: objc; title: ; notranslate">
- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
	[viewController saveState];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */

	[viewController saveState];

}
</pre>
<ol>
<li>applicationWillTerminate is called by IOS 3.x while applicationDidEnterBackground is what iOS 4.x calls. All I do is invoke the saveState method of my viewController (the app delegate has a convenient instance reference to viewController which contains my core game logic)</li>
<li>You may think why not simply override these APIs in BricksViewController.m? Well, if you first read the Apple documentation, it will tell you these callbacks are only invoked on the delegate which happens to be BricksAppDelegate. Or, if you are like me, and never read, just implement and then wonder why your callback is not being called, stackOverflow.com will bring up threads where other n00bs like me made the same mistake and suffered several minutes of complete cluelessness&#8230;</li>
</ol>
<h2>BricksViewController.h</h2>
<p>The best way for me to explain the game design is to explain BricksViewController.h to you. First, here is the full dump so you can copy paste it if you need.<br />
<span style="text-decoration: underline;"> (click on show source below)</span></p>
<pre class="brush: objc; collapse: true; light: false; title: ; toolbar: true; notranslate">
//
//  BricksViewController.h
//  Bricks
//
//  Created by Arjun on 10/15/10.
//  All rights reserved.
//

// Explosion sprites credit:
// http://homepage.ntlworld.com/david.howe50
//
// Other tutorial credits:
// http://icodeblog.com/2009/01/15/iphone-game-programming-tutorial-part-1/
// and Beginning iPhone Game Development by Apress
//
// Background images:
// http://openclipart.org
//
// Music:
// Jake Peterson's GBMusicTrack for background MP3 (classical music is &quot;Minuet in G Major&quot; by Bach from my personal collection)
// clap: http://www.pacdv.com/sounds/applause-sounds.html
// other sounds: http://www.wavsource.com/sfx/sfx3.htm
// http://simplythebest.net/sounds/WAV/sound_effects_WAV

#import &lt;UIKit/UIKit.h&gt;
#import &lt;AudioToolbox/AudioToolbox.h&gt;
#import &quot;GBMusicTrack.h&quot;				// Using GBMusicTrack to play background MP3 (does NOT work in simulator)

#define BRICKS_ROWS 8
#define BRICKS_COLUMNS 7				// dimensions of the matrix of bris

#define BRICKS_IMAGES 5					// I have 5 different brick images which can represent different powers
#define LIVES  8						// Maximum lives you can have
#define GAME_LEVELS 4					// Let's start with 4 levels

#define NORMAL_BRICK 1
#define METAL_BRICK  2					// Metal bricks cannot be killed. You will bounce off sharply

#define SUPER_BRICKS 3					// Any brick ID &gt;=3 is a 'special' brick
#define LIFE_BRICK  3					// This one gives you a new life (if you are not at max life)
#define MISSILE_BRICK 4					// This one gives you 5 missiles with each hit

#define HACK_HITCOUNT 4					// What's a game without a hack? If hack mode is on, you get to next level
										// after 4 hits

@interface BricksViewController : UIViewController &lt;UIAccelerometerDelegate&gt;
{

	NSTimer *gameTimer;					// used for the primary game logic (update ball, check hits etc)
	NSTimer *backgroundTimer;			// used to animate backround sprites - cloud and missile movement
	NSTimer *harderTimer;				// after MAKE_IT_HARDER seconds, this will be called so we can step up the game difficulty

	IBOutlet UIImageView *ball;					// will hold the ball as it bounces around
	IBOutlet UIImageView *paddle;				// will hold the paddle
	IBOutlet UIImageView *cloud;				// well, obviously, the cloud in the background
	IBOutlet UILabel *labelScore;				// holds the latest score shown on top right
	IBOutlet UILabel *labelGameOver;			// hidden by default, will showup in center as text when game is over
	IBOutlet UILabel *labelPause;				// text to display when paused
	IBOutlet UIImageView *explodeView;			// will hold explosion images
	IBOutlet UIImageView *backgroundImageView;	// holds the game background wallpaper
	IBOutlet UILabel *labelCurrentLevel;		// Text to display level on screen
	IBOutlet UIImageView *haveMissileView;		// Will show a missile at lower right when you have missiles
	IBOutlet UIImageView *hackView;				// Will show an icon at lower left when hack mode is on
	IBOutlet UIImageView *volumeView;			// swaps between volume on and off image - lower center
	IBOutlet UIImageView *infoView;				// displays the info button
	IBOutlet UIImageView *helpView;				// displays the help screen when you tap the info button

	// various sound events depending on what event occurs.

	SystemSoundID boingSound;
	SystemSoundID clapSound;
	SystemSoundID missSound;
	SystemSoundID hitSound;
	SystemSoundID explodeSound;
	SystemSoundID booSound;
	SystemSoundID holycowSound;
	SystemSoundID gotlifeSound;
	SystemSoundID missileSound;

	CGPoint ballSpeed;								    // holds the speed at which the ball will move
	CGPoint paddleSpeed;								// holds the speed at which the paddle will move
	int score;											// holds latest score - this is used by labelScore to display
	float touch;
	int livesleft;										// if this goes to 0, you are dead.
	int gameLevel;										// your current game level

	UIImageView *bricks[BRICKS_ROWS][BRICKS_COLUMNS];	// will hold the X*Y array of brick images
	int brick_description[BRICKS_ROWS][BRICKS_COLUMNS]; // will hold the brick format and powers

	UIImageView *lives[LIVES];							// holds the display of lives on top left
	UIImageView *missileView;							// hold the missile Image
	NSString *backgroundArray[GAME_LEVELS];				// holds different background images for levels
	NSString *brickImages[BRICKS_IMAGES];				// holds the different brick images
	NSMutableArray *explodeImages;						// holds the sequence of images for an explosion
	NSMutableArray *rainDrops;							// holds the rain drops that are displayed on the screen
	GBMusicTrack *song;									//background music

	int tBallSpeedX ;				// used temporarily for one bounce
	int tBallSpeedY ;				// used temporarily for one bounce
	int kBallSpeedX ;
	int kBallSpeedY ;
	int kMakeItHarder;				// Time to make things harder in the game
	int kGamePause;					// if 1 then game freezes
	int kHackHitCount;				// HACK MODE: if 1, then we can skip levels just after 4 hits
	int kMissileFiring;				// 1 if a missile has launched. We only allow 1 missile at a time
	int kMissilesLeft;				// when 0, your missile power is done
	int kVolumeIsOn;				// toggles volume on and off

}

@property (nonatomic, retain) UIImageView *ball;
@property (nonatomic, retain) UIImageView *paddle;
@property (nonatomic, retain) UIImageView *cloud;
@property (nonatomic, retain) UIImageView *explodeView;
@property (nonatomic, retain) UIImageView *backgroundImageView;
@property (nonatomic, retain) UIImageView *missileView;
@property (nonatomic, retain) UIImageView *haveMissileView;
@property (nonatomic, retain) UIImageView *hackView;
@property (nonatomic, retain) UIImageView *volumeView;
@property (nonatomic, retain) UIImageView *infoView;
@property (nonatomic, retain) UIImageView *helpView;

@property (nonatomic, retain) UILabel *labelScore;
@property (nonatomic, retain) UILabel *labelCurrentLevel;
@property (nonatomic, retain) UILabel *labelGameOver;
@property (nonatomic, retain) UILabel *labelPause;
@property (nonatomic) SystemSoundID hitSound;
@property (nonatomic) SystemSoundID missSound;
@property (nonatomic) SystemSoundID clapSound;
@property (nonatomic) SystemSoundID explodeSound;
@property (nonatomic) SystemSoundID booSound;
@property (nonatomic) SystemSoundID holycowSound;
@property (nonatomic) SystemSoundID boingSound;
@property (nonatomic) SystemSoundID metalSound;
@property (nonatomic) SystemSoundID gotlifeSound;
@property (nonatomic) SystemSoundID missileSound;

@property (nonatomic, retain) NSTimer *gameTimer;
@property (nonatomic, retain) NSTimer *backgroundTimer;
@property (nonatomic, retain) NSTimer *harderTimer;

@property (nonatomic, retain) NSMutableArray *rainDrops;

- (void) initTimer;
- (void) playGame:(NSTimer *)timer;
- (void) adjustBackground:(NSTimer *)timer;
- (void) makeItHarder:(NSTimer *)timer;

- (void) initBricks;
- (void) initLives;
- (void) initRain;
- (void) moveRain;
- (void) hideRain;
- (void) initExplosion;
- (void) initAudioStreams: (SystemSoundID *)soundId: (NSString *)soundFile: (NSString *) type;
-(void) playAudio: (SystemSoundID) soundId;
- (void) resetAlphasforLives:(int) livesVal forBricks:(int) bricksVal ;
-(void) explodeBrick: (int) y : (int) x;
- (void) initBrickLayout;
- (void) launchMissile;
- (void) saveState;

@end
</pre>
<h3><strong>Let&#8217;s break it down</strong></h3>
<pre class="brush: objc; title: ; notranslate">
#import &lt;UIKit/UIKit.h&gt;
#import &lt;AudioToolbox/AudioToolbox.h&gt;
#import &quot;GBMusicTrack.h&quot;				// Using GBMusicTrack to play background MP3 (does NOT work in simulator)

#define BRICKS_ROWS 8
#define BRICKS_COLUMNS 7				// dimensions of the matrix of bricks

#define BRICKS_IMAGES 5					// I have 5 different brick images which can represent different powers
#define LIVES  8						// Maximum lives you can have
#define GAME_LEVELS 4					// Let's start with 4 levels

#define NORMAL_BRICK 1
#define METAL_BRICK  2					// Metal bricks cannot be killed. You will bounce off sharply

#define SUPER_BRICKS 3					// Any brick ID &gt;=3 is a 'special' brick
#define LIFE_BRICK  3					// This one gives you a new life (if you are not at max life)
#define MISSILE_BRICK 4					// This one gives you 5 missiles with each hit

#define HACK_HITCOUNT 4					// What's a game without a hack? If hack mode is on, you get to next level
										// after 4 hits
</pre>
<p><strong><br />
</strong></p>
<p>We first import &#8220;AudioToolbox.h&#8221;. You need this file to play the audio files. We also import GBMusicTrack.h which is Jake&#8217;s class to play a background MP3.  Next follows some key #defines. While for the most part, the comments are self-explanatory, some commentary is due:</p>
<ul>
<li>The bricks matrix you see at each level is essentially a 2D array. BRICKS_ROWS and BRICKS_COLUMNS specify its dimensions</li>
<li>While the code currently uses 4 brick images to show different powers, I have 5 (1 for future use :)</li>
<li>Then, I use different values to depict which brick is &#8216;normal&#8217; and which brick is &#8216;super&#8217;. Why do I need this? You will see later, that for each level, I design a 2D matrix of bricks and fill in the values 1-4 so that when a ball or a missile hits that brick my game knows what to do (just explode, give you missiles, give you a life etc.)</li>
<li>Finally, I&#8217;ve added a &#8216;developer mode&#8217;.If you triple tap the lower left corner of the screen, you get a &#8216;pac-man on fire&#8217; icon that tells you that you don&#8217;t need to shoot/hit all the bricks to get to the next level. HACK_HITCOUNT defines the number of bricks that need to be killed before you progress to the next level.</li>
</ul>
<pre class="brush: objc; title: ; notranslate">

@interface BricksViewController : UIViewController &lt;UIAccelerometerDelegate&gt;
{

	NSTimer *gameTimer;					// used for the primary game logic (update ball, check hits etc)
	NSTimer *backgroundTimer;			// used to animate backround sprites - cloud and missile movement
	NSTimer *harderTimer;				// after MAKE_IT_HARDER seconds, this will be called so we can step up the game difficulty

	IBOutlet UIImageView *ball;					// will hold the ball as it bounces around
	IBOutlet UIImageView *paddle;				// will hold the paddle
	IBOutlet UIImageView *cloud;				// well, obviously, the cloud in the background
	IBOutlet UILabel *labelScore;				// holds the latest score shown on top right
	IBOutlet UILabel *labelGameOver;			// hidden by default, will showup in center as text when game is over
	IBOutlet UILabel *labelPause;				// text to display when paused
	IBOutlet UIImageView *explodeView;			// will hold explosion images
	IBOutlet UIImageView *backgroundImageView;	// holds the game background wallpaper
	IBOutlet UILabel *labelCurrentLevel;		// Text to display level on screen
	IBOutlet UIImageView *haveMissileView;		// Will show a missile at lower right when you have missiles
	IBOutlet UIImageView *hackView;				// Will show an icon at lower left when hack mode is on
	IBOutlet UIImageView *volumeView;			// swaps between volume on and off image - lower center
	IBOutlet UIImageView *infoView;				// displays the info button
	IBOutlet UIImageView *helpView;				// displays the help screen when you tap the info button
</pre>
<ol>
<li>First, you will notice that my class derives from UIViewController (which is what Xcode generates when you select a View based application. But in addition, since I want to also be able to detect accelerometer movement (to move the paddle), I need to tell iPhone that this class will also implement the mechanics required to receive accelerometer events which is what  achieves. You can read up on protocols, delegates and the general iphone architecture model if you don&#8217;t know what this means. Google for these words.</li>
<li>Next up, we declare 3 timers. these timers will be triggered for different purposes. gameTimer is triggered 30 times a second to determine state of the game (collisions, hits, etc). backgroundTimer will be called 30 times a second as well to animate the game background as well as move a missile when fired (more on this later)</li>
<li>harderTimer is called once in 60 seconds to &#8216;step up&#8217; the difficulty of a level (right now, it will increase the ball speed)</li>
<li>Next up, we define a whole bunch of UIImageView related variables that will point to various objects on the screen. I&#8217;ve used Interface Builder to create the initial screen for almost all of the images, with the exception of the bricks themselves that are dynamically created according to the level in code. Pretty much everything else is created in IB.</li>
</ol>
<pre class="brush: objc; title: ; notranslate">

// various sound events depending on what event occurs.

	SystemSoundID boingSound;
	SystemSoundID clapSound;
	SystemSoundID missSound;
	SystemSoundID hitSound;
	SystemSoundID explodeSound;
	SystemSoundID booSound;
	SystemSoundID holycowSound;
	SystemSoundID gotlifeSound;
	SystemSoundID missileSound;
</pre>
<ol>
<li>Next up, we have various handles to sound files that will be played when an event occurs in the game. Each sound is a WAV that these variables will point to. boing is when the ball bounces off the edges of the screen; clap is when you complete a level; miss is when your paddle misses the ball; hit is when it, er, hits; explode is when a missile or the ball hits a brick;  boo is when all your lives finish; holycow is when &#8216;harderTimer&#8217; is called (its an indication that the level just got faster); gotlife is when you hit a brick that gives you a life; missile is when you launch a missile. Whew! this was tough explanation&#8230;</li>
</ol>
<pre class="brush: objc; title: ; notranslate">

CGPoint ballSpeed;								    // holds the speed at which the ball will move
	CGPoint paddleSpeed;								// holds the speed at which the paddle will move
	int score;											// holds latest score - this is used by labelScore to display
	float touch;
	int livesleft;										// if this goes to 0, you are dead.
	int gameLevel;										// your current game level
</pre>
<ol>
<li>Comments are self-explanatory. Basically, paddleSpeed controls the ball movement. Depending on what the ball hits, its X and Y co-ordinates will be manipulated and later the ball will be moved relative to its current position based on the X,Y values of paddleSpeed</li>
<li>I&#8217;m sure you have figured out the rest</li>
</ol>
<pre class="brush: objc; title: ; notranslate">
UIImageView *bricks[BRICKS_ROWS][BRICKS_COLUMNS];	// will hold the X*Y array of brick images
int brick_description[BRICKS_ROWS][BRICKS_COLUMNS]; // will hold the brick format and powers
</pre>
<ol>
<li>These two arrays are the heart of how bricks are displayed and controlled.</li>
<li>bricks is a 2D array that holds the actual brick images for a level (hence it is an array of UIImageView &#8211; each brick is an ImageView layer)</li>
<li>brick_description in a 2D array of the same size and holds integral values that define the &#8216;brick power&#8217;</li>
<li>You will see later that to draw the bricks, we look a nested for loop, and for each row/column, we will first read the brick_description_value (no brick, normal brick, steel brick, life brick, missile brick) and then display the appropriate image</li>
<li>In other words, by simply changing the brick description array, we can create a new layout for every level with the same rendering code</li>
</ol>
<pre class="brush: objc; title: ; notranslate">

	UIImageView *lives[LIVES];							// holds the display of lives on top left
	UIImageView *missileView;							// hold the missile Image
	NSString *backgroundArray[GAME_LEVELS];				// holds different background images for levels
	NSString *brickImages[BRICKS_IMAGES];				// holds the different brick images
	NSMutableArray *explodeImages;						// holds the sequence of images for an explosion
	NSMutableArray *rainDrops;							// holds the rain drops that are displayed on the screen
	GBMusicTrack *song;									//background music

	int tBallSpeedX ;				// used temporarily for one bounce
	int tBallSpeedY ;				// used temporarily for one bounce
	int kBallSpeedX ;
	int kBallSpeedY ;
	int kMakeItHarder;				// Time to make things harder in the game
	int kGamePause;					// if 1 then game freezes
	int kHackHitCount;				// HACK MODE: if 1, then we can skip levels just after 4 hits
	int kMissileFiring;				// 1 if a missile has launched. We only allow 1 missile at a time
	int kMissilesLeft;				// when 0, your missile power is done
	int kVolumeIsOn;				// toggles volume on and off

}
</pre>
<ol>
<li>Some commentary here incase comments are not clear enough: as I mentioned, we have different background images per level, so backgroundArray will hold the names of those images</li>
<li>the explodeImages array will hold the 34 odd explosion sprites that we need to animate on top of a brick that is hit</li>
<li>rainDrops is basically an array of around 50 rain drops that we will animate and move on the screen for some levels</li>
<li>song will hold a pointer to the mp3 file that will play in the background</li>
<li>tBallSpeedX and Y and values that we fill in when you hit a steel brick. Basically, when we compute the next ball position, we take the current position+ball speed+tBallSpeed. In effect what that means is that the ball will bounce faster when you hit a steel brick. Then, when the ball bounces off the screen, we make tBallSpeedX and Y zero. Effectively implying that the ball will shoot out if you hit a steel brick and then reset back to normal speed after it hits a screen edge.</li>
<li>kMakeItHarder holds the time in seconds after which the ball speed will be bumped up (in other words, harderTimer is invoked kMakeItHarder seconds later)</li>
<li>kMissileFiring &#8211; will be set to 1 when you launch a missile. When 1, we will not allow another missile to be fired. When the missile hits a brick, or, goes off screen, then this value is reset, so we can fire again</li>
<li>kMissilesLeft &#8211; when you hit a missile brick, you get 5 missiles. When you shoot a missile, this variable keeps decreasing by one.</li>
</ol>
<pre class="brush: objc; title: ; notranslate">
@property (nonatomic, retain) UIImageView *ball;
@property (nonatomic, retain) UIImageView *paddle;
@property (nonatomic, retain) UIImageView *cloud;
@property (nonatomic, retain) UIImageView *explodeView;
@property (nonatomic, retain) UIImageView *backgroundImageView;
@property (nonatomic, retain) UIImageView *missileView;
@property (nonatomic, retain) UIImageView *haveMissileView;
@property (nonatomic, retain) UIImageView *hackView;
@property (nonatomic, retain) UIImageView *volumeView;
@property (nonatomic, retain) UIImageView *infoView;
@property (nonatomic, retain) UIImageView *helpView;

@property (nonatomic, retain) UILabel *labelScore;
@property (nonatomic, retain) UILabel *labelCurrentLevel;
@property (nonatomic, retain) UILabel *labelGameOver;
@property (nonatomic, retain) UILabel *labelPause;
@property (nonatomic) SystemSoundID hitSound;
@property (nonatomic) SystemSoundID missSound;
@property (nonatomic) SystemSoundID clapSound;
@property (nonatomic) SystemSoundID explodeSound;
@property (nonatomic) SystemSoundID booSound;
@property (nonatomic) SystemSoundID holycowSound;
@property (nonatomic) SystemSoundID boingSound;
@property (nonatomic) SystemSoundID metalSound;
@property (nonatomic) SystemSoundID gotlifeSound;
@property (nonatomic) SystemSoundID missileSound;

@property (nonatomic, retain) NSTimer *gameTimer;
@property (nonatomic, retain) NSTimer *backgroundTimer;
@property (nonatomic, retain) NSTimer *harderTimer;

@property (nonatomic, retain) NSMutableArray *rainDrops;
</pre>
<ol>
<li>Standard stuff. I sort of copy-pasted here. Likely the @property settings need a relook.</li>
</ol>
<pre class="brush: objc; title: ; notranslate">

- (void) initTimer;
- (void) playGame:(NSTimer *)timer;
- (void) adjustBackground:(NSTimer *)timer;
- (void) makeItHarder:(NSTimer *)timer;

- (void) initBricks;
- (void) initLives;
- (void) initRain;
- (void) moveRain;
- (void) hideRain;
- (void) initExplosion;
- (void) initAudioStreams: (SystemSoundID *)soundId: (NSString *)soundFile: (NSString *) type;
-(void) playAudio: (SystemSoundID) soundId;
- (void) resetAlphasforLives:(int) livesVal forBricks:(int) bricksVal ;
-(void) explodeBrick: (int) y : (int) x;
- (void) initBrickLayout;
- (void) launchMissile;
- (void) saveState;

@end
</pre>
<ol>
<li>Finally, we declare some of the internal functions of the game class. I&#8217;ll explain them all later in the implementation file.</li>
</ol>
<h1>End of Part I</h1>
<p>Well, that&#8217;s it for now. I hope you are getting a good sense of the &#8216;implementation direction&#8217; by going through the .h. In the next part of the tutorial, I will dissect the implementation of each function as well as post a ZIP file for you to download the project and files.</p>
<h1>In the meantime&#8230;</h1>
<p>If you are a pro, or a better beginner than me, feel free to leave comments here on what mistakes you may have already spotted. Thanks.</p>
<h1>On to Part II &#8211; the Implementation</h1>
<p>Click <a href="http://blog.roychowdhury.org/2010/10/26/tutorial-iphone-game-programming-professional-bricks-part-ii/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.roychowdhury.org/2010/10/25/tutorial-iphone-game-programming-professional-bricks-part-i/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

