Music Gremlins is Approved!

Derpy gremlin

My iPad app is approved and going live on July 1st!

Music Gremlins is an ear-training game where you beat gremlins by matching the notes that they play. Different types of gremlins demand different strategies. As a musician, I found it very difficult to practice relative pitch and this makes it easier and more fun.

I wanted to have Music Gremlins be more game-like, but it turned out kind of like Mavis Beacon Teaches Typing for ear training. Oh well, I hope that at least musicians still find it useful. And it’s only my first attempt.

Details: it’s also only for iPad at the moment but it is totally free.

The App Store Process

Last weekend, Music Gremlins was almost ready to go so I put in a focused effort to finish it up. I spent all weekend doing a thousand little “last things” and submitted it for review on Sunday.

It took me hours to actually submit the damn thing. If you ever come across Apple’s “Download Application Loader”, run away. The Application Loader is a pit of hell from which there is no escape. You can upload your app directly through XCode, which involves a mere hour or so of swearing.

Once XCode has uploaded your app for you, you get an automated email that your app is “Waiting for Review.” The review process for my app was painless, but Music Gremlins didn’t exactly stretch the bounds of iOS. I uploaded it on Sunday, June 9th and they got back to me today (June 17th), which was a lot faster than I expected. I got several emails today, that my app was “In review,” “Processing,” and finally:

App Store Approval

Screenshot from the final game:

iOS Simulator Screen shot Jun 9, 2013 9.41.59 AM

Unfortunately, I forgot to remove the debugging framerate, so you can see the frame rate in the lower left corner. This is a screen shot from the simulator and is running at 20fps, but on my iPad it runs at 60fps (yay!). I’m going to try to remove that by July 1st…

It’s turtles all the way down

Turtles all the way down” is a concept that Java handles very nicely:

public class Turtle {
    Turtle prevTurtle;
 
    public Turtle(Turtle prevTurtle) {
        if (prevTurtle == null) {
            throw new RuntimeException("It's turtles all the way down.");
        }
	this.prevTurtle = prevTurtle;
    }
}

(Probably there should be a special FiniteTurtleException, but I wanted to keep the code compact.)

Similarly for other circular references:

class Chicken {
    Egg cameFrom;
 
    public Chicken(Egg hatchedFrom) {
        cameFrom = hatchedFrom;
    }
}
 
class Egg {
    Chicken cameFrom;
 
    public Egg(Chicken mother) {
        cameFrom = mother;
    }
}

You can do it in C-like languages, but you need to be a little clever in your header files, which takes some of the fun out of it.

Yertle the Turtle

Adding an Assertion Macro in Objective-C

TL;DR:

#define CHECK(val) NSAssert((val), @#val)
 
// Then use:
CHECK(/* something (hopefully) true */);

Long version:

iOS made the the somewhat bizarre choice that dereferencing a null pointer is not an error. The program just ignores that line and keeps going. Now this causes fewer crashes (yay-ish), but when I developing I’d really like the program to fail fast instead of just skipping huge swaths of code.

As far as I can tell, there’s no way to make dereferencing a null pointer an error. Thus, I’ve started adding asserts everywhere that I expect values to not be null:

NSAssert(my_var != nil, @"my_var isn't supposed to be nil");

I wrote that all of once and decided I needed a macro:

#define CHECK(val) NSAssert((val), @#val)

Now, I can just say:

CHECK(my_var != nil);

