Wallet
One of the first features I like to design in any language is the Wallet
.
Its main purpose is to store and save currencies.
It should also be able to check if the player can afford something or not.
Requirements
- Store currencies
- Select which currencies can be stored
- Check if the player can afford something
- Emit an event when currency is gained
- Apply currency multipliers if applicable
- Easily extendable with more currencies
- Save & Load
Usage
Implementation
To avoid making typos regarding currencies, we declare an enum CurrencyType
Currency
then simply becomes
The Wallet
has to deal with storing the currencies, and check if they are valid
Multipliers
To avoid a dependency on App.game
, the Wallet
internally keeps track of a list of multipliers per CurrencyType
.
If a Feature
changes a multiplier (by for example buying an upgrade),
it needs to trigger a recalculation by emitting the onCurrencyMultiplierChange
event.
App.game
will then recalculate this multiplier and update the Wallet
.
Saving and Loading
Saving now becomes very straightforward. We only need to add each currency to the WalletSaveData
.
info
You might think that declaring the currencies 3 times just to save them is a bit excessive.
It is possible to simply return currencies
and save that.
This does however leave you with a bit less control when modifying saves as TS can't tell which attributes exist.
It's up to you!
Events
onCurrencyGain
Emitted whenever a currency is gained.