how much faster is bad code?

The equation in discussions of coding quality runs something like:

“Yes, it’s faster to write code that is bad. But whoever comes to use this code later will spend far more time trying to maintain it. And that person using it later is most likely you!”
good job
leaving aside for the moment the impossibility of clearly defining bad versus good code, this argument seems at first glance to be sound. For example, if you it’s faster to not add any comments to your code, but uncommented code is definitely much harder to come back to later.

So what does that mean when you go to write code for a game jam? with just 48 hours to build everything this must be an example where ‘fast’ is the priority.

re-reading this post it kind of assumes you know what game jams are: They’re a weekend event where you and a small team try to complete a playable game in 48 hours. They generally start Friday afternoon and end Sunday night, keep this is mind as I describe the pacing

After seeing some tips from a Unity employee where she mentioned ‘remember the code you write in a game jam would never pass code review,’ I tried to really live by this principle in the recent Cartoon Network Game Jam. I’d like to discuss some ways I tried to write things ‘quick and dirty’ and how it worked out:

Debug.Log lines everywhere

Huge success just adding Debug.Log lines around what I was doing, before I was even sure I would need them.

I actually did this right off the bat, logging stuff like ‘I’m trying to match strings, here’s my progress’ without that bit actually breaking yet (of course it did break later so hashtag success).

This isn’t faster than not logging anything, but is faster than writing careful code comments.

The only downside was if the logs were inaccurate for some reason (not checking the right variables or whatevs) or if I ended up logging so much it drowned out the important info. Unity by default displays the last log message at the bottom of the editor, so it’s kinda annoying when that’s no longer useful info.

Generally even logfile chattyness is okay as long as it’s not happening on every frame.

hardcoded dialogue

The benefit here should be obvious: if you just have the customer say a string you just fed in, you know it’s working, you don’t have to muck with data storage or parsing.

… good, right?

The problem here is one of negative feedback: the better your game is doing at the gam, the more likely you’re going to wish you had better control of the dialog.

If you end up with a game that people want to play for 5 minutes (that’s a massive success btw), your 1 or 2 hardcoded strings will probably look more like an in-code dictionary.

Worse, with my most recent game I really wanted associated info with bits of dialogue. My game is a sandwich shop, I wanted each customer dialog to also include an ‘order’ and some indication of which character sprite should be asking.

I ended up with a 2-dimensional array that took several dozen lines. Since C# doesn’t let you store mixed types in arrays, I had to store the integer for sprite selection as a string, then parse that back to an int.
Everything's fine
yes I am aware that this annoying me proves I am truly Javascript’s creature

So I had to write a lot more code to handle this big gross blob than I meant to at the start.

I think basically there might be another lesson here entirely:

life lesson 1: Make sure it’s always easy to add dialogue to your gamejam game

Dialog, just like loop lines in film production, is a cheap and easy way to paper over small issues with your game. you’re going to find yourself wishing you could make the NPC’s say ‘be sure to click that blue gem at the bottom to spend your spirit tokens!’ on Sunday, so hard coding dialogue is probably not that smart.

Array counting

when you’re storing sound effects in an array, it’s nice to take in some strings, use a switch statement and make it easy to call the right sound effect at the right time with something like PlaySound("jab")

Buuuuuuuut it’s a lot faster to just toss them in an array, then use a legal pad or extra .md file to keep track of which index is which sound. It also removes one bit of work from your code: you have a much simpler PlaySound function to keep track of.

This also goes for stuff like hard-coding the length of arrays. First of all c# doesn’t let you mutate the length of arrays at runtime, so your array should always have the same length, also for most arrays except perhaps those that contain dialogue as noted above, you really shouldn’t be changing your arrays late in the weekend. Want to add a third attack move to your character? Should have thought of that before noon Saturday.

Finally, array index errors are relatively easy to debug: the errors thrown tend to point right to the problem.

Fake Random

When your game is being judged, you will be very lucky if someone plays it for 2 minutes. In that time, if a modal pops up and says ‘oh my god a random monster just appeared?!?!11?!?’ then the player will know that this was, as part of the game narrative, a random event.

…does it have to be random tho?

you cheated
in general anything you might want to code that feels like cheating is probably the right thing to do in a game jam

No! And in fact testing stuff that contains random number generators is a hassle, obviously. You can try locking the RNG with a seed but then you haven’t really tested it. Even testing it with min and max values isn’t certain (maybe 1 of your 10 array entries is broken, but not the first or last) isn’t surefire.

