Categories
Nerd Fun Programming Self Improvement

H@PPY N3W Y3@2 2015!

My Resolutions for 2015

  • Contribute to an open source project
  • Write a mobile app every month
  • Master VIM, GIT, and Make
  • Read all of Focus’ suggested computer science papers at least once 🙂
  • Write ALL the tests first! Roar!
  • Buy and read books printed on paper!

I’ll post weekly updates!

Categories
Cocos2d-iPhone Programming

Cocos2D-Swift 3.0: A great way to get started developing iOS games!

If you’re new to iOS game development now is a great time to get started. In 2008 a brilliant engineer named Ricardo Quesada rewrote his 2D game engine for Apple’s iOS and released it as open source. It’s no exaggeration to say that hundreds of games, like my own, were developed using Cocos2D—including dozens of hits. Now it’s 2014 and the newbie game developer has several versions of Quesada’s Cocos2D framework to choose from. But for me the branch of Cocos2D devoted to the iPhone and iPad will always have a special place in my heart. Clearly Cocos2D-iPhone (now called Cocos2D-Swift) was the inspiration for Apple’s SpriteKit framework. And once you learn the fundamentals of Cocos2D on iOS you can easily transfer these skills to Android, Windows, and HTML5 versions of the Cocos2d family. Working with Cocos2d-Swift is like “reading Shakespeare in the original Klingon.”

Learning iPhone Game Development with Cocos2d 3.0 by Kirill Muzykov is a book I wish I had when I was learning to develop my first iPhone game. Muzykov patiently covers all the basics (nodes, sprites, actions, text, sound, buttons, menus) and jumps into advanced topics (particles, physics, tile maps, iTunesConnect, Game Center, and in-app purchases) while guiding the reader though creating a game called CocosHunt and using important tools (Particle Designer, Texture Packer, Tiled) and websites (freesound.org, media.io).

Along the way the reader also learns about Objective-C, Xcode, and iOS APIs. You’re still a beginner by the time you finish Muzykov’s book but you’re a well informed beginner and ready to tackle larger and more complex projects—like the next Candy Crush.

One of the best things I like about Muzykov’s book is it’s structure. A typical chapter starts with setting up a project and cycles through segments entitled “time for action” and “what just happened?”. This alternating rhythm becomes a reliable way to digest the material and ensure the author doesn’t wave his hands over new concepts. Almost every chapter includes a pop-quiz. I’m not a big fan of quizzes but if that’s what you need to re-enforce the material Muzykov provides them.

The source code is clean and clearly written with good comments. Muzykov keeps the syntax simple, using “typedef enum” instead of “typedef NS_ENUM” and “#define” instead of “FOUNDATION_EXPORT NSString *const” which is probably for portability. Much of a game is managing state and game developer who follow Muzykov examples in his classes won’t get into trouble.

If you’re new to mobile game development and you want to focus on iOS then Learning iPhone Game Development with Cocos2d 3.0 is a good book for you.

Categories
Programming Sprite Kit

Sprite Kit, Retina, iOS7 and Getting It Right

I spent more time that I care to admit figuring out how to reconcile my old Dungeonators code with Apple’s Sprite Kit, Retina displays, and iOS 7. Along the way I searched the web for help and ran into tons of tutorials and advice for indy game developers (I highly recommend  www.raywenderlich.com for a great set of systematic and well written tutorials). But I learned to be wary of advice on some sites that is confused or actually wrong. For example I came across this macro in one of Ray’s tutorials that originated from a Stack Overflow conversation:

#define IS_WIDESCREEN ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )

This macro was written by a floating point math C macro professional. It’s used to determine if the resolution of an iPhone screen is 4 inches. iOS 7 only runs on iPhone’s with Retina displays but there are still  millions of iPhone 4 and 4s models in use with 3.5 inch screens. The iPhone 5, 5c, and 5s has a widescreen of 4 inches.

But why do I need a fancy macro for that? It’s code that I’m only going to run once. And it’s not a particularly CPU intensive calculation. And really, I want to understand what every line of code in my game does. Copy and paste code is always a bad idea.

