“Pick the most boring approach to every problem you encounter; if you can think of an exciting approach to solving a problem, it’s probably a bad idea.”

If this is how you’d paraphrase most of the advice in this book, I wouldn’t blame you. A lot of these Rules can be a bit of a buzzkill. They point to some interesting or clever technique you might use to solve a problem, then immediately inform you that it would be a bad idea to use that technique. And it’s true that the simple, boring approach is almost always the best approach. But only almost!

On some very special occasions, the clouds majestically part and you’re bathed in the warmth of a single ray of sunlight spearing down from the heavens to illuminate you at your keyboard. 1 And in this brief, glorious moment, you realize that it would be simpler and easier to solve a more general version of whatever specific problem you’re working on.

Revel in these occasions, because they don’t come very often. When they do come, be ready to take advantage. Write the simple code, solve the general problem, and glory in the moment.

Jumping to Conclusions

Here’s an example . In one of the early Sucker Punch games, the player bounds through levels as the master raccoon thief Sly Cooper. Sly is very agile, leaping into the air, then landing on tiny outcroppings or alighting on thin tightropes strung between buildings. The controls are simple—press the X button to jump, bend Sly’s midair trajectory (in a physically impossible but entirely believable way) using one of the controller’s sticks, then press the O button to land on things like spires or tightropes.

Of course, there was code to make this all happen! 2 The trickiest bit of that code handled choosing the place where Sly lands when the player presses the O button. The player knows where they want to land when they press O, and the game needs to guess the player’s intent somehow. When the guess is correct, the player doesn’t even notice the magic; when the guess isn’t, the player is very, very frustrated.

Guessing the landing spot the player has in mind is much easier said than done. Imagine that the player is steering Sly toward a tightrope and there are no other possible landing spots nearby. The code needs to decide where on the tightrope the player is trying to land. What’s the algorithm for choosing this point?

The simple answers don’t work very well. Steering for the point on the tightrope closest to Sly’s current location doesn’t work very well—if you’re jumping along the tightrope, you’d get sucked backward to the point you were over when you pressed the button. To avoid that particular problem, the code could project Sly’s current trajectory forward, then land on the point on the tightrope closest to that trajectory. That’s a better solution, but it still broke badly in common cases. And in fact these seemingly simple answers weren’t at all easy to implement, given that the tightrope was actually a cubic curve, not a straight line.

Cue a long sequence of increasingly desperate prototypes, each trying some new hacky heuristic to solve the problem of landing on a tightrope. This went on for weeks. Painful, painful weeks. 3

Until, one day, the metaphoric clouds opened and a metaphoric beam of light hit me at the keyboard as I struggled with yet another doomed prototype. The problem was that I was thinking small, and I needed to think big.

I’d been looking for an analytic solution, trying (and repeatedly failing) to find a single magic function that would spit out the best position given the inputs—Sly’s position and velocity, the player’s input on the controller, and the geometry of the tightrope. I didn’t want to calculate the best landing point on the tightrope, I now realized—what I really wanted was to write a function that would evaluate the appropriateness of every single point on the tightrope, then choose the best one.

Well, not exactly. I didn’t actually need to evaluate the function for each individual point on the tightrope—I only needed to find the point that was most appropriate. I needed to minimize a cost function (measuring appropriateness) over a domain (a parameter identifying the points along the tightrope).

In short, I had an optimization problem. If I solved the bigger problem of finding a local optimum for a function that mapped floats to floats, then wrote a cost function for Sly landing on a point, I could find the point with the lowest cost. If the cost function matched what the player had in mind, then the game would choose the right point on the tightrope .

The golden section optimization algorithm is pretty bulletproof and not hard to implement: 4

