Becoming a Slower Coder

Project 2: Additional observations about our approach

This project (“Whack-A-Mole,” Project 2) is fundamentally more challenging than the last. It has more moving parts — literally: It has to store different kinds of data, is looking to understand varieties of player input, and to top it off, is built on top of an endlessly-repeating loop (which is built into the gopher’s STEP event), whereas the previous project was fairly linear (the EightBall code started up, waited for a cue, and then delivered its data to the player).

All of this makes for a more challenging project than the first one. That is intentional. But it is also clear — based on the conversations that we’ve been having in and out of class, that this challenge often feels alien and uncomfortable, especially for those of you for whom code is new (AKA, you’ve been writing code for fewer than 2 years). In the same vein, many of you have suggested to me that this process is completely different from the experiences you are having in other courses.

That’s a great observation, so let’s talk about that for a moment.

For the most part, nothing that most of us encounter in college is completely new: Say you take a course on post-WWII Japanese cinema, or Grand Guignol theater in early 20th Century Paris, or the aesthetics of designing for mobile platforms. Even if you know nothing about the history of Japanese cinema, for example, or the French stage, or digital aesthetics, those courses are still likely to feel loosely familiar because you already know a lot about, say, how to read novels, or how to watch movies, or even how to use a web browser on your phone. Because, look: Even if you aren’t consciously aware of those parallels (“the Grand Guignol theatre is like a horror film,” “contemporary app design standards owe a lot to digital aesthetics on mobile platforms”) your infinitely plastic, endlessly playful brain is constantly looking for patterns that seem to repeat across superficially dissimilar concepts, disciplines, institutions and behaviors. Pattern recognition is what we do: Identifying even the smallest similarities between a thing we know, and a thing we don’t know, is how we get our foot in the door to better, deeper, and faster understanding of… well, nearly everything.

Nearly everything.

Code — especially for novices — does not work like this, though. In this respect, coding can feel like an alien experience: Complex and full of knots and tangles and confusion, and it often seems fundamentally different than most of the other knowledge domains you’ve been carefully mastering for over a decade now.

So why can code often feel so alien, so endlessly confusing? Why is learning to code sometimes infuriating, in a way that working through your Intro to Health Sciences textbook is not?

In my experience, code is hardest when we approach it like we do our courses in Japanese cinema, or French theatre, or mobile design. The thing is that we are GREAT at learning almost-new things. We pick that stuff up quickly, and often intuitively. When we read a textbook, or watch a film in a foreign language, or learn about the history of some technology, we are constantly short-circuiting the process: We don’t advance the film one frame at a time; we don’t learn about a city by identifying each building and every citizen, one by one.

We’ve learned to work in chunks, a process at which our brains excel: A word (like the word “word“) is really a series of 4 letters, one after another. And each of those letters is really just a collection of black strokes carefully organized on the page, precisely arranged, one next to the other.

BUT WE SELDOM SEE THEM THAT WAY: Instead of a collection of vertical and horizontal black strokes organized into 4 tiny groupings; instead of the letters W, O, R, and then D, we perceive them as a single unit, “word.” In fact, in many cases, we can look at a sentence or a paragraph, a chart or a photograph, and understand what we’re seeing immediately: We don’t always have to reduce a thing to its component parts to understand it. Despite what our parents told us, we have learned that we can judge a book by its cover, or an album from one song. We are very often right, and we get better at it every year.

But (to my mind, at least) that’s where learning to code causes trouble. We keep wanting to understand and manipulate code in chunks, but we can’t. Not yet.

The time you invest in each project will be far more remunerative if you insist on slowing down and try not to see things in “chunks.” Instead, force yourself to work line-by-line.

Before you move from one line to the next in your code, for example, ask yourself:

When GameMaker encounters the line of code I just wrote, do I know exactly what will happen? Or do I just have a sense that the line of code I just wrote seems always to appear in programs like this oneā€¦ but I don’t know exactly what it does. There’s nothing wrong with the latter (we’ve got to start somewhere). But you want to insist on getting to the former more often.

  • If you often find that your code works, and then it doesn’t, and then it kinda does, but finally you have absolutely no idea why the outcome keeps changing;
  • if you look at the code in your own game and discover that you’re pretty sure there is stuff in there you have never seen before; or
  • if you find yourself changing one seemingly trivial detail and suddenly unable to run your program;

Then the best fix is probably a good opportunity to rethink how you are approaching this process.

And that is what I want to emphasize, as I have before: In my experience, learning to code is mostly about learning to make sense of things on a much smaller, much more exacting scale than we do otherwise in our lives. Learning to code is about forcing yourself to read your code line-by-line, slowly and methodically, instead of trying to understand everything in big, baroque chunks.