It’s not hard to figure out what this macro does: It gets the height of the screen, subtracts the resolution of the 4 inch iPhone from it and makes sure the result is less than a number that is as close to zero as the phone’s floating point system can represent. However, there is no reason that we have to go to this level of complexity!

My feeling about macros is that you almost never need to use them. And if you do, call in a pro C programmer. Macros can optimize your code but if you don’t use the right number of parens you could end up with subtle side effects and bugs that are hard to track down.

As an added bonus this macro is only useful if you have determined that the iOS device your game is running on is an iPhone. Taken out of context this speedy line of code could give your game the wrong idea.

To do it right, as in doing it with code that is safe, maintainable, and as efficient as it needs to be, you have to understand how Apple internally represents the resolution of an iOS device. (I’m assuming you want your game to be universal across the Apple universe.)

So let’s say you want to write a universal iOS game in Objective-C using Sprite Kit. Here are the consequences of your decision:

  • Your game can only run on iOS devices running iOS7. This fact eliminates the original non-Retina iPhones but not non-Retina iPads
  • Your game must support both 3.5 and 4 inch iPhones.
  • Your game must support iPad and iPad Retina devices.
  • Don’t worry about model names! The name of the device (iPad, iPad Air, iPhone 5, iPhone 4s, iPadophone 7xyz) doesn’t tell you anything reliable about the number of pixels you have to play with.

Here’s the non-obvious part: You’re going to create your game with pixels in mind but Apple is going to give coordinates in points. I wish Apple had not done it this way. I guess they were trying to be helpful. At lest let developers turn of the points paradigm if like me, they find it unhelpful. But we can’t turn it off so we have to live with it!

Apple says there are 2 pixels in a point. This table should help:

Device Type    Pixels        Points      Models
iPhone 3.5"    960 x 640     480 x 320   iPhone 4, 4s
iPhone 4"      1136 x 640    568 x 320   iPhone 5, 5c, 5s
iPad           1024 x 768    1024 x 768  iPad, iPad Mini
iPad Retina    2048 x 1536   1024 x 768  iPad with Retina

Apple gives us a macro of it’s own to figure out if we’re running on an iPhone or iPad, UI_USER_INTERFACE_IDIOM() and a way to discover the screen’s dimensions in points,
[UIScreen mainScreen].bounds.size.height

Thus, here is a simple method that you can add to your game projects to figure out what sort of iOS device you’re running on based on it’s screen real estate.

- (NSString *)figureOutScreen {
    // Call once during initialization!
    NSString *result;
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        
        // iPhone
        
        if ([UIScreen mainScreen].bounds.size.height==568.0f) {
            
            // iPhone Retina 4-inch
            result = @"iPhone Retina 4-inch";
        } else {
            
            // iPhone filename 3.5-inch            
            result = @"iPhone Retina 3.5-inch";
        }
    } else {
        
        // iPad (Can't tell if it is mini, standard, or Retina 'cause all the dimensions in points are the same
        result = @"iPad";
    }
    return result;
}
Categories
Nerd Fun Programming

Getting Xcode and GitHub to work together like besties

Updated for Xcode Version 7.3.1 

Thanks to Jake for pointing out that his blog post needed a little freshening up!

After watching the WWCD keynote I wanted to fool around in Cocoa and Objective-C again. It’s been a while and my Xcode skills were rusty. One task that always seems tricky is getting Xcode’s local git repository to work well with GitHub’s remote repositories. I clicked around, read some docs, did a little Googling, and experimented until I got it to work and in way that works every time.

There are many other blog and stackoverflow posts on this subject but most are either missing a critical step or making it out to be way more complicated than it really is. That’s the problem with Apple magic: Sometime’s they design away the details to a point that you really don’t know what is going on.

The best tutorial on Git, Xcode, and GitHub for the white belt hacker is here: http://www.raywenderlich.com/13771/how-to-use-git-source-control-with-xcode-in-ios-6

