I Wrote a Customer Review on Amazon

I purchased an Asus monitor for my Mac Mini as a cheap alternative to the 27″ Apple Thunderbolt Display. I had a couple of tips and shared them on Amazon.

A couple of things to note:

  • Amazon make writing the review insanely easy. When I logged into Amazon it prompted me to rate and review all of my recent purchases.
  • The review was published within an hour. Perhaps sooner.
  • Amazon is protecting my privacy. I’m not sure why but perhaps that is there default setting. Much appreciated!
  • I immediately got a comment on my review with a better, cheaper alternative to the tip I presented.
  • Nobody, as of this writing, has found my review helpful.

I’m proud of my little review and I’ll check in on it from time to time to see how it’s faring in the wooly world of Amazon customer reviews!

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.

Apple’s Snakes and Ladders Swift Example

All the cool kids are learning Swift this week! Not wanting to be left out I downloaded Xcode beta 6 and the iBook introduction and started following long with the code sample in Xcode’s new playground.

Swift is impressive as it fixes a number of issues with Objective-C by replacing it wholesale with a modern language that feels like a well thought-out JavaScript. I love the idea of optional values, implicit types, simple generics, and how let and var are used to create immutable and mutable objects. I’m still digesting the class vs struct vs enum idea. I’m not sure why they are just not all classes but give me time, I’m sure I’ll see the light.

The Snakes and Ladders example is a fine bit of sample code and shows off Swift’s power as a teaching language. But I had a couple of issues with it and tweaked it. See below and check out the comments for why I did what I did. You should be able to copy and paste this code into a playground and watch it run!

// Playground - noun: a place where people can play

import Cocoa

// Snakes and Ladders Game

let finalSquare = 25 // 25 squares in the game (0 to 24)

// init all squares to 0 and included a 26th square (to simplify the code)
// Note: you can use var or let to define the array board (Apple uses var, I'm using let)
// - let makes board a constant but values of a const array are still mutable
// - its the number of elements in the array that are immutable
// - using let allows the compiler to optimize looking up values in the array
let board = Int[] (count: finalSquare + 1, repeatedValue: 0)

// in 4 squares as ladders (+ values) and 4 squares as snakes (- values)
// ladders move the player forward by value in square
// snakes move the player backward by value in square
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08

var square = 0   // player position
var diceRoll = 0 // moves are determined by an 8-sided die

println("Game Starting at square \(square)")
// start the game
while square < finalSquare {
  
  // the Apple sample code used a rather useless means of rolling a dice by
  // incrementing a value.
  // I see why they did that: a more real world example requires the un-swifty 
  // C function arc4random_uniform().
  // Later on the book Apple shows you how to use a generator class to create
  // a random number but frankly, that is overkill.
  
  // I betcha Apple to introduce a Swifty library of math functions that will 
  // hide the ugliness of arc4random_uniform() with something like randInt()
  
  let diceRoll = Int(arc4random_uniform(7))
  
  // move by the rolled amount
  square += diceRoll
  
  if square < board.count {
    
    // if the player is still on the board do what the current square instructs
    let oldSquare = square // extra let created for printing the results since square's value has changed
    square += board[square]
    
    println("diceRoll = \(diceRoll), landing = \(oldSquare), instruction = \(board[oldSquare]), destination = \(square)")

  }
}

println("Game over at square \(square)")

Update!

I could not get the sweet while loop with the label "gameLoop" to work in the playground. It's no surprise that Swift has a couple of bugs. So with a bit of fiddling I got it to work with a gameOver flag. And while I was at it I created a swifty function to hide the ugly arc4Rand_uniform() call and refactored the print statements so you can follow along with the game in the console.

func randNum(limit: Int) -> Int {
  return Int(arc4random_uniform(UInt32(limit)))
}

// start the game
println("Game Starting at square \(square)")

var gameOver = false

gameLoop: while square != finalSquare {
  diceRoll = randNum(7)
  switch square + diceRoll {
  case finalSquare:
    // diceRolled moved player to finalSquare
    // game over
    print("starting \(square), ")
    print("diceRoll \(diceRoll), ")
    print("destination \(square + diceRoll), Game Over")
    println()
    
    // Swift didn't recognise the loop's label so I commented it out
    // This teams the break only breaks out of the switch
    // The gameOver flag is used to break out of the while loop
    gameOver = true
    break //gameloop
  case let newSquare where newSquare > finalSquare:
    // diceRoll moved player beyound finalSquare
    // roll again
    print("starting \(square), ")
    print("diceRoll \(diceRoll), ")
    print("destination \(square + diceRoll), Re-roll")
    println()
    
    // Swift didn't recognise the loop's label but in this case
    // it doesn't matter...
    continue //gameloop
  default:
    // valid move
    // update board
    print("starting \(square), ")
    print("diceRoll \(diceRoll), ")
    square += diceRoll
    print("destination \(square), ")
    print("instruction \(board[square]), ")
    square += board[square]
    print("result \(square)")
    println()
  }
  // if flag is set break out of the while loop
  if gameOver {
    break
  }
}

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 ) &lt; 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;
}

Re-doing Dungeonators

Meet the Dungeonators

