r/godot • • 12d ago

free tutorial The Programming Pattern that built Slay the Spire 2

https://youtu.be/Vjn3LLcnATU?si=2VgGTrJDjcsNOkgO

There's already a lot of deep-dives into Slay the Spire 2's codebase (which you should totally check out if you own the game), but I wanted to talk about the core pattern it uses to make all of it's cards, relics, potion, powers, etc work.

It's all hooks.

(and maybe the Template pattern if we really need a OOP name)

There's a lot of cool stuff talked about in the video, but I wanted to discuss more in depth how the overall pattern works here, along with some pros and cons. The main use case is a game where you want a variety of different "items" that can cleanly trigger different affects on the game state, making it easy to add new items and new effects. Here's how it works:

  1. A base class defines all of the event hooks.

These are game events that are broken up into specific, empty hook functions. For example, `beforeCombatStart()` or `afterItemAddedToInventory()`. The important thing is that one base class holds all of these hooks, and they all have a default implementation that does nothing. This means child classes that inherit from here can stay empty, and only define the functions they want to override

A game manager will then loop over every item that's active, and call it's hook function. For most items, this will be empty from the default implementation.

Additionally, there can be multiple hook functions for a single event to ensure the correct "order of operations". The best example is calculating damage, because if everything was calculated under a single hook, effects for additive and multiplicative changes would mix and make an inteterministic result. STS2 gets around this by breaking the hook into:

- `modifyDamageAdditive()`

- `modifyDamageMultiplicative()`

- `modifyDamageCap()` - ex, if enemy can only take a max of 9 damage per hit

These all get calculated in that order.

2. Core functionality comes from static "command" objects

This one is a little interesting, because you constantly hear about "not using globally accessible classes/vars", but here it simplifies the design substantially. Instead of saying "this is bad practice", here's the pros and cons that I could think of:

Pros

- Easy access to call commands inside other classes

- Simple

- Logical grouping of functions in classes (almost like a util library)

Cons

- If a functions contract changes (ex need a new parameter, return type, etc), it would require changing every invocation of that function

- Harder to isolate unit tests (you can't mock a "PlayerCmd" object as it's directly called by the class, so if you had a test suite and something was wrong with PlayerCmd, it could appear as failures in unrelated classes)

The big one that I think most people have run into is changing the contract, but it seems like they have a pretty stable design so they can afford to take that risk. In other words, if you really know that something isn't going to change, you can afford to keep it simple.

Thanks for reading! (and/or watching)

441 Upvotes

24 comments sorted by

18

u/NatiM6 Godot Junior 11d ago

I was making modular machinery for my factory game. I kinda needed modules to do basically anything, so each would need its own script, but I also wanted to make it compatible with everything - and yep, hooks. It took me a while to actually come up with this, wish I had seen this post earlier.

As for the contract change, if you make the variable a context dictionary, you can pass it everywhere, and then simply putting and taking from the dictionary only the things you need. This saves you from the contract change, since you have no contract to keep.

4

u/LEPNova 11d ago

Could you explain a little bit about how you implement that in your project?

4

u/NatiM6 Godot Junior 11d ago

Alright... The workings of a machine are split into two parts, a Machine and a Module. The base Module defines all the hooks that any module can override when extending it - pre/post-hit, pre/-/post-processing, etc. While the Machine is the controller that calls each hook in order. Hooks can also return a result of their action, which is a simple enum defaulting to ignored.

Machine has exactly one module designated as a core, and a list of attached modules sorted by priority. This is used to determine the order in which the hooks are called - some hooks are exclusively called on the core module, some are called explicitly last on it to preserve decision authority.

Machine is solely a controller - what an instance of it actually does is defined solely by which module selected as a core.

And as I said in my comment, context is passed as a simple dictionary to every hook. Other hooks can fill the context with some info, while others read whatever they need from it. For example, a preprocessing hook might input the pending progress into the context, and processing hook accept it from it. Processing hook might also expect to get delta time from the context if needed, which is passed by the machine.

This is type unsafe, but you can always add safety to individual hooks when you need it.

2

u/LEPNova 11d ago

Interesting, a little over my head but I appreciate you sharing! 

33

u/maxmurder 12d ago

You can leverage GDScript's duck typing to do this without tying everything to a single parent class.

A game manager can loop over every object and check if it has a hook method before calling dynamically.

This can get a bit messy as there is no way to inforce the method signature, and performance heavy depending on how many objects you need to iterate; groups can be used to help manage that at least.

I tend to lean on signal subscriptions more heavily, and ive found pretty good utility in dynamicly bound callback lambdas for passing context etc, so controller classes can implement more simple signaling.

25

u/speps 11d ago

That’s not duck typing, it’s reflection 🦆🪞

2

u/cheezballs 11d ago

In most languages that's expensive and generally not recommended, how is reflection in GDScript?

1

u/RttnKttn 11d ago

I'm oversimplifying things a lot here, but in short it's costly, just not that noticeable imo.

It's noticeably more expensive in languages where regular function calls are heavily optimized. GDScript, however, already relies on dynamic method dispatch in many cases, while optimizing direct calls whenever possible. So calling a method by name still has some overhead, but the difference isn't necessarily as significant as in a language like C++.

Just don't rely on this technique in hot paths, and you'll be fine.

3

u/Skarredd Godot Regular 11d ago

what i use is a global signalbus class that has every event imaginable in the game, anything can fire an event via that and all the listeners will get called. No need to check if it has a function or not since objects register themselves.

1

u/DannyDeKnito 10d ago

STS2 actually went with C# rather than GDScript. While gdscript is the default scripting language, I guess having a team that was working in unitty for a hot minute made C# a sensible choice.

5

u/mister_serikos 11d ago