But the part on connecting your local Git repository created and managed by Xcode to your remote GitHub repository is a little brief and lacks detail that might trip you up. Here is all you need to do to get Xcode and GitHub to play nice…

  • Create your Xcode project with a local Git repository and write some code
  • Commit your changes locally (File > Source Control > Commit…)
  • Create your GitHub remote repository on GitHub but do not initialize it and do not add a readme.md file!
    • Note: You can give that remote repository any name you want, I gave it the same name as my local git repository because I’m lazy
  • Go to the Source Control menu and and choose the second item with the name of your repo. This item leads to a popup menu. Choose the last item of that popup menu which has the name of your repo and word “configure”
  • In the configure dialog choose the Remotes item
  • Click the + button and choose “Add Remote” to associate a remote repo
  • In the Add a Remote dialog box you have two fields to fill out
    • In the name field enter the name of the GitHub repository you just created
    • In the location filed paste the “HTTPS” URI from GitHub for your repo
    • It will look like this: https://github.com/you-account-name/your-repo-name.git
  • Now you have a connected local and remote repository 🙂
  • Go back to the Source Code menu and choose Push…
    • A dialog box pops up with a drop down menu
    • Choose the only option you can which will be something like your-repo-name/create
    • Click the push button
    • Enter your user name and password in the dialog box that appears

You Win!!

Remember to check “Push to remote” in the Commit dialog box so you check in your code both locally and remotely.

Extra Credit:

I use Two Factor Authentication and I had to turn it off to test this. That made me a little nervous and I immediately turned Two Factor back on.

However you can generate a Personal Access Token so that that you can push to GitHub from Xcode and keep Two Factor on!

  • Log into you GitHub Account and go to Settings > Personal Access Tokens
  • Click the Generate New Token button
  • Give the button a description such as “Xcode Repo-Name”
  • Check the least amount of scope needed to commit code remotely: “Repo”
  • Click the Generate Token button at the bottom.
  • Copy the token (which is a long string of numbers)
  • Back in Xcode go to Preferences > Accounts and choose your repo under the list of repositories.
    • The Address field will contain the HTTS URI you entered earlier
    • The Description is the name of your repo
    • Authentication should be set to User Name and Password
    • User Name should be your GitHub user name
    • In the Password field paste token

Boom! Now you can commit remotely with Two Factor Auth in full effect!

 

Categories
Programming

Everyone should learn to code

I was on a HuffPost Live segment and got a chance to discuss why learning to code is something everyone should do!

Movement Grows To Cultivate Computer Programming

That’s me on HuffPost Live!

And I have two HuffPost blog posts talking about coding and drawing and why you should learn to do both.

Categories
Programming

Opps! Errors in Google’s Chrome Extension Tutorials

I don’t know why, but I got interested in writing a Chrome Extension. Yeah, I know, like 3 years too late. I figured it would just take an hour and I might learn something about well designed plug and play component architecture. I quickly found the Getting Started tutorial. The screen shots were a bit out of date but the instructions were clear and simple. After following the tutorial the example extension (kitten photos from Flickr) failed to display images and failed to post any errors to the debug console.

So I went the Debugging Tutorial but I could not get my extension to load in the debugger.

Fooling around I could make text to and images display in the example extension’s popup window but the example code, provided by Google, failed to work. Did the Flickr query API change? Was a bug introduced in a Chrome update? Is my computer broken? A glitch in the matrix?

I love that feeling you get when you’re debugging utterly simple code and completely lost: “It should work and when I figure it out I will feel like an idiot!” (because generally it’s a missing a “}” or some other typo).

But this time it wasn’t me! It was Google’s tech writers.

First, if you want to debug a Chrome extension do not follow the instructions: Right-click the Hello World icon and choose the Inspect popup menu item.

Instead do this: Left-click the Hello World icon so the popup appears and then right-click the popup window! (Unless you are left-handed like me and you have to right-click where the world says “left-click.”)

