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:
- 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)