Worse, what if when the 1 person whose opinion matters at all tries your game and something possible but unlikely gives him a bad experience? He wanders the tall grass for 10 minutes but no encounters trigger.

I love cruft and noise in games, but for anything other than visual touches, it’ll actually be a better experience for players if you hard-code the path they will follow. One good example for something totally cosmetic: the npc’s in my most recent game said various phrases at random if you failed their task. When I tried it out with each one picking a random phrase, the first 4 all said the exact same thing. So I ended up wishing I’d just ordered my array and stepping through it.

circular references.

Unity makes it real easy to make calls between scripts. Just declare a Public var of type otherscriptname, drag the gameobject into the new field in the inspector, and boom, you can call any public function on the otherscript.

But surely when you’re hooking up GameManager to PlayerHealth, and then later you hook up PlayerHealth to GameManager, your alarm bells will go off that this is a Bad Way To Do Coding.

Here we get to some basic coding philosophy: If this is a bad way to code, you have to know why it’s bad.

When working on code that is a component of a larger codebase, decomposing your code into objects is critical: if someone wants to mess with the ‘audio’ object later, they probably don’t want to have to import the ‘scoreManager’ object. However, if you’re trying to use code you wrote during a game jam on another project later without editing it…

no.

stop.

Interdependence/Circular Referencing does make code a huge hassle to refactor later, but even so you don’t necessarily want to optimize for a problem you’ll never face: if the audio played is dependent on the score, and the score manager needs to be able to play audio, the fact that both scripts reference each other reflects real interdependence.

Anyway this saved me tons of time and I don’t regret it at all.

Some “timesavers” not even I was dumb enough to try

Functions named “DoTheThing()”

partway through the gam I looked up a code example that used ‘foo’ and ‘bar.’ Then it used ‘Foo()’ and ‘Bar().’ note that the variables and the functions were unrelated in this code snippet, creating a pattern in the code where none should be.
gross
While this is unforgivable in a tutorial (I’ve got about 10,000 words in me about why ‘foo’ and ‘bar’ should be banished from the programmer’s lexicon), it’s also just a turbo-bad idea in a game jam.

This gets to a basic assumption which is that someone else is going to be looking at your code. It might be another programmer at this jam, but even if you’re solo it might be you trying to fix something late on Sunday.

If you fill your code with ‘MoveTheThing(float x, float y)’ you’re making it almost impossible to figure out what’s broken when you come back to it. Any logs pointing to this function will be similarly unreadable. So yeah, don’t do this.

If you’re too tired to come up with with helpful names, go to bed. Any code you write will be more trouble than it’s worth.

just one huge script file

This one should be kinda obvious but it doesn’t actually save any time to keep everything in one huge file. If you notice that GameManager.cs has a lot of audio control in it and you should maybe create AudioManager.cs, this might be a refactor that’s not worthwhile while you’re working full-speed, but some stuff is clearly separate from the beginning, like enemy AI and the UI/score manager.

The worst thing about scripts/classes longer than 100 lines or so is how hard it is to to view them all at once. I find myself scrolling up and down constantly to figure stuff out.

Instantiate and Destroy instead of object pooling

I actually think of Instantiate as a kind of insidious anti-pattern. Sure there are times when you can’t avoid it, and it does make it easier to send your project around if it’s just script files that instantiate everything they need from prefabs, but in my experience this kind of stuff is just asking for trouble.

Is it because I don’t understand these functions perfectly and often fuck it up? Yes it is. So, I assume, will you; if you’re a journeyman Unity dev, I’m a bit surprised you’re reading anything I’m writing.

Yeah it’s true that Destroy kicks off garbage colleciton and can hurt performance, but that’s not the reason to avoid this in a game jam.

‘Instantiate’ creates an object that, unless you do stuff with it right then is ‘lost’ in your scene requiring you to find it by tag or brute force later.

Instantiating an object with a collider inside another object causes some crazy Unity behavior.
glitchy gta
approximately 100% of all glitches people post in AAA games are due to object instantiation errors

Above all: this is a very short, small-scope game. If you can’t figure out what objects need to be in the scene before the player starts playing, you’re working on code that’s too robust for the task at hand. If you’re not certain how many cacti you’ll need to spawn, just drop an extra dozen into the scene. Make them the children of an empty object so they don’t clutter the heirarchy, but for god sakes don’t waste time mucking about with the careful management of instantiate.