Clicking with the “other mouse button” (the handed-neural way to say “right-click”) on the extension’s window brings up a context menu that let’s you inspect the extension and load its code and resources into a Chrome debugging window.

Second, if you want to see the kittens, change this line in popup.js:

    req.open("GET", this.kittensOnFlickr_, true);
to the much more effective:
    req.open("GET", this.searchOnFlickr_, true);
The function kittensOnFlickr_ is never defined. The function searchOnFlickr_ is defined instead. The kitten look excellent when they finally appear!
Sometimes when looking through a tutorial I find errors like this and wonder two things: Am I the only one who actually reads and runs programming tutorials? Is this an intelligence test?
Given that Chrome extensions are no longer a hot technology it probably doesn’t matter 🙁
Categories
Nerd Fun Product Design Programming

HyperCard: What Made it Leet

I posted a blog entry on HyperCard yesterday on The Huffington Post: HyperCard: The Original Bridge Over the Digital Divide. From the comments and tweets that I got it was pretty clear that us older hackers have fond memories of HyperCard. But there’s the rub–Us older hacker. Kids today, i.e., people in their twenties, missed out on the whole HyperCard phenomenon.

The children of HyperCard are ubiquitous! Every web browser, every presentation app, and even Apple’s iBook Author tool and Adobe’s AIR environment are Jar Jar Binks to HyperCard’s Qui-Gon Jinn.

But like Jar Jar himself, HyperCard’s children are flawed. All these apps and tools that link, animate, and script are over-specialized or over-complicated.  iBook Author is a great example. It’s a quick and easy (and free) way to create an app that runs on iPhone and iPad but only if you want that app to look and feel like a high school text book. Not sexy!

On the other end of the spectrum is RunRev’s LiveCode. It’s the most HyperCard-like of HyperCard’s successors, allows you to import HyperCard stacks (originally), uses many of the same stack and card metaphors, and provides a programming language very similar to HyperTalk. Unfortunately LiveCode has become a tool for creating serious desktop and mobile apps. It’s become as complex as Adobe Flash/Flex/AIR and almost as expensive. I have to give points to RunRev for keeping the dream alive and they deserve to generate a profit but it’s not about 10-year-old kids and school teachers making interactive lessons anymore.

Here’s my list of what made HyperCard great. I hope someone picks it up and runs with it.

  • You could do a lot but you couldn’t do everything with HyperCard. Limitations are a great way conserve complexity and keep doors open to the general public.
  • HyperCard was a general “software construction kit”. You could create a presentation but it wasn’t optimized for presentations or anything else. In its heyday HyperCard was used for everything from address books to to calculators to role playing games but it always felt a little amateur and frivolous.
  • HyperCard was free, preinstalled, and came with a great set of sample stacks. Some people just used the stacks as they came out of the box. Others noodled around with a bit of customization here and there. A few brave souls created new stacks from scratch. But it didn’t cost a dime (originally) and was easy to find.
  • HyperCard’s authoring tools were bundled with it’s runtime environment. Any stack (originally) could be opened and every script inspected. If a stack did something cool you could easily cut-and-paste that neat trick into your own stack.
  • HyperCard’s scripting language, HyperTalk, was very very English-like. More English like than AppleScript and 10,000 times easier for the amateurs and kids to master than JavaScript, Python, Ruby, or Processing. I’m sorry but “for (var i = 0; i < x; i++)” is just not as readible as “repeat with x equal to the number of words in line 1” to normal literate humans. (Python comes close, I give it props for trying.)
  • HyperCard stacks looked like HyperCard stacks. You could easily spot a stack in a crowd of icons and when it was running HyperCard stacks had their own visual language (originally). This visual identify made HyperCard authors feel like members of a special club and didn’t require them to be User Experience experts.

Limited, Free, Simple, Open, Accessible, Generalized, Frivolous, Amateur; The characteristics of greatness that also define what is great about the World Wide Web (originally).

Note: The careful reader might wonder why I’m clarifying my statements with the phase “(originally)”. Towards the end of its life HyperCard added complexity and locking and became something you had to buy. The parallels with the closed gardens and paywalls of today’s Inter-webs  are a bit uncanny.