The part with the specific relics being checked in the vulnerable power code is kinda yucky.  Does that mean modding has to modify that code section instead of just adding a new relic or whatever?  I went with a command pattern for my card game, and then kinda just use it like an event system that can be modified before the event happens.  I also ended up doing a similar thing with the static classes for functions.

2

u/DannyDeKnito 10d ago

those are specifically relics (and powers, cruelty is also in there) that interact with vulnerable in non-standard ways. If you also wanted to add a power/relic that had a vulnerable interaction, then yeah, you'd have to add it to vulnerable's calculation code. For example, if i wanted to make a relic that applies 1 vulnerable to a random enemy every turn i wouldn't have to modify vulnerable code, but if i wanted to make a relic that makes vulnerable twice as effective against enemies with block, i *would* have to modify it.*

*there's workarounds for modifying actual game code rather than add new content, but that's lowkey outside the scope of your question.

5

u/moonfidelity Godot Junior 11d ago

Great video!

What’s the graph at 0:35? I would like to use the same tool to build a dependency map of my project 😵‍💫

2

u/b34s7 11d ago

That’s exactly how Dash Dash Dead uses statuses

2

u/shortguy014 11d ago

I have been obsessed with this implementation after looking into how to mod the game. In particular I really love the model db concept that builds a super simple registry concept either ahead of time or using reflection. I think any game with any decent level of content will eventually need some kind of content DB so doing it up front in a scalable way really pays off in the long run

2

u/Xeno_Morphine 10d ago

a high-score self-provoked bullet-hell type game uses this same thing to bestow stackable bullet patterns to otherwise "default" bullets

2

u/insats 11d ago

Interesting! That’s actually exactly the same pattern I’ve been using in our games (Eldrum), and I’ve ported the same pattern to our new game built in Godot.

1

u/TurkusGyrational 11d ago

I am making my first big game (targeting a size similar to StS, give or take) and so starting to mod this game and then finally building my own thing based on the architecture was a huge boon for me. I'm so thankful to megacrit for making the codebase open source.

1

u/DesignCarpincho 10d ago

I built a version of a card game core that leverages a different design pattern and avoids a hook (although the pattern is amazing! this is just an alternative).

Using the command pattern, you can make a command class for each major action the game takes like damage, block or drawing cards. You then make a CommandManager that uses a PubSub to notify that a command WILL execute, has just executed, or has completed executing.

What you do next is you listen to the PubSub and react to commands you care about. The CommandManager has a built-in add_reaction(cmd) method that lets you add another command as a reaction to the one just posted, and you can set the priority in that command. The manager sorts them each time one is added, and then you can have your " add 20 block, but BEFORE you halve all block from this other card".

I think hooks are much better for most use cases, but if you have a very response-heavy game, this might give you other flexibility.

1

u/RttnKttn 11d ago

It's not a bad pattern, but IMO it makes interfaces a bit too bloated.

I did something similar in spirit (not exactly the same approach) about 5 years ago. I built an ECS-like system where units could have components like HP, skill charges, damage patterns, damage types, etc.

For example, when it was time to deal damage, the round director checked which units could attack, packed their attacks into "damage events" and sent them to affected cells on the board.

Units with a DamageReceiver component processed those events and sent themselves an "HP loss" event, which could then be handled by the HP component. Some units had their own weird damage rules, like rocks that didn't take damage the usual way. If HP reached zero, it sent another event, something like "I'm dead", which could trigger other components. One could destroy the unit (yep, another tiny component), another could spawn something like shields, bombs, bonus containers or whatever. And all those things were just regular units too.

Event processing was a weird hybrid. Some events were processed immediately, others at fixed stages. For example, damage was calculated right away, but deaths were handled at the next stage. Sounds like a mess, but it gave me a stable and predictable pipeline.

So unit behavior was basically defined in Lua with stuff like:

"add_health(5)" "add_destroyable()" "add_spawn_on_destroy(unit_name)" "add_damageable(direct | adjacent | bonus)"

No need to write complex lifecycle logic for every unit, just a bunch of small building blocks you could combine however you wanted.

And yeah, I used direct calls too when I was sure a component existed, like "obj->getComponent<Damageable>()", without going through events.

And the cherry on top — game logic wasn't tied to what the player saw on screen. Each move produced an event log, which was then consumed by a separate system I called the Animation Director to drive the animations. So I could run the game headless for tests or speed up everything without breaking the logic.

Of course, if you messed up event processing, you could get some funny visual desync bugs. Units could end up in wrong places or have wrong visual states. Luckily, most of those bugs fixed themselves on the next unit update, and they weren't that hard to track since we had text logs of what happened in the game logic and how it was played back.

And the funniest part? All this overengineering was for a hypercasual mobile clone of a popular game. :D

-11

u/DriftWare_ Godot Regular 12d ago

This would be even easier by making a signalbus singleton and connecting all the hooks to global signals

15

u/Shifty-Cow 12d ago

My question would be, why even add the signal bus at all? :)

The game manager that loops over all the items to call each hook function has access to the run state, and that holds all the relics, cards, etc that are active. Because of that, it can just directly call the hooks on each item. 

This makes it a little simpler, as each item doesn't have to hookup an event to it's callback, it's managed centrally instead

0

u/DriftWare_ Godot Regular 11d ago

A game manager totally works, but a signal bus seems like it could be more extensible. I'd have to experiment and try both ways

3

u/Salazar20 11d ago

Also signals seems to call the functions immediately, which means that code after the signal emit gets stopped until seemingly all other callbacks ends

This is annoying when you introduce signals that triggers other signals. So if you dont make signals the easiest more straight forward things, you're finished

Seriously, if you want something more complex than updating the health of the player then use other method