All this isn’t to mention the problems that arise when trying load or re-load the scene, or call public functions on an instantiated object that isn’t present at build time.

So, this is Agile

SHIP IT
I believe in game jams because they’re a microcosm of what it’s like to be a ‘real’ developer: Not everything is going to get fixed. Not every class you write will be something that people want to hang in museums.

When GitHub first came on the scene there was enormous pushback from people who were afraid to show off code. Often they described projects they had worked on for months or years as ‘unfinished’ and only a ‘finished’ project was ready for people to gawp at.

Git has had it’s own noxious influence in enabling a culture of calling out ‘bad code’ but it’s also helped reveal the reality of development: this world runs on bad code that everyone thought they were going to re-write years ago.

There are certain things I do in game jams that would never fly in my day job, but the best lesson to take away is to use use the tools you have available in a way that makes sense at the time

Even if you end up spending all Sunday debugging the code you wrote Friday night, you’ll have learned something about process. Instead of wasting months producing code you regret, you’ll just have burnt a weekend learning this valuable lesson.

memorization?

I tell people all the time that memorization isn’t necessary or desirable for doing programming. It’s about being able to find answers

but what about that subset of things I find myself looking up all the dang time… like how to format SQL queries?

Turns out there are some times when rote memorization is the right thing! I’m using a Memrise course to learn some JS method names and after that I’m going to try to distill some SQL knowledge into flash cards.

One thing about this process: I know what I can skip now that I’m used to these environments. I have no need to learn all the myriad date functions in JS, but I do need the date math SQL stuff. Here we get to a basic issue in teaching: techniques should only be taught once you’re familiar with the problem you’re solving.

So yeah, I don’t want to memorize everything, but it’s worth it memorizing the syntax on something I type 10 times/week.

I do not want to use React

For many, many reasons but the inclusion of JSX syntax in the tutorial is a super good reason to avoid it.

I still feel what I read about JQuery: strength of the tools aside, ease of learning a framework is what determines its long-term adoption.

People are terrible at knowing Javascript notation as it is and sugaring in alternate syntaxes isn’t going to improve matters.

Okay, I feel grumpy for writing this, I’ve made some cool React stuff in the past, but bleh, I do not want to fiddle with it again right now.

Follow up on running JQuery on some arbitrary Angular Views

I really wasn’t able to get a good answer on the best approach to “run this JQuery on select views.” I could much more elegantly do this on every page, but that feels super sloppy: transforming the aria-label of a bunch of buttons that probably don’t even have popovers seems like it’s definitely going to screw someone up later. “Hey you added popovers to this page that say ‘new!’ on some eqiupment, now the aria-labels are all just ‘new'” “I did not know that would happen.”

This kind of gets us to the core of the problem: yes I currently know that there are no aria-label attributes set anywhere on the site, and that popover text or popover-title text is always what should be label, but there’s no contract in place anywhere that says this should always be true. Two core problems:

  1. For someone editing the view later, this ‘turning the popover into a label’ isn’t terribly predictable behavior.
  2. If I were making this site from scratch, I would never engineer it to do this

I think the best approach may be “manual:” just declare the aria-label whenever a popover or popover-title is being declared.

The advantage of the manual approach is I could tailor some body text, label, and role for each menu button e.g. we could label each equipment button with the items name and include “text” with its stats and whether it’s currently equipped.

It kinda makes sense there’s no prescribed method to programmatically change the views that you just wrote.


So this is part of the drawback of my own experience: I have much much more experience working on giant crufty codebases than fresh ones. That I needed to know the history of why methods were named the way they were, why this was structured like this, all made sense when I was working on a 5-year-old codebase worth hundreds of millions of dollars.

But the whole purpose of something like Angular patterns is to create a site that makes sense even as it’s expanded as if it was created fresh today.

Angular -or- If you don’t use it, you lose it

As it comes time to review 2015, I cannot help but remember my lowest moment.

No, not when I dragged myself, with a shattered knee and snapped wrist, out of a gutter. Not the ten minutes after that while I realized that no one would come running at 6 AM no matter how many times I called for help.

My lowest moment was when I begrudgingly opened an Angular JS tutorial so that I could make a new commit to [Habitica], logged in when prompted, and the codeschool interface seemed oddly greyed out. Finally I realized what it was trying to tell me:

“You have done every one of these lessons already. Even though nothing in the Habitica page templates looks even vaguely familiar, I assure you that early in 2014 you spent dozens of hours mastering almost every technique covered herein.”