Categories
Cocos2d-iPhone Programming

ARC Memory Management in iOS 5 and Cocos2d-iPhone 2.0

My rewrite of Dungeonators is crawling along at a glacial pace. Mostly because I can only work a couple of hours a week on the project. But the iOS 5 way to manage memory with ARC (automated reference counting) is making the process far less painful than it was the first time I wrote my game. ARC uses annotations and some new key words to manage memory on your behalf. It works very well if you’re doing simple client-side game development and don’t have to worry about backward compatibility with iOS 4.

Here is an example of how ARC changes your life for the better…

In the old days you would declare out your ivars, declare your properties, then synthesize and map them together, and release them in a dealloc method. This little design pattern required 4 repetitive lines of code for every ivar (instance variable) and engendered flamewars about  coding style and where underscore should go (if you thought it was necessary to distinguish an ivar name from a property name).

Pre-ARC Entity.h

#import "cocos2d.h"
@interface Entity : CCSprite {
BOOL isActive_;
NSString * name_;
}
@property (nonatomic) BOOL isActive;
@property (nonatomic, copy) NSString * name;
@end

Pre-ARC Entity.m

#import "Entity.h"
@implementation Entity
@synthesize isActive = isActive_;
@synthesize name = name_;
- (id) init {
  self = [super init];
  if (self) {
    isActive_ = YES;
    name_ = @"Fang";
  }
  return self;
}
- (void) dealloc {
  [name_ release];
  name_ = nil;
  [super dealloc];
}

In this new modern era of automated reference counting I just declare properties, I don’t worry about accessing the ivars directly, and I don’t write my own dealloc. It’s a lot less code in a complex game where characters and objects have dozens of properties.

Post-ARC Entity.h

#import "cocos2d.h"
@interface Entity : CCSprite
@property (nonatomic) BOOL isActive;
@property (nonatomic, strong) NSString * name;
@end

Post-ARC Entity.m

#import "Entity.h"
@implementation Entity
@synthesize isActive;
@synthesize name;
- (id) init {
  self = [super init];
  if (self) {
    isActive = YES;
    name = @"Fang";
  }
  return self;
}

To get Cocos2d-iPhone to work with ARC was really easy: I just replace the NSAutoreleasePool object in main.m with the new ARC friendly @autoreleasepool annotation. (I might not have had to do this but it’s supposedly more efficient.)

int main(int argc, char *argv[]) {
//    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
//    int retVal = UIApplicationMain(argc, argv, nil, @"AppDelegate");
//    [pool release];
//    return retVal;
  int retVal;
  @autoreleasepool {
    retVal = UIApplicationMain(argc, argv, nil, @"AppDelegate");
  }
  return retVal;
}

The downside, as I stated above, is that your app will only run on iPhones, iPads, and iPods running iOS 5 and you need to use Cocos2d-iPhone 2.0. But I think that’s a fair tradeoff. Backward compatibility is a killer of the artistic soul and should be avoided where possible. To Err is human, but to upgrade is divine 🙂

Check out Ray Wenderlich’s excellent ARC tutorial for all the gritty details!

Categories
Product Design Tech Trends

When Dogfooding Fails

For over 20 years we’ve been eating our own dog food in the software industry and it’s not working. For the uninitiated dogfooding means to actually use the product you’re developing. It started out as a radical idea at Microsoft and spread as a way to get developers to experience their customer’s pain. On the surface it was a very good idea–especially for an aging corporate culture divorced from its users. When I interviewed with Microsoft in 1995 I was told that all their engineers we’re given low-end 386 PCs. These PCs ran Windows 95 so slowly that the MS developers were incentivized to improve Windows’ performance to ease their own suffering. I don’t know about you, but I find that Windows is still pretty slow even in 2011 running on a really fast multicore PC. Clearly all this dogfooding is not helping.

So I’d like to frame an argument against dogfooding and in favor of something else: Plagiarism.