Now: Doing this does not magically make all of your problems go away. But you knew that already. What it can do is help prevent the downward spiral of confusion and frustration that lots of novice and intermediate programmers get ourselves into.


These are things I’ve already suggested, but I’ll repeat them, now and later, as they are fundamental to this practice:

Whether you are attacking the whole game, from splash screen to game over screen, or if you are trying to make a specific thing happen at a particular moment, you must force yourself to begin from a non-technical version of what you’re building. You will not be successful by just jumping into GameMaker and writing code. You will not be successful by just “thinking it through,” in your head, and then jumping into GameMaker and writing code. All of us shoot from the hip occasionally, of course, but that will seldom work out well for you. Yes: It often feels foolish; slow; childish. Dumb. It is not even even vaguely sexy. But in the end, it is an absolutely necessary part of this process. We’ve already modeled several approaches, and will continue to model more: Some of you may make use of comprehensive outlines, some of you may describe events in paragraph form, some of you may create flow-charts or graphical descriptions of the code you’re writing. But — one way or another — it has got to happen.

One side benefit of doing this, of course, is that you can worry about the logic of a process without necessarily worrying about the specifics of the programming language. It lets you think about things on a level of abstraction that we commonly associate with fun (the same abstraction as is common, e.g., in crosswords and television procedurals).

I’ll come back to this later this week as we start Project 3. But to provide you with another concrete example of what it looks like to insist on this kind of specificity, this kind of granularity, let me share with you four or five iterations of my Whack-A-Mole pseudo-code. Each pass is another opportunity to un-chunk my assumptions and work towards irreducible statements.

“Draw the gopher holes and have the gophers randomly appear”

“Controller creates gopher holes and gophers in one swoop; each gopher goes up and down according to an internal clock; if we click on them they die.”

Controller creates back of hole on bottom layer,
Gopher on middle layer,
Front of hole on top layer, using same x value for consistency;
Each gopher has a clock that increments regularly, in tiny amounts;
Redraw each gopher with new Y based on sin() of that clock;

By pass FIVE (excerpted here, because it has gotten pretty long by now), I’ve finally gotten to asking YES/NO questions (which is what I’ll need the computer to do, too):

With every single loop of the STEP event, ask: Did someone just click? AND Was the click ON a gopher? AND Is the mouse NOT on top of the gophers’ burrow? AND is the gopher NOT dead? Affirmative to all? Then: Show the “dead” gopher, add to score, and slow down the animation.

The code that comes out of this ends up at the bottom of my gophers’ STEP event loop. It’s a fairly 1:1 translation of the above pseudo-code.

