755 Beginning iOS Game Development


4 months ago
Full text


  Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties withrespect to the accuracy or completeness of the contents of this work and specifi cally disclaim all warranties, including without limitation warranties of fi tness for a particular purpose. The fact that an organization or Web site is referred toin this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or website may provide or recommendations it may make.

ISBN: 978-1-118-10732-4

  Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties withrespect to the accuracy or completeness of the contents of this work and specifi cally disclaim all warranties, including without limitation warranties of fi tness for a particular purpose. The fact that an organization or Web site is referred toin this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or website may provide or recommendations it may make.


  Since then, he has written software using every language and hard- ware platform that he could get his hands on, including a brief and painful foray into Fortran on a VAX system during his engineering education. Currently, he is focused on developing connected applications and games for mobile devices such as the iPhone and iPad.


  He now enjoys developing games for the iPhone and iPad, and currently has four games in the AppStore (Woridgo, Jumpin’Java, Kings Battlefi eld, and Set Pro HD). I would also like to thank all of the other edi-torial and production staff that put many hours into this project to help get it to print.


3 What Makes a Good iOS Game? 4 Device Usage 4 Use Unique Features of iOS 4 Make Your Game Fun 5 Graphics and Design 6 Developing Your Idea 6 Documenting Your Game 6 Prototyping Your Game 7 Preparing to Code 8 Game-Related Frameworks 9 Cocoa 9Drawing: UIKit and Core Graphics 11 User Interaction: Cocoa Touch 12 Animation: Core Animation 12 Sound: Core Audio 13 Game Kit 14 Summary 14


17 The Coding Environment 18 Creating a Project 19 Navigating Your Project 22 The Navigator Area 22 Navigating by Symbol 23 Searching Your Code 23 Viewing Code Issues 24 Examining Logs 24 Editing Your Code 25 Code Coloring 25 Indentation and Snippets 26 xvi CONTENTSFix-it 28 Integrated Help 50 Operators 51 Assignment Operators 77 Pointers 82 A Game Example 75 Breaking Up Code with Functions 74 Choosing an Option with switch 73 The Conditional Operator 73 The if Statement 72 Execution Flow and Decisions 64 while and do…while Loops67 break and continue Loops 64for Loops 55 Scope 55 Structures 56Arrays 61 54 Logical Operators 54 Relational Operators 52 Arithmetic Operators 47 Extending the Data Types 28 Using the Jump Bars 47 Generating Output and Accepting Input 46 Variables 47 Base Data Types 46 Data Types 45 Variables and Expressions 45 Introducing C CHAPTER 3: THE C PROGRAMMING LANGUAGE 36 Summary 42 35 Building a Simple Interface 31 Additional Breakpoint Features 31 Breaking and Stepping through Your Code 30 Xcode Debugging Tools 29 The Assistant Editor 85 Summary 91 CONTENTS


95 Classes and Objects 96 Instance Variables 97 Methods and Messages 98 Managing Memory104 Automatic Reference Counting 106 Inheritance 107Building Subclasses from a Base Class 107 Overriding Base Class Methods 110Polymorphism 111 Building a Game in Objective-C 114Exposing Class Data with Properties 115 Declaring a Property 115 Accessing a Property117 Class Methods117 Implementing the MindPlayer 119 Building the Game Loop127 Summary 134

CHAPTER 5: THE COCOA FOUNDATION FRAMEWORK 137 Model-View-Controller Architecture 138 Your First iOS Game