One thing I think all software developers love to do is to make software for “the heck of it.” Hacking something together without having to worry about users, open source community members, and code reviews, is something devs don’t get to do often in these days of test-driven, agile, minimum viable products. Back in 2011 I created an iPhone game just for the heck of it. I wanted to learn about the indy game development process and there isn’t a better way of learning than by doing. I accomplished my mission and uploaded the first version of Dungeonators to Apple’s iTunes App Store in October of 2011. While the game is not very playable, I learned a lot:

  • How to design and implement a realtime game with Objective-C and the Cocos2d-iPhone framework
  • How to create all the art, fonts, sprites, and a spite atlas
  • How to record (or buy) all the sounds and music and use open source tools to transcode audio for a game
  • How to create the mechanics of a game with objects and callbacks while ref counting to manage memory
  • How to test and deploy an iOS game and get something approved in the App Store

Now it’s 2014 and much has changed in the world of indy game development for iOS. Apple’s iOS 7 introduced Sprite Kit which reduces the need for a framework like Cocos2d. Apple also introduced the iPhone 5 and the iPad with Retina, which mean there are four iOS screen resolutions/aspect ratios in common use. Oh, and let’s not forget Flappy Bird and 2048. While writing a hit indy game is still harder than winning the lottery it looks like a couple of people have done it!

Since I’m taking a break between adventures, I thought it would be fun to update Dungeonators for iOS 7 and Sprite Kit. Plus it would be good to make the game universal (available on all iOS devices) and global (available in more than just the United States edition of the App Store). And I should probably make it playable!

The technical part of this plan is relatively easy. iOS 7 is easier to develop with than previous versions of iOS. I can use ARC (automatic reference counting)in addition to manual ref counting. All the music and sound effects should just work fine. My custom Objective-C classes just need some simplifying (I wrote too much code–that’s my bad coding habit). The original Dungeonator’s artwork is all vector-based so rendering it in different resolutions for each iOS device shouldn’t be too hard. Finally, Sprite Kit is remarkably similar to Cocos2d. Porting the scenes, sprites, transitions, and actions will also be easy.

D2-2014_2
High resolution Dungeonators under development (1136 x 640 pixel rendering)

The hard part is creating a playable game. If you download original version of Dungeonators from the App Store you’ll find it really confusing. How do you play? Where to you touch? What is the goal? I don’t know what I was thinking!

Actually I do know what I was thinking. I was thinking about the inside not the outside. Inside there are classes for characters, strategies, spells, payloads, and matches. Way too much to fit in a casual game. So while I’m porting everything over I’m going to tear out hundreds of lines of code. I’m going to simplify Dungeonators to the point where it doesn’t require a personal demo from me to learn how to play!

I still might not have a playable game but at least it won’t crash anymore!

April 1, 2014 Tech News

Google Announces Google++

Google++ users will have access to a social network with encapsulation, multiple inheritance, and polymorphism. Google++ users get the added benefit of UML diagrams and free advice from the Gang of Four (The computer scientists, not the punk band).

Yahoo! Acqui-hires Apple

To ensure it has the right talent for the 21st century Yahoo! acquired Apple today, cancelled the iPhone, iPad, iOS, and all those other tired old projects, and distributed Apple’s engineers to it’s most disruptive technology initiatives, including Yahoo! Mail, Yahoo! Groups, and My Yahoo!.

Facebook Founder Mark Zuckerberg Buys EVERYTHING

Facebook bought everything, the whole shebang, all of existence, and life as we know it, for a combination of cash and stock valued at $1 Quadrillion USD. “Mark promised the universe would remain independent and free of advertising,” Noted The Creator, who now reports directly to Susan Sandberg.

Apple Unveils Apple TV, Which is Apparently, a TV

Tim Cook released detailed of the long rumored Apple TV. According to Mr. Cook, Apple’s super secret TV is a TV. It hooks up to any cable box and is compatible with almost any Ikea entertainment center. Innovations include a power cable with an odd connector and a remote control with no buttons.

Elite Hackers Who Supposedly Fixed Healthcare.gov Admit They Did Nothing

The co-called elite hackers called-in by the Obama Administration to keep the Affordable Care Act website from crashing admitted, via a blog post on Medium, that while they held many meetings and drew several diagram, the scaling and performance problems with Healthcare.gov were actually resolved by the software developers who have been working on the project the whole time. “Luckily the developers just ignored us and fixed the bugs they were going to fix.”

Learning Haskell on the Web

Mister Spock

(Image source: https://blog.kejsarmakten.se/all/software/2011/10/23/haskell.html)

Below are websites and such that I’m tracking in my quest to sharpen my FP skills by learning Haskell in my spare time.

  • The Haskell website (where you can download it)
  • A brief introduction to Haskell on GitHub (apparently from a book on Scala, short and sweet)
  • A complete Haskell textbox on WikiBooks (and a great example of a WikiBook)
  • School of Haskell website (hosted by my friends at FP Complete)
  • Guide for setting up Haskell on Windows from Stack Overflow (yes, I have a Windows machine #noshame)
    • Note: The question and top answer are from 2008. Scroll down to the 5th answer from 2013–which is the best one IMHO)

Why should you learn Haskell? Because you only have one one life to live and you shouldn’t spend the majority of it hunting down bugs created by unintended side effects (or intended side effects for that matter) created by programming paradigms that get fuzzy around the edge cases. Life is all edge cases!

Even if you never write production Haskell you can take what you learn from it and apply it to your programming lingo of choice and hopefully write more legible, maintainable, and extensible code.