float optimizeViaGoldenSection(
    const ObjectiveFunction & objectiveFunction, 
    float initialGuess, 
    float step,
    float tolerance)
{
    // Track a domain + range pair for the objective function

    struct Sample
    {
        Sample(float x, const ObjectiveFunction & objectiveFunction) :
            m_x(x),
            m_y(objectiveFunction.evaluate(x))
            { ; }
        Sample(
            const Sample & a, 
            const Sample & b, 
            float r, 
            const ObjectiveFunction & objectiveFunction) :
            m_x(a.m_x + (b.m_x - a.m_x) * r),
            m_y(objectiveFunction.evaluate(m_x))
            { ;  }

        float m_x;
        float m_y;
    };

    // Get an initial triplet of samples around the initial guess

    Sample a(initialGuess - step, objectiveFunction);
    Sample mid(initialGuess, objectiveFunction);
    Sample b(initialGuess + step, objectiveFunction);

    // Make sure the "a" side has a smaller range value than the "b" 
    //  side. If we haven't lucked into an initial range bracketing a
    //  minimum, we'll travel toward "a" until we find one.

    if (a.m_y > b.m_y)
    {
        swap(a, b);
    }

    // Find a point where the "mid" range value is smaller than the 
    //  "a" and "b" range values. That guarantees a local minimum
    //  somewhere between a and b.

    while (a.m_y < mid.m_y)
    {
        b = mid;
        mid = a;
        a = Sample(b, mid, 2.61034f, objectiveFunction);
    }

    // Loop until we've got a tight enough bracket on the domain

    while (abs(a.m_x - b.m_x) > tolerance)
    {
        // Makes sure the "a" side brackets a bigger domain than the 
        //  "b" side, so that the golden section is taken out of the
        //  bigger side.

        if (abs(mid.m_x - a.m_x) < abs(mid.m_x - b.m_x))
            swap(a, b);

        // Test a point between the "mid" sample (our best guess so 
        //  far) and the "a" sample. If it's better than the mid
        //  sample, it becomes the new mid sample and the old mid
        //  sample is the new "b" side. Otherwise, the new sample
        //  becomes the new "a" side.

        Sample test(mid, a, 0.381966f, objectiveFunction);

        if (test.m_y < mid.m_y)
        {
            b = mid;
            mid = test;
        }
        else
        {
            a = test;
        }
    }

    // Return the best domain value we found

    return mid.m_x;
}

Once the general-purpose golden section algorithm implementation was tight, I could implement an objective function for falling to the tightrope. Tightropes were modeled as Bezier curves , one of many ways to represent a cubic curve. To simplify the actual code just a bit, the objective function is the time it takes to fall to the landing point (meaning that points the player can land on earlier are preferred) times the maximum acceleration needed to land on that point. The context required to calculate this, like Sly’s current position and velocity, is part of the object that implements the objective function :

struct BezierCostFunction : public ObjectiveFunction
{
    BezierCostFunction(
        const Bezier & bezier, 
        const Point & currentPosition, 
        const Vector & currentVelocity,
        float gravity) :
        m_bezier(bezier),
        m_currentPosition(currentPosition),
        m_currentVelocity(currentVelocity),
        m_gravity(gravity)
    {
    }

    float evaluate(float u) const override;

    Bezier m_bezier;
    Point m_currentPosition;
    Vector m_currentVelocity;
    float m_gravity;
};

The evaluate method isn’t very complicated:

float BezierCostFunction::evaluate(float u) const
{
    // Get point along curve

    Point point = m_bezier.evaluate(u);

    // Calculate how much time it will take to fall to the height
    //  of that point

    QuadraticSolution result;
    result = solveQuadratic(
                0.5f * m_gravity,
                m_currentVelocity.m_z,
                m_currentPosition.m_z - point.m_z);

    float t = result.m_solutions[1];

    // Assume we scrub off all horizontal velocity before landing

    Vector finalVelocity =
        {
            0.0f,
            0.0f,
            m_currentVelocity.m_z + t * m_gravity
        };

    // Get immediate and final accelerations...since we're
    //  following a cubic curve one of these will be the maximum
    //  acceleration

    Vector a0 = (6.0f / (t * t)) * (point - m_currentPosition) +
                -4.0f / t * m_currentVelocity +
                -2.0f / t * finalVelocity;

    Vector a1 = (-6.0f / (t * t)) * (point - m_currentPosition) +
                2.0f / t * m_currentVelocity +
                4.0f / t * finalVelocity;

    // Ignore acceleration in Z, since we know that's gravity

    a0.m_z = 0.0f;
    a1.m_z = 0.0f;

    // Calculate cost function

    return t * max(a0.getLength(), a1.getLength());
}

Running the golden section optimizer on this function produced a landing point that felt more or less natural. It did require some tuning, and I’ve left the edge cases out of the evaluate implementation, 5 but even the first results were better than the long string of failed prototypes this solution replaced. After tuning, it felt completely predictable and natural—and in practice, players trained themselves to match the cost function, and the game guessed what they had in mind nearly all the time. 6

As a rule, it’s almost always better to solve the specific problem you do understand rather than trying to solve a general problem you don’t understand. Generalization takes three examples, per Rule 4 . But that truth isn’t quite universal—sometimes the general problem is easier to solve than the specific one. In this case, the specific problem of choosing a spot for Sly to land on the tightrope was hard to solve, at least analytically, while the general problem was relatively easy to solve .