My argument goes like this:

  1. Dogfooding doesn’t work, or at least it’s not sufficient, because it’s not a good predictor of software success. Some software that is dogfooded is very successful. Most software that is dogfooded fails. (Most software fails and most software is dogfooded therefore dogfooding fails.)
  2. Dogfooding is really bad because it give you a false sense of doing something to improve your product: “It’s OK, I know our software is terrible but we’re forcing our employees to dogfood it and out of shear frustration they will make things better! Everyone go back to sleep…”
  3. Dogfooding reinforces bad product design. Human beings are highly adaptable (and last time I looked software devs are still considered human). We get used to things, especially in a culture where company pride and team spirit are valued (e.g. groupthink). Over time poor performance becomes typical performance. It starts to feel natural. Thus slow loading Windows operating systems become the gold standard for thousands of loyal Microsoft employees and customers. Instead of fixing the software we are fixed by it.

I believe that the urge to Dogfood is an emergent strategy of mature tech companies that want to rejuvenate their software development process. Management starts talking about Dogfooding when they realize the spark of creativity has gone out and they want to reignite it.

One of the reasons Dogfooding fails is that you never eat your own dog food in the beginning: The dog food didn’t exist yet. You had to get your inspiration from outside the company. Microsoft Windows was not the first OS with a graphical mouse-driven shell. At some point the Windows devs must have looked at the Apple Lisa and Macintosh computers for inspiration. And the Apple devs looked at the Xerox Star. And the Xerox devs drew their inspiration from the physical world: The first GUI desktop was modeled on an actual physical desktop. No dog food there.

So rather than dogfooding we should talking about plagiarism. If you want to make a great software product eat another a great software product and make it taste better–don’t eat yucky dog food.

Microsoft should force their devs to use the fastest computers running the best operating systems with really cool applications. I think they must have bought some MacBook Airs, installed Ubuntu and Spotify because Windows 8 looks pretty awesome 🙂

Categories
Nerd Fun Programming

Fraction: Does not recognize selector forward::

If you’re crazy like me you love reading really good primers on programming. Not just to learn about a particular language but to enjoy well written technical prose. (Yeah, I said I was crazy). Yesterday, I started reading Stephen Kochan’s classic Programming in Objective-C (original edition), which was published in 2003. What I like about Kochan is how he presents the principles of object oriented programming and the syntax of Objective-C without jumping into writing a fancy application. Kochan takes his time to teach each component of the language and the paradigm instead of glossing over the details to quickly get to a utilitarian example.

If you want to understand how a great tutorial is written you can’t do much better than Kochan. Unfortunately a lot has changed in the Mac OS X world since 2003 and the code examples don’t compile. The code is fine. It’s the default compiler setting that have changed. A Google search on the compile error brought me to a a good discussion on the problem on Apple’s developer support forum. You have to dig but the fix is pretty trivial if you know gcc complier flags (which the target audience of a primer are unlikely to know).

My advice to students and armchair time travelers who want to follow the original book is to resist the urge to change the source code examples to inherit from NSObject. Instead use the -arch i386 flag as suggested by very helpful forum user Constantino. (Mysteriously Constantino’s forum name is spelled with a K.)

In other words instead of compiling with

gcc ClassName.m -o ProgramName -l objc

use

gcc -arch i386 -o ProgramName ClassName.m -lobjc

To compile and run the OOP first example of the book from the terminal you can copy and paste the following 2 lines:

gcc -arch i386 -o Fraction Fraction.m -lobjc
./Fraction

And for the full experience, don’t use Xcode or a fancy text editor. VI is fun, old school, and Apple’s Terminal a joy to work with.

Notes:

  • There is a third edition that probably addressed this issue. But what fun is that if you only have the original edition? I would love to set up an old Mac with a vintage version of the Mac OS X to really immerse  myself in the experience!
  • There is also also a Programming in Objective-C 2.0 3rd Edition which looks like a lot of fun to read and which might actually be more relevant if you have an urgent need to write a modern Mac application.