At compile time, the assert’s message will automatically be set to the string @"my_var != nil" (that’s what the preprocessor instruction # does: it means “wrap in quotes”).

Most libraries have a macro like this for asserting, but I’ve never programmed it myself. Nifty stuff!

P.S. If you need to debug the macro, you can run Objective-C files through GCC normally to see the preprocessor output:

$ gcc -E Gremlins.m > Gremlins.E

MongoDB: The Definitive Guide 2nd Edition is Out!

MongoDB: The Definitive Guide

The second edition of MongoDB: The Definitive Guide is now available from O’Reilly! It covers both developing with and administering MongoDB. The book is language-agnostic: almost all of the examples are in JavaScript.

Upgrading from a previous edition?

If you have read the first edition, the new edition covers a lot of new material (it is twice as long!). Everything has been updated and lots of sections on new features have been added.

Translations

I hear O’Reilly is working with their translators to get this edition translated into other languages, but I tend to be the last to hear about that so I don’t know what the schedule is.

So…

Pick up a copy and let me know what you think!

First Two Weeks at Google

I’ve been at Google two weeks now and I’m loving it so far. My team is great and the work’s very interesting, but I can’t talk about what I’m doing, so:

There’s a ton of orientation stuff new employees have to do, which hasn’t been much fun. There was a scavenger hunt (which is the kind of thing I usually loathe) but we did find some cool stuff. One of the places on the list was “the music room.” When we went in it was a soundproofed room with a half-dozen guitars along one wall, an electric drumset, synth, a mic, soundboard, amps… it was amazing.

Other things I’ve discovered so far are:

  • The library, which has big comfy armchairs and couches, shelves of physical books, and a sci-fi touch interface for checking out ebooks.
  • The juice bar: free smoothies anytime.
  • The workshop with metal/wood crafting supplies and a 3D printer.

I also got this, er, unique hat:

Google beanie

If anyone wants a propellor beanie, let me know.

Stock Option Basics

Here’s what I wish I’d known when I started working at 10gen. Disclaimer: don’t take this as financial advice, consult someone who actually knows what they’re talking about before making any financial decisions, this is for entertainment purposes only, etc. Also, the numbers used below do not match any startup that I know of, they’re just hypothetical.

Intro to Stock Options

Stock options are the option to buy X shares of stock in a company at a guaranteed price of $Y per stock. Generally, they have some time constraints: they are doled out to you slowly over 3-5 years (the vesting schedule) and expire after a certain number of years if you don’t buy them.

$Y is the strike price, the price of the stock when you’re given your stock grant. Basically, it is determined by taking the value of the company (say, $2,000,000) and dividing it by the number of shares that have been issued (say, 5,000,000). This would give you a strike price of $0.40.

If the company is successful, the stock price should be higher when you sell the shares. For example, say that the startup above is successful and their stock price rises to $5.00. Now you can buy your shares for $0.40 and sell them for $5.00, making a nice $4.60 profit on each share.

Except you can’t, because of taxes. If you are the kind of person who doesn’t know what a stock option is, you probably have common, or non-qualified stock options (companies prefer this type because you’ll be footing the tax bill instead of them). For non-qualified stock, you get taxed twice: when you buy (or exercise) your options and a second time when you sell the stock (these are called taxable events).

Let’s say you’re in the situation above: you have 10,000 shares with a strike price of $0.40 and you want to exercise your options. The current price is $5. You exercise your options for $4,000 ($0.40 * 10,000). However, according to the government, you just “made” $46,000 ($5*10,000 – $4,000), which you’ll now be taxed on. I have no idea how this tax rate is computed, but for me it was ridiculous. If my options matched this example (they don’t), I would have had to pay ~$30,000 in taxes (about 60% tax rate). Also, you have to hand the company a check for these taxes when you exercise the options, you can’t put it off until April.

So be careful: if you own a lot of options and the price rises a lot, you can “golden handcuff” yourself to a place because you cannot pay the taxes to actually buy your options.

The second taxable event is when you sell the stock. If you sell the stock within a year, you’re hammered again with short-term capital gains taxes. If you wait for more than a year to sell, you “only” get hit with long-term capital gains taxes.

Negotiating Options

When you get a job at a startup, often part of the offer will be stock options. If the startup is early stage, I’d recommend pretending that your options will be totally worthless forever. Is the salary acceptable on those conditions? (Almost every other startup I know of has failed in the time 10gen’s been around).

In retrospect, I wish I had negotiated more stock options instead of more salary when I started at 10gen, but if I was joining an early-stage startup again, I would do the same thing: not sacrifice salary for options.

The exception is if you’re joining a startup at a later stage and you’re pretty sure they’ll be successful. In that case, you might want to negotiate for more options.

Option Expiration

Typically, options have an expiration date. Make sure you buy them before they expire (if you want them). Also, options are typically designed as an incentive to stay, so they don’t follow you after you leave the company. If you quit or are fired, you’ll have to buy any vested ones before or shortly after leaving.

Buying Unvested Options

You can buy unvested options, but I can’t see why you would unless you’re pretty sure the company’s going to succeed, you’ll be there until the options vest, and you’re trying to avoid the tax hit. If all those hold true, Max Schireson wrote a good blog post on what you need to know about that. In fact, go read his post regardless, because it’s a really good and more technical coverage of a lot of these points.

Dilution

In the example above, you have 10,000 shares out of 5,000,000, meaning you own (or could own) 0.2% of the company, you tech mogul. However, whenever there’s a round of funding typically more shares are issued. Thus, instead of there being 5,000,000 shares, there are now 10,000,000 and you only own 0.1% of the company. Your company should tell you how many stocks are outstanding (the number issued in total) if you ask. I think this number is typically confidential, but I’ve heard people advise that you should ask during salary negotiations, so YMMV.

The other significant event is board meetings, where the board decides how much the company is worth. This changes what the current stock price is. Funding rounds also often have an effect on price.

Stockholder Privileges

Even if you’re at an early-stage startup, it might be worth buying a few shares to get stockholders rights. Find out how many shares you need to buy to get these, if you want a look at the books and so on.

Keeping Your Documents

Particularly at an early-stage startup, there may not be anyone keeping track of this stuff. When 10gen got an Finance/HR person, I asked them about the options grants they had on record and they were missing my original hiring grant. Luckily, I still had the paperwork. Keep everything safe somewhere, just in case.

Exercise Quickly

If you’re leaving a company, get on exercising your options as quickly as possible. You generally have a limited time period before your options disappear and your company might have arbitrary restrictions on when you can exercise (like “not within a month of a board meeting”). Also, it’s not exactly a speedy process: it took 10gen three weeks from when I signed the paperwork and gave them the checks to actually send the stock certificates. You don’t want to have to be dealing with HR at your last company while you’re dealing with new hire HR at your new job.

Recruiting in all the wrong places

A recruiter had an email exchange at me the other day. It started with the standard recruiter email:

Hi Kristina,

How are you enjoying 10Gen? Any interest in going to something earlier stage? I’m working with a client in <field I’m not interested in>. Obviously the specificities of that are fascinating. Let me know if you’d be interested in hearing more.

I ignored it. A few minutes later, I got a follow-up email from him:

Subject: Whoop, how humiliating

Just saw on LinkedIn you left 10gen last month. Do you have plans for what’s next?

Closer, but not quite. A few minutes later:

Ach! Forgive me. Congratulations on the Google job.

Should you ever need the services of an incompetent sourcer, please, don’t hesitate to reach out!

And I kind of wished that I needed a recruiter because that was pretty funny.

Programming a State Machine

A monster modeled after a dog in my neighborhood.

A monster modeled after a dog in my neighborhood.

My attempts at game programming usually turn into impenetrable spaghetti code: “If the player walks through this door, then have him talk to the princess, unless he’s killed a guard, in which case the guards attack, or if he comes out of the secret passage…”

The game I’m working on now is pretty simple, but I’ve kept it really clean (so far) by using a state machine to keep track of what should happen when. Basically, each scene in the game is a state. There’s an overarching state machine which runs the current state on each tap. A state can either return itself or choose a new state to run next time.

In Objective C (+cocos2d), a state looks like this:

@interface State : NSObject {
    CCLayer *ui;
}
 
-(id) init:(CCLayer*)layer;
-(Class) processTouch:(UITouch*)touch withEvent:(UIEvent*)event;
 
@end

The processTouch function either returns nil, which means “run me again next time” or the next state to run. The other half is a “machine” to run the states:

// -----------------
// Interface
// -----------------
 
@interface StateMachine : NSObject {
    State *currentState;
    CCLayer *ui;
}
 
-(id) init:(CCLayer*)layer;
-(BOOL) processTouch:(UITouch*)touch withEvent:(UIEvent*)event;
 
@end
 
// -----------------
// Implementation
// -----------------
 
@implementation StateMachine
 
// Initialize the state machine by setting currentState to the first state
-(id) init:(CCLayer*)layer {
    self = [super init];
 
    if (self) {
        ui = layer;
        currentState = [[FirstState alloc] init:ui];
    }
 
    return self;
}
 
// Run this from the UI's touch dispatcher: it runs the current state's processing code
-(BOOL) processTouch:(UITouch*)touch withEvent:(UIEvent*)event {
    Class nextState = [currentState processTouch:touch withEvent:event];
 
    if (nextState != nil) {
        currentState = [(State*)[nextState alloc] init:ui];
    }
}
 
@end

Then, you might have an implementation like this for a swords & sorcery RPG:

@interface PalaceDungeonState : State {
    Guard *guard;
}
 
@implementation PalaceDungeonState
 
-(id) init:(CCLayer*)layer {
    // Use ui to render a dungeon
}
 
-(State*) processTouch:(UITouch*)touch withEvent:(UIEvent*)event {
    if (guard.alive) {
        [guard updatePosition];
    }
 
    CGPoint touched = [ui convertTouchToNodeSpace:touch];
 
    switch (touched) {
    case GUARD:
         [guard dies];
         break;
    case STAIRWAY:
         return PalaceStairwayState;
    case SECRET_PASSAGE:
         return SecretPassageState;
    }
 
    return nil;
}
 
@end

I’m not thrilled with doing so much work in the init, so for this type of game I’d probably move that to a start method that would be called by StateMachine on state changes.

Regardless, I’ve found this makes it a lot easier to make a complicated sequence of events while keeping my code readable.

Mad Art Skillz

With all this free time, I’ve been working on an iOS game. I’m not even close to done yet, but I’ve wrestled Objective C into submission and now and I’m working on some assets. It’s going to be musical, so here’s Beethoven:

beethoven

And here’s a demon (it plays the piano):

monster2

And the player character, Calliope:

calliope

If you ever need to make some vector art, Chris Hildenbrand’s blog, 2D Game Art for Programmers, is fantastic. It teaches you how to create awesome vector art using Inkscape (which is free). I had never done vector art before and his instructions are perfect for beginners.

Finished The Definitive Guide

Or at least the writing it, it still has to be tech edited, “real” edited, illustrated, formatted, etc. The second edition is going to be about 400 pages (almost twice the length of the first edition), with majorly expanded sections on sharding, replication, and server administration.

Phew.

Now, some mea culpas:

To those of you who sent me schemas: I’m sorry if I never got back to you! I decided to go in a different direction and ended up not using any of them. Sorry to waste people’s time (but they were fascinating to read).

To those of you who sent in a schema and I asked for your mailing address: I forgot to forward those emails to my personal account before leaving 10gen so I’ve lost the addresses. Please resend your address to my personal email (k dot chodorow at gmail dot com).

Screen Shot 2013-03-08 at 1.57.54 PM

kristina chodorow's blog