138 Building the UI140 Outlets and Actions140 Handling Text with NSString 144NSString Methods 144 Mutable and Immutable Types 144String Comparison 145Collecting Objects with NSArray 146 NSArray Methods146 Modifying Arrays by Using NSMutableArray 147 Wrapping Numbers with NSNumber 147 Other Collection Classes148 NSSet 148 NSDictionary 148Building the Game Model 157 Periodic Events and Timers162 Summary 169 xvii xviii CONTENTS 219The Event Architecture 267 Property Animations256 Transition Animations CHAPTER 8: ANIMATING YOUR GRAPHICS 251 Animating Images with UIImageView 252 Introducing Core Animation255 A Brief Introduction to Blocks 255 Animating UIView Properties and Transitions 256 247 Summary 249 222Building a Simple Touch-Based Game: Simon Says 225 Responding to Motion with the Accelerometer 241 Recognizing Gestures 220 Event Objects221 Handling Multitouch Events Animation and Timing with CADisplayLink 206 Finishing the Blocker Game215 Summary 217 PART II: GAME BUILDING BLOCKS CHAPTER 6: DRAWING WITH UIKIT AND CORE GRAPHICS 173 Introducing the Drawing Frameworks 173 UIKit 174 Core Graphics175 198 The View Hierarchy199 197The Image Classes Shadows 186 Gradients 188Starting the Blocker Game with the BlockView 192 Working with Images Specifying Colors with UIColor 178Advanced Drawing with Core Graphics 186 The drawRect: Method176 Drawing Shapes with UIBezierPath 177 The Graphics Context175 The UIView Coordinate System 176 The Drawing Environment175