Finding a Clear Path Forward

Time for another example drawn from the annals of Sucker Punch history…this one a bit more recent. In Ghost of Tsushima , the player can make a short, explosive dash, usually to avoid incoming attacks. They deflect a stick on the controller to choose a direction, then press a button to dash. Poof! Our samurai hero, Jin Sakai, dodges in that direction and danger is averted. Or at least that’s what it feels like for players.

Jin doesn’t always dash in exactly the direction the player has chosen. If the player is fighting enemies in a forest, say, it’s no fun if Jin dashes straight into a tree—even if, strictly speaking, that’s the direction the player has chosen. Nobody wants to be a clumsy samurai! Instead, the code chooses a direction to dash that avoids all the trees, while staying close to the direction the player has chosen. The player is none the wiser—they feel graceful instead of clumsy, and everyone’s happy.

The Sucker Punch engine has code to do this sort of pathing through the game environment—roughly speaking, to try to reach the far end of a search area while skirting areas the player can’t move through. To oversimplify the code: it checks the line segments starting from an initial point to the end of the search area, wraps around any obstructions we encounter, then straightens out kinks in the resulting path as best it can. To undersimplify the code, it’s A* over a discovered graph. 7

Using this pathing code as is was a great start toward natural-feeling-but-graceful dashes, but it wasn’t good enough to ship. Jin dodged gracefully through trees, but blundered clumsily into other characters, whether they were enemies or allies. The obvious fix was to adjust the pathing checks to include characters as well as trees. That was not something the existing pathing code knew how to do! It worked against the fixed obstacles in the environment, like trees and buildings, but it knew nothing about temporary obstacles, like an enemy character charging at the player.

It didn’t seem too hard to add that support, though, so that’s what I did. Remember that at a simple level, the pathing code checks for the intersection of a path with obstructions. If the path runs into an obstruction, the pathing code builds a new path that wraps around that obstruction. So adding support for characters meant two things: checking for intersections between the path and characters, and wrapping paths around characters. Neither was too hard, though it was all new code because characters were represented as circles. And a bonus problem was added—I needed to worry about the intersections between the space carved out for characters with environmental obstacles, and the intersections between characters themselves. All of these intersections were plausible endpoints to the path.

Ugh. This worked, but it meant a lot of new code to handle a lot of new cases. This made the complicated pathing code even more complicated, all to handle the special case of player dashes. Then I discovered that the simple circular obstacle I was carving out for characters didn’t work very well for moving characters, so I switched to lozenge-shaped obstacles instead 8 —and things got worse. The extra complexity I was adding felt unjustified .

Cue the metaphoric parting of clouds and beam of light. I was adding code in the wrong place! The pathing code already supported the arbitrary geometry of the environment, after all. Trees are circular obstacles, just like a character standing still. If I could just pretend people were temporary trees, the pathing code could just avoid them, without all the extra complexity I’d added.

Once I pivoted to this point of view, a clear path forward presented itself. The underlying representations of trees and buildings and fences and all the other fixed parts of the environment were just a really big grid, with each cell marked as passable or impassable. I could introduce temporary obstructions via a simple interface—all I needed was an extra check for whether a particular cell in the grid was blocked :

struct GridPoint
{
    int m_x;
    int m_y;
};

struct PathExtension
{
    virtual bool isCellClear(const GridPoint & gridPoint) const = 0;
};

This extension interface could then be passed into the basic calls to the pathing code, like checking a line segment for obstructions or finding the best path forward in a given direction. Here’s what the original calls looked like :

class PathManager
{
public:

    float clipEdge(
        const Point & start,
        const Point & end) const;
    vector<Point> findPath(
        const Point & startPoint,
        float heading,
        float idealDistance) const;
};

And here’s the new version:

class PathManager
{
public:

    float clipEdge(
        const Point & start,
        const Point & end,
        const PathExtension * pathExtension = nullptr) const;
    vector<Point> findPath(
        const Point & startPoint,
        float heading,
        float idealDistance,
        const PathExtension * pathExtension = nullptr) const;
};

The internal details of clipEdge and findPath were barely affected. Wherever they had previously checked the giant pathing grid, I added an extra check to the PathExtension interface. That’s less than a dozen lines of code, total, across these functions and a handful of other similar functions.

This account leaves out the work to implement the PathExtension interface, but that work was similarly simple :

struct AvoidLozenges : public PathExtension
{
    struct Lozenge
    {
        Point m_points[2];
        float m_radius;
    };

