r/godot • u/Shifty-Cow • 12d ago
free tutorial The Programming Pattern that built Slay the Spire 2
https://youtu.be/Vjn3LLcnATU?si=2VgGTrJDjcsNOkgOThere'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:
- 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)
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.
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.
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.
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