Skip navigation

Category Archives: Game Implementation

It took an entire day to get In-App purchases to work.  TOTALLY unnecessary.  Apple’s docs on the subject are worthless, so I figure it’s time for another Coding Help Blog Post ™.

Alright, so getting a store in place is a bit involved, but I’ll do my best:

Include the StoreKit framework in your project and apply the appropriate #import.  In your main view controller, you will want to begin querying the App Store for product information as soon as possible so you can store the returned information before it’s needed to avoid network traffic slowing your user down.  You will also need to set up transaction observation in order to receive payment information.  To do this add the following lines to your main view controller:

NSSet* productIDs = [NSSet setWithObject:@”com.yourcompany.yourapplication.####”];
SKProductsRequest* productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers: productIDs];
[productsRequest setDelegate: self];
[productsRequest start];
[[SKPaymentQueue defaultQueue] addTransactionObserver: self];

This will ping the App Store for product information pertaining to the product IDs associated with the productIDs given in the set.  When the request receives a response, it will call your view controller’s -productsRequest:didReceiveResponse: method.  In this method, you will want to store the products array provided by the response object.  In this method, you should also check the invalidProductIdentifiers property of the response object to make sure that everything made it through and to respond otherwise.

You can use the information from the response array to populate your GUI and allow users to purchase.  Once the user has chosen a product to buy you will have to intercept their choice and send out for App Store information.  To do this, you create a payment object with the desired product ID and send that out to the App Store.  That will look something like this:

SKPayment* thePayment = [SKPayment paymentWithProduct: someProduct];
[[SKPaymentQueue defaultQueue] addPayment: thePayment];

This method will ping the server with a payment request or a test request if you are using the sandbox.  The request will return to your -paymentQueue:didUpdateTransaction: method.  In here you need to determine the state of the payment object that the update returned.  To do this, iterate over all of the transactions while switching on their transactionState property.  Upon SKPaymentTransactionStatePurchased, you will need to validate the receipt information, begin downloading, and close out the payment.

Most important of these is receipt validation.  To do this, create a string using the returned transaction’s receipt data and turn that into a string.  This string is actually a JSON object which can then be passed to your PHP server (or whatever) to be then forwarded to the App Store for receipt validation.  Your code will probably look something like this:

