Building a clicker game with React

It’s really easy to make a big ball of mud in JavaScript.

You start with a simple loop. You want your program to do A, B, then C. Great. But then you realize you also want D, E, F, G, H, and I. Before you realize it, you have dozens of functions spanning hundreds of lines with no clear structure.

So you try to create structure after the fact. You start putting related functions into separate files. Everything’s global anyway, right? So you just have to add a script tag for each file and everything works. Easy. The problem is when you can’t easily isolate variables and functions and you end up cross-pollinating your files and creating circular dependencies between them. File C is dependent on a variable in File A, because several functions in File A also need that variable, but it doesn’t make sense to move the function from File C to File A. You could use a hackneyed include library, but why add more dependencies? It was just supposed to be a simple app.

Sure, some of these problems can be fixed with a better design, but you’ve already come this far and you don’t want to start over. So you carry on, adding features as needed. Then you take a few months off and forget everything about the app. When you are finally forced to face it again, you just want to scream in frustration at this giant ball of mud past you left for you to deal with.

With vanilla Javascript, you can hack your way to a ball of mud in short order, and there’s not much to slow you down or keep you from chopping off your feet.

What can we do?

Probably not much, except learn from the experience and do slightly better the next time. It’s an iterative process, after all. Don’t sweat the petty things.

Frameworks like React can help, but the barrier to entry is a little higher.

React in particular helps this problem by isolating all functionality into appropriate components, and having clear relationships between parent and child components. Each component has a collection of state variables (or in the case of stateless components, a collection of inherited properties instead). It’s never be a mystery where a value is defined or where properties are coming from.

In addition to state management, React saves us a lot of time by handing component updates for us. Instead of having to lovingly (or bitterly) hand-craft each and every DOM update with jQuery, React listens for changes to states of components and updates all dependent components automatically, without a page reload.

So Let’s Build Something Already

I’ll cover the major steps in building a working prototype text-based adventure game in React, with a simple grid-style map and a compass for navigation.

  • Game Design
  • GUI Design
  • Component Hierarchy
  • Styling
  • The Game Loop