    bool isCellClear(const GridPoint & gridPoint) const override
    {
        Point point = getPointFromGridPoint(gridPoint);

        for (const Lozenge & lozenge : m_lozenges)
        {
            float distance = getDistanceToLineSegment(
                                point, 
                                lozenge.m_points[0], 
                                lozenge.m_points[1]);

            if (distance < lozenge.m_radius)
                return false;
        }

        return true;
    }

    vector<Lozenge> m_lozenges;
};

And that was that. A couple of dozen lines of simple code, instead of the thousand or so lines of nastiness I’d struggled with in my attempt to solve the problem directly.

The new PathExtension interface was much more general, obviously—it handled any sort of temporary obstruction you wanted to add to the grid, with no stipulation about shape or size or way the obstruction was represented. That’s a step forward from the first attempt, which only added hardwired support for circles and then lozenges. But this extra generality is entirely beside the point!

The point isn’t that this solution was more general—it’s that it was simpler and easier to implement than the more specific, less general solution. In fact, as I write this, the Sucker Punch codebase has exactly one implementation of PathExtension —the one I’ve just presented. We haven’t taken advantage of the extra generality, and that’s perfectly OK .

Recognizing the Opportunity

Most of the time, the specific solution is easier to implement than the general solution. Solve the problem you understand. Don’t try to solve a more general problem until you’ve got enough examples to be confident that the more general problem is worth solving. 9

It’s rare to bump into a problem like the examples in this Rule, where the general problem is simpler and easier to solve than the specific one. These two examples are separated by 18 years (!), and nearly all of the umpteen problems we solved in between were solved simply and directly.

While such general solutions are rare, they’re important. These two examples, along with a handful of others, were important breakthroughs for Sucker Punch. Sometimes the breakthrough represented a new paradigm, as in the first example, which prompted us to solve many gameplay problems via a local optimizer; other times it was just a one-off solution to a hard problem, as in the second example. They all created better, more successful products.

That leaves open an important question—what are the clues that a more general solution will create simpler code? How can you spot these opportunities in your code?

I did find one common factor as I looked over the quarter-century-long engineering history of Sucker Punch. In all the examples of the general solution being the simpler path, a major change in perspective was necessary . The general solution represented a completely different way of thinking about the problem, and this new perspective allowed a radically simpler solution.

In this Rule’s examples, the change in perspective was technical—switching from an analytic approach to an optimization approach in the first example and adding the new feature in a completely different part of the code in the second example.

Sometimes, though, the change in perspective isn’t technical at all. You might realize that your code targets the wrong user for a feature, for instance. We’ve often unlocked much simpler approaches by moving a feature historically used by the programming team to the production team instead, or vice versa .

But there’s always a moment when you realize you’ve been thinking about the problem all wrong. And when that realization hits, there’s a chance that the clouds will part and a beam of sunshine will hit and you’ll get to experience the infinite joy of solving a single tough problem with a simple, general solution.

1 You’ll forgive the metaphor. I’ve lived in Seattle for 35 years; I’ve earned a cloud metaphor.

2 This algorithm is covered by US Patent 7,147,560. Sorry, software patents were in vogue at that point. Fear not; the patent expires on December 12, 2023, at which point you’re entirely free to create your own raccoon-agility-centered platformer using the exact algorithm presented here.

3 Personally suffered through by your author, who wrote the code in question.

4 The algorithm isn’t complicated—you could sort it out from the code that follows without giving yourself a headache—but if you’ve got better ways to spend the next 10 minutes, take a look at the Wikipedia explanation. As it turned out, the golden section optimizer helped solve multiple problems, and we call it from a couple of dozen places in the Sucker Punch codebase.

5 The edge cases aren’t that bad—and were easy enough to handle by adding penalties onto the cost function. If the evaluate function tries to evaluate a point off the end of the curve, a penalty is added. Careful construction of the penalty helps point the optimizer back toward the valid range of the curve. Similarly, if Sly doesn’t jump high enough to reach a point, this adds a separate penalty.

6 If you try using an optimizer like this to solve problems, remember that it will find a minimum, but maybe not the minimum you want. Your cost function needs to be constructed carefully, as does your initial guess.

7 The A* algorithm isn’t that complicated, but nevertheless it’s too much to explain here. By discovered graph , I mean that the theoretical search space consists of links between any pair of points in the world. We discover which pairs of points are accessible from each other as we go, by clipping the line between them against all the obstacles in the world.

8 Just as a circle is the set of points at some fixed distance from a point, a lozenge is the set of points at a fixed distance from a line segment. Paper clips and running tracks are lozenge-shaped—two half-circles connected by parallel lines.

9 Where “enough” is “at least three.”