NSString* jsonObjectString = [YourClass encode: (uint8_t*)[[transaction transactionReceipt] bytes]  length: [[transaction transactionReceipt] length];

NSString* completeString = [NSString stringWithFormat: @””, jsonObjectString];

NSURL* urlForValidation = [NSURL urlWithString: completeString];

NSMutableURLRequest* validationRequest = [[NSMutableURLRequest alloc] initWithURL: urlForValidation];

[validationRequest setHTTPMethod: @”GET”];

NSData* responseData = [NSURLConnection sendRequest: validationRequest  returningResponse: nil  error: nil];

NSString* responseString = [[NSString alloc] initWithData: responseData encoding: NSUTF8StringEncoding];

int success = [responseString intValue];

You will have to add the following code to your project.  It’s recommended you put this code in as a category to NSString, but it can be place pretty much anywhere.  The following code can be found here: at the bottom.

+ (NSString*) encode:(const uint8_t*) input length:(NSInteger) length {
    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;

    for (NSInteger i = 0; i < length; i += 3) {
        NSInteger value = 0;
        for (NSInteger j = i; j < (i + 3); j++) {
            value <<= 8;

            if (j < length) {
                value |= (0xFF & input[j]);

        NSInteger index = (i / 3) * 4;
        output[index + 0] =                    table[(value >> 18) & 0x3F];
        output[index + 1] =                    table[(value >> 12) & 0x3F];
        output[index + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[index + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';

    return [[[NSString alloc] initWithData:data
                                  encoding:NSASCIIStringEncoding] autorelease];

This will encode your JSON string to Base64, which can then be passed to your server and on to the App Store for validation.

The variable ‘success’ can be anything your server wants to return to indicate success, but the App Store returns a 0 on success.

Hope that helps.  It was certainly a pain in the ass for me and my co-workers.  Good luck!


Had to present the delivery I made last week to the rest of the office today.  While I strongly support the deliverable, our presentation left a lot to be desired.  However, I feel that passing on the key points of the presentation are a good idea.

What went right: we tore up the user stories.  We hit pretty much every milestone with room to spare and didn’t really have to scramble to get our sprints finished on time.  Despite all of the interruptions that cropped up during development, we still delivered on time with some bits of fluff and padding to spare.

What went wrong: I consistently doubted the abilities and habits of the engineer who had worked on the project before me.  This meant that I frequently had to ask him stupid questions that were resolved with a single line of code, taking away valuable time from him.  Also, other projects kept getting in the way of our sprint.  Although we were able to still deliver with these interruptions, the other projects certainly didn’t help our development cycle and tended to distract our team.

Lessons learned: use the tools at hand to their greatest extent before bugging other people.  Use Command-F, use the debugger, use the internet.  Exhaust your resources before you call in other people to help mitigate your issues.

I don’t own the rights to The Matrix, so I can’t sell this.  However, I can put it in my portfolio and show it off to potential employers.  So take a gander and let me know what you think.  Alex, eat your heart out!

The Matrix Role Playing System

The last playtest went quite well.  The characters went against an agent and actually survived.  I let them run away in the end, but if they had stayed to fight they probably would have all died.  Which is good.  It shows that Agents are sufficiently nasty.

The playtest showed that this system is actually surprisingly balanced, interesting, and playable.  I’m REALLY pleased with how this worked out.  The only thing that really needs to change is some AP exchange rates.  And that’s it really.  I think experience points, AP, weapon damage, locations, movement, all that works pretty well at this stage.

All of the players have been begging me to continue using the system and actually set something up for it.  This is very encouraging and it’s probably the most powerful driving reward that I seek in game design: people loving your game and letting you know.

As far as setting something up to do more, I’m not sure what I can do.  I’m swamped with classes, I’m already in charge of 3 different clubs on campus, I’m going to FL for an internship over the summer.  I really WANT to continue using the system, but I’m not sure how much farther I can stretch myself.

I will be posting PDFs of all of the resources in the next post after I do some clean up.  Thanks to Tim, Malec, Jo, Mike, and Tyler for playtesting!

The playtest for the Matrix RPG went *very* well.  It’s reception was quite good, the players weren’t very serious about it, but they said that they really liked the system and the possibilities it presents.  One thing I’ve noticed is it’s decently complex, but that didn’t seem to matter to the players.  The reference material needs to be available for all of the players, and some values and other miscellaneous rules need to be ironed out.  In general though, I think the playtest went very well and I plan to continue playesting on Wednesday.

Also, I plan to pit the players against an Agent.  That’s right, a ridiculously overpowered nearly invincible dauntless death machine.  The recommended level for an Agent encounter?  10: the highest level possible.  The playtester’s  character’s level? 4.  Should be fun :).

I decided to go with the maze game for the iPhone/iPod Touch.  It will consist of a target that will either be circular or cuboid that the player must move to the end point using their fingers to guide it.  Touching a wall or object will set the target back to the last checkpoint.  I haven’t decided whether I want to implement lives or a timer.  I will try both and see which one playetesters enjoy more.  I think lives will be best, but that remains to be seen.  Simple game with some decent potential, here’s what I have for the “boring architecture part”:


  • Don’t need texture loading (that I can think of)
  • Simple style of colored shapes
  • View scrolling when the target gets to the edge of a defined area.
  • Will have to rebuild Radiance to make sure all of this works well.

User Interface

  • Basic Cocoa UI elements, using Radiance I can overlay what I need.
  • Want to experiment with different kinds of menus and UI displays.
  • Need to make sure view scrolling is adjustable.


  • Implementing Separating Axis Theorem which requires rebuilding Continuum.
  • Need to detect edge triggers for things like doors and victory conditions.
  • Unit test the crap out of my revamped vector system and rotation implementation.

Game Logic

  • Target resets to last checkpoint after (5) seconds of not being touched.
  • If the target touches an edge or another object, reset.
  • Timer?  Lives?  TBA
  • Later levels will have the target orbit the touch point.
  • Later levels will have multiple targets.
  • Later levels will have multiple targets with independent end points.

Level Builder

  • Grid system to start, build level with “positive” tiles on negative background.
  • Want to implement this in Lua to allow for greatest flexibility.

So, that’s pretty much the gist of it.  I have a lot of work to do.  Already rebuilt the vector class I was using to be a little more friendly.  Looking into SAT implementations.  I understand the concepts, but I’m unsure about implementation.  This is gonna be a lot of work at a difficult time.  Cross your fingers…

A good friend of mine, Alex Haase, visited me this weekend and I told him about my idea for an evolution-based game/simulation to expose the mechanics of the evolutionary process and the complexity of homeostasis within a single organism as well as within an entire species. We collaborated to create a very detailed set of rules, environments, and implementations in order to achieve this end. I’m incredibly proud to present the method we came up with.


A given organism’s genetic code will be represented by an array of strings. This array will be arbitrary [8-80] in length, and the strings will also be arbitrary in length [1-256]. This will bring maximum storage for a single genetics table to (256 bytes * 80 / 1000 bytes/kb) 20.48kb. This is quite reasonable and represents a rather large amount of data. However, data in a real gene is not read from end to end. Different genes are spread out over the chromosome, including sections of inert and unused data. Upon generation of the genetics table, a gene map will also be created to determine where each gene sequence begins and ends. This will be represented by an array of arrays containing gene location objects which will hold table index, gene start, and gene end. In this way, the genetics table can be parsed for information dynamically without the possibility of easy user interpretation. Alex had suggested that patterns be evaluated for certain well-known advantageous traits (such as camouflage, cyst stasis, or territorial marking). I agree with a slight modification: the the pattern checking be based not on a specific, static pattern, but by recognition of stepped character differences (more about this later). These patterns will be stored in a dictionary (hash table) of trait expression objects.

So, the way all of these pieces come together is like so:

The genetic table generator will run, generating a table with random properties and values. Keep in mind, the strings will actually be evaluated on their ASCII values in relation to target values. More on this in a few. A simple genetic table might look something like this:

[0] -> Ysl74.,34,.9/\]2gg5D25][46

[1] -> IIb,berl3/64654=/+saddhrt9rh-9454y

[2] -> ?>wa/a’QR#M KGLcknw83_+++

The gene map will create an array containing information like this:

(Motility) [0] -> [0] -> {index: 2, start: 6, end: 15}

The trait generator will generate a table of traits looking something like this:

[“Hibernation”] -> {34, 123, 65, 19}

[“Poison”] -> {10, 99, 14, 29, 78, 16, 41}

The numbers in the trait expressions represent the difference from one character to the next. So a gene section with the ASCII difference between it’s first and second letters that is 10 would begin to qualify for the trait at index 1. The more of these sequential differences the gene satisfies, the stronger the trait will manifest. This kind of checking may be quite expensive, but we’ll have to see.

Genes will be evaluated against a randomly determined array of arrays of numbers to determine the organisms resulting fitness. Genes will be read using the gene map to concatenate all of the like genes together, and then the system will begin evaluating each gene based on it’s ASCII value. The randomly determined array works as a standard. The deviation from the standard by each character in the string goes towards the gene’s score. Then the length of the gene, the total score, and the number of standard elements are factored in to get the final score for that gene. So, say our Motility gene standard was 34-198-102, and we had a gene that was translated into ASCII with values 56-202-181-89-30-2-102. Well, 56 is closest to 34 and is off by 22, so the first score is 22. 202 is closest to 198 and off by 4 so the total so far is 26. 181 is closest to 198 and is off by 17, so the total score is 43; and so on. Normally I would do all the math, but I don’t feel like it right now. Let’s just assume that the total score is 116. We then calc the gene potency by dividing the maximum string capacity (255 * 7), 1785, by the total score to get 15.3879. We then divide this answer by the number of standard values (4), to get the final value of 3.8. This is a fantastically good gene value. Most values will have values between 1.2 and 2.8, but it will vary greatly.


Our first plan for the implementation focused on microbial life. It’s a great starting point, so that’s what I will present here and will be working with for a while. However, I hope expand to multi-cellular creatures at some point, because I feel this system has a lot of potential no matter what scale you work at. So, here are attributes used to describe an organisms capabilities and presence within the sim/game:

  • Offense: Determines the amount of damage the organism can deal to it’s target food source. Food sources will only relinquish food (or die) after a certain amount of damage has been dealt.
  • Motility: The speed at which the organism can move about. This value will be guaged on percentage of a maximum value.
  • Defense: The amount of physical damage resistance, representing cell wall composition or hide thickness etc.
  • Sensation: The degree to which the organism is aware of it’s surroundings.
  • Blending: The degree to which the organism can blend into it’s environment.
  • Health: Determines the maximum amount of damage the organism can sustain until it dies.
  • Metabolism: The percentage of energy the organism can glean from it’s food source.  A higher value allows for more energy output.
  • Storage: The amount of food the organism stores for later use.  Stored food also increases the organisms weight, requiring more energy to move.
  • pH Resistance: The range of pH values the organism can survive in.  If the organism is in an environment it is not resistant to, it will begin taking damage at a rate of (|resist – environment|).  This gives them time to move into suitable environs.
  • Radiation Resistance: The amount of radiation the organism can withstand without becoming ill.  Double this value will kill the organism outright.  Radiation always has a chance of damaging DNA, so rad resist is simply for living conditions.
  • Ion Resistance: The range of diluted ions that the organism can live in.  This attribute functions similarly to pH resistance.
  • Thermal Resistance: The heat range in which the organism can live.  This attribute functions similarly to pH resistance.
  • Redundancy: The number of copies of genetic code the organism possesses.  When something effects DNA (such as radiation damage or replication), a random copy will be selected.  This aids in radiation resistance and mutation resistance.
  • Regeneration: How quickly physical wounds and health are healed.
  • Sequencing: The speed and accuracy at which replication occurs.  Levels are stepped, providing more accuracy, then more speed, etc.
  • Diet:  This one’s tricky.  This attribute determines which food sources the organism can eat, which ones it cannot eat, and which ones are poisonous (should it eat it), including poisons from attacks and other biological agents.


In between each generation cycle, each organism will have active stats that will be taken into consideration while advancing state:

  • Health: The current amount of health the organism has.  If this falls to 0, it dies and can be therefore eaten.
  • Motility Modifier: This is directly effected by the organism’s health, decreasing as the organism is injured, allowing predators to  secure their prey more easily.
  • Energy: This is spent to perform different tasks, such as moving, digestion, attacking, regenerating, or reproducing.  Energy is gained through the eating and digestion of food.
  • Food Stored: The amount of food the organism has stored before it needs to feed again.
  • Health Modifier: This stat is directly effected by the organism’s radiation, pH, ion, and heat conditions.  If this modifier changes the organism’s maximum health to 0 or lower, the organism dies.
  • Conditions: This array stores the amount of ongoing radiation, pH, ion, heat, poison, physical, and other conditions that may be affecting the creature.


The ‘test’ environment for this sim/game will be a petri dish.  The environment will be filled with many different species of bacteria, and resources will be pretty readily available, just to make sure the system works.  However, as the scope of this project grows, environments will become much more realistic and interesting.

  • pH Balance: The acidity of the surrounds.
  • Ion Balance: The amount of dissolved ions.
  • Background Radiation: The amount of ambient radiation.
  • Ambient Heat: The amount of ambient heat in the environment.
  • Resource Pockets: These pockets of food will be scattered about randomly.

The environment will change, sometimes slowly, sometimes rapidly.  Many different events will occur to change the environment in one way or another to show how selective pressures change species.

So, that’s the idea for now.  I’m still trying to figure out how to make this into a fun and interesting *game* versus a interesting *simulation*.  Will give more details later.

A quick update on my game engine (did I forget to mention: I’m building a game engine) and the particle engine in specific:

My particle engine is not cooperating.  I finally have point sprites working, but loading in new textures for the sources corrupts my particle textures AND the source textures, so I’m at a total loss.  All attempts to start the engine over have failed for seemingly no reason, so I’m chopping up my original test to make it work better.  It seems that I will have to step back and redesign the architecture (again).

On a lighter note, I figure the particle engine is mostly fluff at this point, so game prototyping and stress testing will begin shortly.  I have many things I’d like to get in place before I start building real demo games, but simple prototypes will be small enough and simple enough to be able to ignore many of these improvements.

Wow, I’m really in over my head with this one, but the sense of achievement is unparalleled.  Anyway, I hope to have some news on the engine later (for those of you who care…).

Success! I have **FINALLY** gotten point sprites working correctly. After much struggling, frustration, and a slew of websites that offered little to no help whatsoever here is my answer:

To use textures with point sprites you need to do the following:

  1. Find out the limits of your point sprite implementation by using the glGetFloatv( GL_ALIASED_POINT_SIZE_RANGE, <float[2]>) call. This will populate your <float[2]> with the upper and lower limits for your texture sizes (generally, but not always, 1 and 64).
  2. Load in your texture, enable it’s type (I believe that it MUST be GL_TEXTURE_2D), and bind the texture.
  3. Enable GL_POINT_SPRITE_ARB and set attenuation, fade thresholds, and pass in the min and max sizes.
  4. Set texture coordinate replacement parameters using glTexEnvi( GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE).
  5. Specify your point size, using glPointSize(<float>) and (optionally, mostly for particle systems) turn off the depth mask.
  6. Call glBegin( GL_POINTS ), specify 3d vertices, and then glEnd.

Here is the exact code I am using. The loadPoTTextureFromImageNamed: call returns a texture containing GLuint data and a GL_TEXTURE_2D type. Other than that, it’s all pretty self explanatory. Let me know if you find something out of whack. Hope it helps!


//Make space for particle limits and fill it from OGL call.

GLfloat sizes[2];


//Create the texture we want to use.

BBSTexture* t = [BBSTexture loadPoTTextureFromImageNamed:@”Particle1.png”];

//Enable our texture type (in this case, it must be GL_TEXTURE_2D)

glEnable([t type]);

//Bind the texture data.

glBindTexture([t type], [t data]);

//Enable blending and set for particles


glBlendFunc(GL_SRC_ALPHA, GL_ONE);

//Enable point sprites and set params for points.


float quadratic[] =  { 1.0f, 0.0f, 0.01f };

glPointParameterfvARB( GL_POINT_DISTANCE_ATTENUATION_ARB, quadratic );

glPointParameterfARB( GL_POINT_FADE_THRESHOLD_SIZE_ARB, 60.0f );

//Tell it the max and min sizes we can use using our pre-filled array.

glPointParameterfARB( GL_POINT_SIZE_MIN_ARB, sizes[0] );

glPointParameterfARB( GL_POINT_SIZE_MAX_ARB, sizes[1] );

//Tell OGL to replace the coordinates upon drawing.


//Set the size of the points.


//Turn off depth masking so particles in front will not occlude particles behind them.


//Save the current transform.


//Begin drawing points.


//Iterate through our particles, setting the color and specifying their position.

for (Particle* p in particles)


glColor4f([[p color] magnitudeX], [[p color] magnitudeY] – [p lifespan], [[p color] magnitudeZ] – ([p lifespan] * 2), [[p color] magnitudeW]);

glVertex3f([p x], [p y], [p z]);


glEnd(); //Stop drawing points.

//Return to the previous matrix.



You are free to use this code in any manner you see fit.  Have fun with it!