kitsu.cafe/content/blog/a-query-about-game-state/index.md
2024-12-01 18:10:40 -06:00

8.1 KiB

{% extends "../../../layouts/post.html" %}

{% block article %}

A Query about Game State

Preface

I'm an indie game dev that has an interest in making tools that I think would improve my life as a game developer in the hopes that it can help others. I'm not an expert in any of the topics that this article covers. I have no formal education in game engine development or architecture, systems programming, or anything else. I went to university for Computer Science with a specialization in game design & development when I was in my early 20s and the only thing I learned is that there are better ways to spend tens of thousands of dollars.

Everything in this article is drawn directly from my experiences working in tech and game development.

Theseus' Shield

In the context of game design and development, object oriented data modeling can feel intuitive. Players, NPCs, and Enemies can all derive from a common "Creature" class which handle things like health and damage. Weapons, armor, and consumables can derive from a common Item class which handle inventory management.

Thinking exclusively in terms of hierarchal, nested patterns can come at a cost: software brittleness and inflexible design. Let's use our base Item class as an example.

abstract class Item {
    public string Name { get; protected set; }
}

abstract class Weapon: Item {
    public float Damage { get; protected set; }
    public float Range { get; protected set; }
}

abstract class Armor: Item {
    public float Defense { get; protected set; }
}

class Sword: Weapon {}
class Bow: Weapon {}

class Helmet: Armor {}
class Shield: Armor {}

In the above scenario, we have three layers of inheritance. We can imagine that Item handles behaviors like item management such as being added or removed from an inventory and highly generic item behavior. Weapon would then be responsible for an item which is capable of dealing damage at any range. We can expect that the specifics of its attack behavior would be implemented by a subclass. Similarly for Armor, this would handle generic damage interactions such as common mitigation or avoidance calculations while leaving specific implementation details to its subclasses.

Seasoned game devs, disciplined object-oriented programmers, and existing ECS developers can likely already see what comes next. A new requirement.

How do we add a Spiked Shield item -- one which derives the behaviors of Weapon and Armor? If we were using a language which supports multiple inheritance this could potentially be a nonissue: except that multiple inheritance is often purposefully missing in many languages. We could decide that the item belongs more to one class than the other and just duplicate the missing behavior but these types of decisions often introduce unforeseen complexity: will the damage algorithm need to do a specific type check for SpikedShield? What about the equipment screen? And of course, what happens when we need to implement a damaging potion?

Perhaps the most appropriate solution this case would be to forego the inheritance pattern in favor of composition. In C#, this could be achieved with interfaces and default implementations.

interface ICollectable {
    void Take();
    void Remove();
}

interface IDamaging {
    void ApplyDamage(IDamageable damageable, float value) {
        damageable.ReceiveDamage(this, value);
    }
}

interface IDamageable {
    void ReceiveDamage(IDamaging source, float value);
}

class SpikedShield: ICollectable, IDamaging, IDamageable {}

We can use this approach to refactor our existing items and systems to derive/override only the behaviors they use. The respective systems for these interfaces now only need to check for the existence of these interfaces in order to act on them.

Engines like Unity and Godot use variations of the Entity-Component (EC) pattern (similar to but distinct from Entity-Component-System (ECS)). These patterns favor composition over inheritance by allowing developers to isolate behaviors into discrete components that can be applied to entities. In the Spiked Shield example, a developer could make a "Damage Source" and "Damage Target" component and add both to the item. In essence, this is the same as the interface-based approach.

Unfortunately, these patterns suffer issues that are much more difficult to solve.

In the event of my demise

Due to the nature of video games, important events may need to be handled at any moment. For example, a player may've dealt a fatal blow to a boss enemy on the same frame that they received fatal damage. In which order should this damage be processed? Depending on the handling order, this is likely the difference between clearing a potentially difficult boss battle and needing to do it again.

In my experience, this would likely be handled by a traditional event system where the order is difficult to predict. This isn't to make the claim that syncronous event systems are unpredictable, but ensuring that a given event will be handled in a way that is predictable to the designer/developer without additional abstractions is difficult.

It's often useful to explicitly define the processing order of certain interactions and events. To solve this problem, we could implement a priority event queue.

public class DamageEventArgs : EventArgs {
    public readonly IDamaging Source;
    public readonly IDamageable Target;
    public readonly float Value;
}

public delegate void DamageEventHandler(object sender, DamageEventArgs args);

class DamageEventQueue {
    private PriorityQueue<DamageEventArgs, int> queue = new();

    private void OnHandleDamageEvent(object sender, DamageEventArgs args) {
        var priority = args.Source switch {
            Player => 2,
            Enemy => 1,
            _ => 0
        };

        queue.Enqueue(args, priority);
    }

    private void OnTick(float deltaTime) {
        while(queue.TryDequeue(out var event, out int priority)) {
            event.Source.ApplyDamage(event.Target, event.Value);
        }
    }
}

DamageEvent.Invoke(this, new DamageEventArgs(bossEnemy, player, 10));
DamageEvent.Invoke(this, new DamageEventArgs(player, bossEnemy, 10));

There's a lot of issues with this code that I'm going to pretend were deliberate decisions for brevity. The point of this example is to show that we can ingest events and sort them arbitrarily based on the requirements of our games. We've made a step in the right direction by identifying a need to explicitly order these events. Even if this implementation isn't ideal, it properly encodes the requirements of the design ("player damage should be processed before all other types").

In search of loot

Managing game state is difficult. As a game grows, so too does the amount of amount of objects active at any given time. Dozens, hundreds, or even thousands of entities each with their own behaviors, goals, and concerns that interact with each other in different ways. This explosion in complexity can be exceedingly hard to manage even in games that are small in scope. Games, even at their simplest, tend to be highly complex.

Enter ECS

ECS solves many of the problems presented by object oriented programming patterns but it's still in its infancy.

Issues with ECS

Mental modeling is hard. Complex queries are hard. ECS is hard.

A Solution?

something something game state as a database, expressive querying

Going forward

continued evolution of ecs which can broadly respond to specific use cases and needs

What I'm looking for

  • constructive feedback and discussion about the general direction i'm putting forward
  • potential implementations and data structures that allow ecs to perform as outlined
  • potential pitfalls that ecs may not be able to answer

Not on topic but will still accept

  • improvements and specific optimizations to my prototype

What I'm not looking for

  • criticisms about my specific prototype implementation

{% endblock article %}