CONTENTS Core Animation Basics275 Layer Layout276 Animatable Properties276 Layer Trees282 Summary 285 CHAPTER 9: MAKING NOISE WITH IOS AUDIO APIS 289 Playing Simple Sounds with the System Sound Services 290 Playing Sounds with the AV Foundation Framework 291 The AVAudioPlayer Class291 Format and Performance Considerations 292 Confi guring the Audio Session 293 Playing Multiple Sounds Simultaneously 313Looping Sounds 313Media Player Framework 322 Summary 330 CHAPTER 10: BUILDING A NETWORKED GAME WITH GAMEKIT 333 Introducing GameKit333 Starting Out334 Networking Your Game 351 NSData and NSCoding352 Converting Classes to Data with Archives 353 Connecting and Sending Data 354 Running the Game364 Summary 366 APPENDIX: ANSWERS TO EXERCISES 369 INDEX 385 xix INTRODUCTION


  Once you learn some of the key fundamentals, you should be able to pick up and run with any of the core technologies and this book will help you to get there. I think that the best way to learn is by doing, and by working along with the game examples in this book, you will learn how to useApple’s tools to build games.


  Even though the book assumes some pro-gramming experience, I feel that someone with very little to no experience could pick this title up and use it as a starting point for beginning the journey into the world of game programming. By the end of this book, youwill have written several games and you will have experience with many of the frameworks that you can use to draw graphics, perform animation, work with sound, and handle user input.


  In the fi rst part of the book, I cover the absolute basics that you need to know in order to write any iOS program, game or not. After you are fi nished working through the examples, you can enhance these games on your own to learn more about the technolo-gies discussed in the chapter.



  Sure, you can use thebook as a reference guide to the APIs that I cover when you are done, but I tried to write the book in a way that gently guides the reader from one topic to the next. If you intend to run your games on a device such as the iPhone or iPad, as opposed to running your code in the iPhone simulator, you will need to join the iOS developer program.


  You will fi nd the code snippets from the source code are accompanied by a note indicating the name of the program, so you know it’s available fordownload and can easily locate it in the download fi le. Once at the site, simply locate the book’s title(either by using the Search box or by using one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.


  In January of 2011, Apple released a list of the top-selling applica-tions on the App Store: Getting an overview of the game-related frameworks in iOSSince you have picked up this book and are reading this, you must be interested in writing a game for iOS. Use Unique Features of iOS Some other factors that you should consider when designing your iOS game is how a player will con- trol the game and how you can take advantage of the advanced features of iOS devices.


  Therefore, a goodapplication defi nition statement may be something like: “The purpose of this project is to implement the game of chess with features geared toward teaching a beginner the basics of the game.” Developing Your Ideax Once you have your application defi nition statement, you are ready to start defi ning the features that you will implement in your game. For a beginner’s chess game, you may come up with a feature list like this: ‰ Implement the correct rules of chess.‰ Provide the ability for the player to undo moves.‰ Give the player a way to ask the computer for suggested moves.‰ Show the player legal moves for any selected piece.‰ Build a computer opponent that can adapt to the player’s skill level.


  Continue to work with this document to refi ne the size of your game elements. When you are fi nished, you will have a fi lethat you can use to estimate the correct size and position for the graphics in your game.


  For instance, in the Blocker game that you will buildlater in the book, you will draw the ball in a slightly different position in each frame, giving your game the illusion of motion. The peer-to-peer network framework does not specify the format of the data that you can exchange between the devices on the network, so youhave a large amount of fl exibility in developing a data format that works for your game.

2 The Xcode Programming Environment WHAT YOU WILL LEARN IN THIS CHAPTER:

  Aside from the capabilities of an advanced text editor, a good IDE provides you with addi- tional tools that help you with the software development process. However, you will do all of your development for iOS using the Xcode IDE, so it is very important that you take the time now to learn how to use it.


  The Coding Environmentx FIGURE 2-9: Quick help popover The quick help provides the name of the function, its declaration, which iOS versions support it, a short description of the method, the header in which the function is declared and a link to the com-plete reference documentation. If you look in the Jump bar in the right-hand pane, you will see that the fi rst entry in the Jump bar says,“Counterparts.” This indicates that the Assistant editor is showing the counterpart to the fi le in the main editor.


  You should see the follow- ing text appear in the Console area: 2011-08-01 19:54:37.879 FirstProgram[1479:ef03] 0 This is the output of the NSLog statement during the fi rst pass through the loop when the value of i is zero. Try adding a breakpoint to the NSLog statement with the condition i%10==0 and the log message “@i@ is divisible by 10.” Run the application and you will see that every time that the value of i is divisible by 10, Xcode breaks and prints your message to the log.

15. Now you are ready to implement your code. Do not worry if the code is confusing or

  seems strange; you will learn all about the Objective-C syntax later on in the book. In the ViewController.h header fi le, add an int variable to hold your counter.

CHAPTER 2 16. In the Navigator area, or by using the Jump bars, navigate to the ViewController.m implementation fi le. In this fi le, you will write the code to react to the user tapping the button or moving the slider

17. Find the viewDidLoad method and add the following code below the call to [super viewDidLoad];

  buttonPressed method to increment the counter when the user presses the button like this: Building a Simple Interfacex How It Works After you created your project, the fi rst thing that you did was to open the .xib fi le that holds your user interface. The buttonPressed: method fi rst increments the counter by using the operator: ++ // Increment the countercounter ++; Then, you updated the label by using the same code as in the viewDidLoad method: // Update the label using the outletself .


  INTRODUCING C The C language is rooted in the PDP-7 assembler language that the creators of Unix used to write the fi rst version of the operating system. You can fi nd further information about the history of the development of the C language in an excellent online article by one of the original developers of the C language, “The Development of theC Language” by Dennis M.


  The amount of memory used by each data type is dependent on the platform that is running the code. At run time, the function replaces the formatting characters with the values that you passed.


  To use scanf , you pass a format speci- fi er like the ones you use with printf, along with the address of a variable that you will use to hold the value that the user typed. For example, to get an int value from a user, you would use thiscommand: scanf ( “Enter your age: %i” , &age); In this function, the %i is the format specifi er for an integer value and &age is the address of an int variable called age.

1. Start

  The */ in this code closes the comment and any code after it would not be considered a comment: /* comment/* The next lines use the I/O function printf to print the size of each type: print f ( “Size of int: %lu \n” , sizeof ( int )); As you learned above, you use the printf function to print formatted content to the console. The output should look like this:Size of int: 4 Size of char: 1Size of float: 4 Size of double: 8Size of short int: 2 Size of long double: 16 How It Works You can see that the amount of memory used by a short int is half of that used by an int and that a long double is twice the size of a double .

CHAPTER 3 Assignment Operators When you want to assign a value to a variable, you use an assignment operator. The most common

  For example, instead of adding 5 to the value in n and assigning it back to n by using a statement like this: n=n+5 ,you can prepend the addition ( + ) operator to the assignment operator and write the statement as n+=5 . You will now see the following at the bottom of the output: i: 0 i++: 0i: 1 i: 0 How It Works First, the code declares a variable of type int called i and sets it to 0: int i = ; Then, you print the value of i : printf ( “i: %i\n” ,i); Next, you use the postfi x version of the operator to increment and print i : ++ printf ( “i++: %i\n” ,i++); You can see that the value of i is used and then i is incremented.


  Subtraction - / Division Multiplication * % Modulus All of these should be self-explanatory with the exception of the modulus operator. You will see the modulus operator in use in the game example at the end of thischapter.


  You use the && operator to express that you need both parts of the statement to be true for the entire statement to be true. When you declare a variable at the beginning of a function, like the variable i in the main function in our example code, that variable is available from the point where you declare it onward, in thatfunction.

2. To make the point struct available to multiple functions in your code, you need to declare it outside

  Run the program and you should see the following output in the debug output window: Upper Left -- x:3 y:4 Lower Right -- x:6 y:2 Upper Left -- x:5 y:7 Lower Right -- x:8 y:5How It Works The code fi rst declares the two points that will determine the location of your rectangle: struct point ul; struct point lr; You declare struct variables by using the keyword struct followed by the type name, the variable name, and then a semicolon. After printing the coordinates, the code moves the rectangle: // Move the rectangle right 2 units and up 3 unitstheRectangle.upperLeft.x += 2 ; theRectangle.upperLeft.y += 3 ;theRectangle.lowerRight.x += 2 ; theRectangle.lowerRight.y += 3 ; You can see that the code uses the += operator to increment the x positions of each point by two and the y positions of each point by three.

2. Replace the code in the main.c fi le with this:

  Finally, you used the printf function to print out the contents of the fi rst card in the deck, the ace of spades: printf ( “The first card is %s of %s\n” , deck[ ].value, deck[ ].suit); A nice feature of using arrays is that you can refer to the items contained in the array by index. In the body of the loop, you are printing out the contents of the array at location index i : printf ( “The card is %s of %s\n” , deck[i].value, deck[i].suit); Therefore, the fi rst time through the loop, i is 0 so you print out the value and suit of the 1st card in the array, i[0] , the ace of spades.

2. When you run this code, the output should be the same as you saw in the example above

  Often times you will want to use a for loops differ from while Where i++; printf ( “The card is %s of %s\n” , deck[i].value, deck[i].suit); How It Workswhile : i In the loop block, you printed out the value of the card located in the deck array at index while (i< 52 ) { Then you said that you wanted to execute the following code while i is less than 52: int i= ; and set it to 0: i loops. First, you declare the variable i to use as a counter and set it to 0: int i= ; Next, you b uild the body of your loop: do { In the loop, you generate two random numbers between 0 and 51 that you will use as indexes into the deck array: // Generate 2 random numbers to determine which cards to swaprandomA = random() % 52 ; randomB = random() % 52 ;31 The random function returns a random number between 0 and 2 ⫺1.


  If none of the cases matches, the code in the default case runs and you will see the normal output: default :printf ( “The card is %s of %s\n” , deck[i].name,deck[i].suit);break ; Here is the output from when I ran the program: The king of the world (spades) The ace of diamonds is great! The card is four of spades The card is two of diamondsThe king of the world (clubs) The card is ten of clubsA jack of all trades (clubs) The card is seven of diamondsThe card is ten of hearts The card is nine of spadesThe card is two of hearts The card is six of diamondsThe card is four of clubs A queen of the castle (diamonds)The ace of clubs is great!


  For example, you could write a function that adds two int s and returns their sum like this: int addInts ( int num1, int num2){return num1 + num2; } To call this function, a user would pass in the two numbers that they want to add and assign the return value to a variable like this: sum = addInts ( 4 , 5 ); This line would call the method addInts and pass in the values of 4 and 5 as parameters. Once inside the addInts function, the value of 4 is assigned to the parameter num1 and the 5 is assignedto num2 .

1. Under the defi nition of the card struct, defi ne a new shuffle function like this:

  You use the pointer dereferencing operator * to get the fi rst card fromthe deck and assign it to theCard : void printDeck( struct card* deck) { As you learned, the printDeck function receives a pointer to the fi rst element of the deck array, which is of type struct card , as its input parameter: How It Works // Dereference the pointer so that the theCard variable holds // an actual card. In the while statement, the arrow operator dereferences the pointer to the deck and gets the value mem-ber from the structure all in one step: while (deck->value!= ) { Likewise, in the printf statement, you use the arrow to dereference the deck pointer and obtain the name and suit values from the underlying structure:printf ( “The card is %s of %s\n” , deck->name,deck->suit); Then, you simply move to the next card in the deck by incrementing the pointer.

2. You will reuse the includes, card struct, and the shuffl e function, so leave that area of the fi le

  Delete all of the code in main after the deck array is declared and replace itwith the following code: // Create the player’s bank and start it off with 100 creditsint bank= 100 ;// Create a pointer to the deckstruct card* pDe ck = deck;// Create a variable to hold the betint bet= ;// Run the function to shuffle the deckshuffle(deck);// Run the game in a loop. Upon entering the loop, the code prints the number of credits in the player’s bank and then prints the fi rst card: // Print the amount of credits in the bankprintf ( “Your bank: %i\n” , bank);// Print the cardsprintf ( “The cards: “ );// First cardprintf ( “%s of %s “ , pDeck->name, pDeck->suit); Next, the code increments the pointer to the deck, pDeck , to move to the next card.

4 The Objective-C Programming Language WHAT YOU WILL LEARN IN THIS CHAPTER:

  ‰ Understanding the relationship between C and Objective-C ‰ Learning basic object-oriented concepts like classes, objects, methods, and messages ‰ Building classes in Objective-C ‰ Managing memory Objective-C is a superset of C. Object-oriented programs can also beeasier to debug and modify because you encapsulate all of the functionality and data related to an object in the object itself.


  The concept of encapsulation is that you can contain all of the functionality of a class in the class FIGURE 4-2: Member variable scope itself without exposing the inner details to users of the class. For example, con-sider the following C function to defi ne a rectangle with two points, x1, y1 and x2, y2: void defineRect (int x1, int y1, int x2, int y2) Callers of this function would call it like this: defineRect (20,30,60,120) Without knowing the defi nition of the function, it is impossible to tell what the 20, 30, 60, and 120 represent.

6. Switch to main.m and replace the existing code with this:

  The fi rst thing that the header does is import the Foundation.h header: #import <Foundation/Foundation.h> You may remember using the #include statement in the last chapter to inform the compiler about some of the functions that you would be using. However, if you plan to put an autoreleased object into an instance variable for access at a later time, you have to call retain on it or else it will be de-allocated at the end of the run loopand your application will crash when you try to send a message to the de-allocated object.

11. In the main function, change the greenHouse to be a Colonial instead of a House like this:

  The MindPlayer tells the playertwo things: ‰ How many pegs are the correct color and in the correct position ‰ How many pegs are the correct color, but not in the correct positionThe MindPlayer needs to report only on each instance of the pegs that the player has guessed. Using the information that the MindPlayer has revealed, MindPlayer the player attempts to deduce the MindPlayer’s pegs.rack Peg The game is over when the player has either the correct color To implement the game, you will build two classes as you can see in Figure 4-5.


  Open the Peg.h header fi le and add the pegWithColor method declaration below the color prop- erty declaration: Switch over to the Peg.m implementation fi le and add the implementation of the pegWithColor: method below the compiler directive that synthesizes the color property: // Create the pegPeg * thePeg = [[ Peg alloc ] init ]; // Set the peg’s colorthePeg. Open the MindPlayer.h header fi le and replace the contents with the following code: #import <Foundation/Foundation.h> #imp ort “Peg.h”@interface MindPlayer : NSObject { // An arrray to hold the rackPeg * rack[ 4 ]; }// Pick the pegs for the rack // Check the guess against the rack // Return rack string to print // Clean up the memory used by the rack @end 7.

Dokumen baru

Aktifitas terkini

Download (435 Halaman)


1243 Beginning Ios 3D Unreal Games Development 1242 Beginning Facebook Game Apps Development Beginning Android™ Application Development Game Ios Untuk Apple App Store 860 Beginning Android Web Apps Development Beginning App Development Tensorflow Keras Pdf Ios 832 Beginning Windows Phone 7 Application Development 1563 Beginning Microsoft Visual Studio Lightswitch Development Pembuatan Game Ksatria Wasis Gamelan Jawa Berbasis Ios Bab
Show more