if (isLMBPressed && isMouseEnter && !isDead && !myCraterID.isMouseEnter ) {
	image_index = 1;
	image_speed = 0;
	clockspeed = 0.009;
	score = score + 5;

While we’re here: That first line is a great place to ask “Do I know exactly what this code is up to?” Here’s the low-down:

If (condition1 && condition2 && condition3 && condition4){ 
    do this;
    do this;
    and then do this;

“IF( )” always means “If the following expression (or formulae or variables or statements) can be resolved to be TRUE, then do the code that appears inside the curly braces. Otherwise, skip the whole thing.”

&& means “perform a Boolean AND operation.” Boolean operations are just teeny tiny little rulesets. They never ever vary. To explain the above code, let’s imagine you are writing a search query in order to find a file on your computer. You know a few things about the file:

  1. It is a JPG file;
  2. It is bigger than 200k in size;
  3. It is definitely NOT in the WALLPAPER folder.

So I could create a set of outcomes for each search requirement, and gradually shrink my field of possible answers by looking for common members across all the sets. OR I could let the computer do it. Maybe it would look something like:

file type == .jpg
size > 200k
folder != "user/garrison/wallpapers"

If we test every file on your computer against these parameters, the computer will only return the files that answer TRUE to each of these three conditions: Is it a .jpg file? AND is it more than 200k in size? AND is the folder it is store in NOT /user/garrison/wallpapers?

So each “condition” can be isolated and determined to be TRUE or FALSE. And the boolean operations allow us to say ensure that all three conditions have to be TRUE for a file to be included in the results.

Which brings me to that last thing: The exclamation point (sometimes called a “bang” or a “boolean NOT”). Do you remember “opposite day” from middle school (ah, the endless charm of public education!)? A Boolean NOT is basically a symbol for “opposite day.” In the case above, it specifies that the folder must NOT equal “/user/garrison/wallpapers.” Earlier, one of the conditions I was checking was to see that my gopher “!isDead”. Remember first that “isDead” and “isDead == true” are both the same statement: We often just take out the “==true” part because if() conditionals are always ONLY interested in finding out what things are TRUE. So in this case, “if (!isDead)” means “if (isDead == false)”.

Sorry, way too long. We’ll pick this up again on Tuesday.

A Quick Whack-A-Mole Review

I’m still working through the questions, examples, and problems you’re sending my way. I’ve got a few more things to upload too, but I’m out of time today, and can’t get back to this until Sunday early AM.

With that in mind, and hoping to reach the broadest possible audience, here is a quick video that reviews the loop I’m using in my quick Whack-A-Mole mock-up.

As I say, there are a few more things coming, but probably not until tomorrow AM.

Note: The video is still uploading to Vimeo and I don’t have an address for it yet. It should be the first video on this list, however: It may not be visible until 7PM on Saturday (today).

Finally: Here’s a copy of the source code for Space Gophers Something Something, the code I discuss in the 45 minute video, above.

More demo goodness

For today’s workshop, here’s a demo I just put together. It makes use of:

  • Spritesheet import;
  • Music / sound;
  • Multiple rooms / room switching;
  • Alarms / timers
  • Special effects (really just an explosion object)

You can download the demo here. Sorry for not having time to add comments — please follow along in class and annotate as useful. If I have time this weekend, I’ll revise this with full comments.

Planning Suggestions Project 2

Some ideas about how you should proceed, if you’re not yet proceed-ing.

  1. Start with a sketch of the game board and explanation of gameplay;
  2. Simplify that sketch (take as many details out as you can bear! You can put them back later!)
  3. Now describe your gameplay (your “game loop”) drawing exclusively from that sketch;
  4. Simplify and condense your game loop to its most essential elements;
  5. Add the stuff that needs to go before and after the game loop in order to make things work (e.g., “Show game board”, etc.);
  6. Now divvy that outline into phases for building (a to-do list);

In a separate phase, then, do more strategic planning.

  • Decide on immediate, mid-term, and due-date goals;
  • Decide on bonus outcomes and opportunities, etc.;
  • Map things out to a calendar (our Second Project is tentatively due on Sunday, 26 September, by Midnight);
  • Be as explicit here as you can stand to be.

Some miscellaneous suggestions: Problems you may need to solve. Keep in mind that you don’t always have to solve these problems in order — but resist the temptation (wherever possible) to skip around randomly without actually finishing any single task: That approach is a disservice to the work you’re doing, and will (usually) end up putting you in a bad position.

  • Figure out how to get a single gopher instance to appear and disappear — without making all of them do the same;
  • Figure out how to detect if you’ve clicked on a gopher at the right time;
  • Figure out how to assign points for that event;
  • Can you determine which gopher you’ve just clicked on?
  • Figure out how to record an increase in score after successful click;
  • Can you make those points appear in the place where you just clicked? Even as you remove the gopher from the screen?
  • Figure out how to vary the gopher animation;
  • Figure out how to gradually increase difficulty.


For no particular reason, here’s a bunch of cookies orbiting around Cookie Monster.

Cookies float around Cookie Monster.

Some of the things going on in this code include:

  • Programmatic object instantiation (the Cookie Monster creates a random number of cookies) — their placement relative to the center of the screen is then calculated and saved back into each cookie instance;
  • Using instanceID handles;
  • Randomizing names using an array (and assigning the outcome to each specific instance);
  • Detecting the closest cookie instance to your mouse (and returning the instanceID);
  • Drawing text and shapes over an instance;
  • And probably some other things, too. Questions? Let me know!

Here’s the package.

More Nested Loops

for() loops are so important to understand thoroughly. This tutorial shows you how I create the side of a building by making a window out of a sprite, and then carefully calculating how to squeeze as many on the surface of the building as possible. Download the code below.

Once the windows are installed, you’ll notice that you can mouse over them to turn the inside lamps on — but they’ll go out in a random amount of time.

An unpleasant building.

The blinking blue star is my “controller object” — it builds the building, etc., but doesn’t do anything after that. Note that the building surface itself is just a sprite I’ve dragged onto an independent “Asset” layer — not the “Instances” layer itself. I can do that because the building doesn’t have any code to run. Just the windows (which are placed programmatically on the “Instances” layer, where their code can run.

If you have time, there is a tiny bit of code in the Mouse Enter event that deals with setting an Alarm — a timer — that can be useful.

Nested Loops

A for() loop lets us repeat a task a certain number of times. Put one for() loop inside another, and suddenly you’re the Mayor of Repeatsville (I dunno what that means either, just work with me on this.)

Let’s start with a quick reminder of how for() loops work when they are young, single and sassy:

for (var x = 1; x < 4; x = x + 1) {
// do everything inside those curly braces
// AKA "a code block"
// When that for() loop finishes, it
// will leave the code block and come here next.

As a reminder, here’s what is happening in that for() loop.

  1. We start with a temporary variable, called x, which we set to 1.
  2. Then we do everything in the code block (anything between those curly braces on lines 1 and 4).
  3. When we finish that code block, and we hit that bottom curly brace on line 4, we’re still “doing” the for() loop — so we go back to it (on line 1).
  4. It tells us to add one to x.
  5. If also tells us that if x is still less than 4, then we should do the whole code block again (this time, though, x is 2).
  6. Finished with the code block? We’re still inside the for() loop, so go back to it (on line 1).
  7. It tells us to add one to x.
  8. It also tells us that if x is still less than 4, then we should do the whole code block again (this time, while x is 3).
  9. Finished? Cool. Go back to the for() loop statement on line 1 again.
  10. It tells us to add one to x, which means x is now at 4.
  11. It then asks (just like it has before) is x < 4? This time, obviously, the answer is no. So we don’t just repeat the code block again. Instead, we make a hasty exit to the next line of code that is outside of our for() loop. In this case, we’d jump down to line 5.

The Assistant-Manager Approach to Nested Loops

So then how does a “nested for() loop” work? We’ll use them a lot — and they seem complicated, but if you break each step down, I think you’ll find that you get a lot of predictable (if tedious) steps that make sense.

First bit of advice: As before, don’t get hung up on the idea of “nested for() loops” as overly technical. Think of them instead as a way of accomplishing familiar tasks. For example, imagine we run a fancy-shmancy 5-story boutique hotel. Well, not “run” technically, as we’re Assistant Manager, not Manager. But you and I both know that the Manager leaves most of the important stuff to me, so I might as well be Manager.

Anyway, imagine that every floor of this hotel has four rooms. Five floors, four rooms each: That’s 20 rooms in total. So when I need to print out new hotel keycards — the little credit-card sized digital keys that we give to guests — I could type each one out by hand, but I could also create these keycard codes computationally.

Now imagine the keycard code looks like this: “3FL/RM4.” To us hospitality (“assistant”) management types, that means 3rd Floor, Room 4. (It isn’t as easy as it looks!) Try this one: “1FL/RM2.” That would be First Floor Room 2. (You’ll get there! Not everyone is cut out for the “assistant” manager roles). Anyway, here’s how we might think of the keycard generator in “pseudo-code” — our natural-language description of the process.

  1. Count off our hotel’s floors, one-by-one, starting with the first floor and not going past the fifth floor;
  2. For each of those floors, count off that floor’s rooms, one-by-one, starting with the first room but not going past the fourth room;
  3. Take the floor number and add the characters “FL/RM”;
  4. Now add the room number to that string;
  5. That’s the keycard code! Print it out or whatever.
  6. Keep looping through each of the rooms until you run out of them;
  7. Finished with the room loop? Now go back and do the next floor. When we do that, the first thing we come to? OH ITS THE ROOM LOOP AGAIN SO MUCH FUN. So I guess we get to do that again. In this numbered list, that means going back to step 2 again! Re-starting our room numbers from 1! Joy!

If we looked at a list of the keycards generated this way, here’s what we’d see (in the order they were created):


OK: Let’s translate that common-sense series of commands into something the computer can cope with. Here is the code above translated into GameMaker Language. In this case, I push the output to the debugger window.

for (var floor = 1; floor < 6; floor = floor + 1) {
  for (var room = 1; room < 5; room = room + 1) {
    var myKeyCode = string(floor) + "FL/RM";
    myKeyCode = myKeyCode + string(room);

Some things to notice:

  • We have 5 floors, so in my code, I say (in line 1) “as long as floor is less than 6″ (which makes sure the loop only quits running AFTER it does the 5th floor). I could also have done this (less common, but just as valid):
for (var floor = 1; floor <= 5; floor = floor + 1) {
  // note that <= ("less than or equal to...") works,
  // but "equal to or less than" (floor =< 5) gives an error.
  • Pay attention to the indentations / tabs. While sometimes they get messed up (usually by us — the computer tries to use them wherever it can) those indentations are a good indicator of where a new block of code starts. See how everything is indented below the SECOND of the for() loops (lines 3-5)? And see how THAT for() loop and THAT code block are indented beneath the FIRST for() loop? Those indentations (which go hand-in-glove with the curly braces) help us understand how some code “fits inside” other code.
  • Because they are nested, note that the two for() loops actually do a very different amount of work. The outermost for() loop seems to do much less work, while the innermost for() loop does a lot of work.

Let’s test that idea:

Let’s say for a minute that we could somehow attach lights to each for() loop in order to see when the computer was running that code. Let’s put a Red light on the outermost loop (in the case above, the Floor counter) and a Green light on the innermost loop (in this case, the Room counter).

Here’s what we’d see (I’ve consolidated it to one line to keep it shorter!)