The concept of knowledge decay, or knowledge atrophy, had never been put to me more clearly. I had even made a couple of Angular sites around February 2014, but trying to make even a small tweak over 22 months later felt impossible.

Onward and upward, I re-learned JQuery when I needed it, and it took way less time the second time. Hopefully I’ll keep tinkering with Habitica long enough that Angular will be entered into my mind’s permanent stores.

Adding Aria-Label attributes programatically

I’m a recent addict of Habitica, the good-habit-building game that turns your life into an RPG, and I was thrilled when I realized their stack was basically what I knew best (well I thought I knew it well but then oh geez). I took a look for low hanging fruit in their current feature requests, and noticed some comments about screen readers being unable to use the site.

The person I was talking to was using JAWS on Windows, and I don’t have either of those things, but some random googling got me to this great writeup on how to label stuff. I later found Google’s Web Accessibility course which clarified a few things. One thing that kinda baked my noodle: people who can’t see your site see the DOM. That’s what they interact with.

I didn’t really have the rights or the knowledge to mess with Habitica’s DOM structure, but I could for sure add aria-label attributes where appropriate. I started taking apart various views.

Oh first I messed around with Apple’s Screen Reader! It was a little hard to figure out at first, and incredibly annoying when it was trying to narrate what I was doing clicking between seven different windows. But eventually I was able to get it to say ‘button’ about all the 100 buttons on the Habitica inventory screen. Sure enough, that was unusable for the blind.

I started by adding in Labels wherever they were needed. Normally aria-labels are required when you have something like an icon button: something where the sighted will see what a thing is and know right away what it does. In the case of the Habitica inventory, the problem was that the explanatory text was in a popover that no screen-reader would ever activate or read. That meant hundreds of labels needed to be added.

Worse, each kind of icon (equipment, pets, collectibles) were all being instantiated in the view with seperate, similar loops. I had to insert aria-label tags in seven or eight places just in the first view! It was taking time and I didn’t know the Jade Syntax well so I kept messing up.

Eventually I got a page done (one of five) and headed to bed pretty satisfied. Then as I was lying in bed I realized that there was a much better way to do all this.

I’m inordinately proud of this little script. It operates off the knowledge that the text we want to apply as an aria-label is in a popover or popover-title attribute already. It grabs that text and adds a label to every button that had a popover.

So I was really happy! All I needed to do was run this JQuery code on every affected page and they would work, yay!

I found myself pretty stymied, though, by figuring out where to put this code… A… service? One of the routes? A controller somewhere?

This script overwrites any existing aria-label attributes, I didn’t want it running on every page, so adding it to the footer was wrong.

I ended up include it in the target pages’ views and plunking a .js file down in that folder, which is in “/views/” so I know that’s not ideal, but I think I need to study Angular patterns a bit more if I intend to do anything that’s as reliable and simple as my kind of hacky answer.

Cronjobs on OSX

Well, I’m not doing something right but still this is pretty interesting. My terminal started printing ‘you have mail’ above the bash prompt, and I couldn’t figure it out.

Eventually I found that there was a new file in /var/mail/[myusername] that had a log of the cron jobs I tried to create failing.

I think the user the cron is running as doesn’t have access to Node, so I can’t just run a node script direct from cron. There should be multiple possible fixes for this, but I’ll fiddle with it tomorrow.

Still, interesting!

Piping stuff together with Linux

I blew two interviews by not knowing the Linux command line well enough. Well, I blew the first one, the second I was just slightly shaky.

The test was to sort through a million-line logfile. I’m ashamed to say it but for the first test I started writing a tool to do this in Node.

The answer, of course, is to chain up some Linux functions, probably grep and uniq will do it.

Anyhoo After that I studied this a bit and learned what I needed to answer that exact question, but this week I started reading a book on the command line and it’s been super helpful filling the corners.

It is extremely helpful when learning the command line to be using a virtualbox (or VMWare) machine hosted on OSX. My text was The Linux Command Line by William E. Shotts, Jr., and this text was rather catholic about not being a book for every possible weird unix command line, focusing almost entirely on Debian builds.

Therefore it’s really nice when learning something to have an osx terminal open just so you can check ‘does this stuff work over here?’

How to test on every browser with an OSX machine

This will show you how to do heavy multiplatform QA on a browser from OSX, especially when the page you want isn’t public or requires user action, like a login. We’ll cover IE6 and up, Android, iOS on multiple devices, and MS EDGE.

