Categories
Programming

Grunt unable to locate JSDoc (wrong installation/environment)

Recently I set up Himins (a server-side node project) to properly build using Grunt. I got every tool working awesomely in my gruntfile.js except for JSDoc! Grunt give me this clue:

Running "jsdoc:dist" (jsdoc) task
>> Unable to locate jsdoc
Warning: Wrong installation/environnement Use --force to continue.
Aborted due to warnings.

I had previously installed JSDoc with NPM globally and tested it on the command line. Googling around didn’t turn up much at first. I was not going to move JSDoc to a non-standard location just for Grunt!

This blog post, The Best Document Generator for Node, gave me the clues I needed to resolve the problem!

I just had to add

jsdoc: './node_modules/.bin/jsdoc'

to my gruntfile.js!

Why Grunt doesn’t look for JSDoc there in the first place is weird to be. All it’s friends are there. The sample code for using the JSDoc Grunt plug-in doesn’t mention this issue.

You can find my full guntfile.js here.

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

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
  }
}
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 ) &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;
}
Categories
Cocos2d-iPhone Programming Sprite Kit

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!

Categories
Programming

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.

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 🙁