So this comes up pretty often: you want to make sure that your cool new interface works everywhere. Your site is used by the public, and it turns out people who have IE 7 are also not the smartest shoppers, making them good customers! So how do you do this starting on OSX?

So there are several tools that will load a site from a URL you feed it and show you the output in many browsers, but I’m going to dismiss those because I’ve never ever been able to use them. Why?

Multi-browser testing sites are worthless

  • Almost everything I work requires a login. None of these services support this without some goofy scripting

  • most show you a .png of the site as it loaded. Okay, do the drop-downs work? How does the site handle window resizing (on IE 8 and later, earlier and there’s no media calls)? Can you open the file that your cool gif-making site spits out?

  • My site isn’t publicly avaialable at a all! Somehow these tools don’t accept https://localhost:4043!

so your mileage may vary but I’ve tried and failed to use these so many times I just quit. Here’s how I do it:

The right way: virtual machines and lots of them.

Part the first: Windows

It might be tempting to think of using boot camp, the super-cool tool that lets you install Windows on your mac, but don’t do that. After a very long process installing windows, you’ll find it’s very difficult to change versions of Internet explorer on one install of Windows, and there’s no single OS on which you can test IE 6 all the way up to EDGE (or even IE 8 and higher), so you’d have to install several boot camp images, which will totally fill your hard drive before long.

Let’s start with the hardest things to test: IE on Windows. For these, Microsoft has a cool service set up. All you gotta do is:

  1. Go get the virtual machine tool VirtualBox and install it. Virtual Box is a tool set for running and organizing virtual machines. If this sounds like gibberish: virtual machines are a copy of all of the hardware of a computer in a virtual environment, borrowing resources from the real machine. Virtual box needs an ‘image’ to run, though you can download free OS’s like ubuntu and install them to make your own virtual computer.

  2. Go grab some Mac virtual machine images from Microsoft at https://dev.modern.ie/tools/vms/mac/, they’re big files so it will take some time, but look at all these options!

Virtual_Machine__VM___Windows_Virtual_PC___BrowserStack___Microsoft_Edge_Dev

  • Talk to your team about what ones you need to test, these images are free moneywise but they’re a hassle to manage, you don’t want ones hanging around you don’t need.
  1. open one of these images with Virtualbox. little niggles:

* one of the set didn’t open for me until I got The Unarchiver
* these images are big! clear off your hard drive if you want to keep this stuff around. The nature of virtualization means there’s no real way to avoid storing an entire OS on each of these images

  1. BOOM! Windows! Most front-end people don’t consider it necessary to test Firefox and Chrome separately on Windows, but you can install software as normal on these machines if you need to test software installs or files opening

Part the second: Android

I’m going to be a bit lazy here, and use Bluestacks, which is its own funny build of Android specially adapted for playing on the PC. The main problem (that I’m aware of) is that the screensize is just some arbitrary size, though of course you’re not testing for any weird bugs with certain Android versions. To do both of those kinds of testing, use Android Studio which can run tons of different size devices and different Android versions. The thing is this process is a hassle and I was never able to find a bug like this.

However if you’re supporting a fleet of kiosks with an exact pixel size, use Android Studio

Part the Third: Soooooo many ipads

We’ll launch our iOS simulators from XCode, a process that has actually gotten much easier in the last year since XCode now lets you start in ‘playground mode’ without creating a whole project you’ll never use.

You may need to fully install/update Xcode to get it working, and in classic Apple fashion the button keeps

  1. launch XCode and select ‘playground mode’
  2. Xcode > Open Developer Tool > Simulator

Open_Developer_Tool_and__and_Menubar

By default it will load into the iPad Retina simulator, but you can go to Hardware>Device and go all the way back to the 4s. Cool, right? Not really! all of these versions will be great for checking display size, but they all run the same version of iOS. Beyond finding an old device, I’m not aware of a great way to test before iOS 8.1, but if you go to ‘manage devices’ you can add an iOS 8.1-8.4 device.

Device_and_Hardware_and_Menubar

Naga!

So after a few Twitter experiments that never saw the light of day I finished Naga last week, and it totally works!

Some things I learned:

  • running SQLite is nonsense and no one should ever do it. I had a lot of trouble getting a SQLite console to access the stored DB file, meaning I was kind of operating blind for stuff going into the DB without logging. That was lame!

  • Logging in JSON is convenient

  • a bunch of Twitter API things that are supposed to be limited aren’t limited e.g. blocking. Some like faving totally are.

  • Mocha is fun.