Rpg Stats - Temporary Changes, Harder Than I Realised!?

This topic is 533 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I'm writing a turn-based RPG, and have a small coding dilemma about stats. Specifically, it's about when you need to make temporary changes. Say the player has a speed which is currently 50, and the spell "slow" takes 10 off the speed. So it's reduced to 40, and in a few turns it has 10 added back so it's back at 50. Fine, cool with that.

Now, suppose the speed is 5. I take the 10 off, but aha, can't be < 0, so I set it to 0. A few turns later I restore it, but now it goes back to 10, which is clearly wrong and an exploitable side-effect, so I don't want that to happen.

I have 2 choices as I see it.

1. Allow the speed to be negative, but whenever I use it, I clamp it to the range [0,100] (say). Note that the same goes for if the speed is 95, I allow it to go to 105 if the "fast" spell is used. I need to be very careful when coding this, because if I fail to clamp, things will go quite wrong and it will be a bit unpleasant to track down.

2. Create an undo record that says "only increase by 5 when you put it back". This requires an architecture for storing the changes, but also needs quite a lot of care to ensure consistency and I am not 100% convinced it can be made to be consistent because other things can be messing with the stats inbetween the change and the undo. I rejected the "store the actual speed it goes back to" option for this very reason.

So: am I missing other possibilities, or if not, which of the two appeals and why?

Share on other sites

I'd just add a "is under slow spell influence" property to the player that can be set/reset independently

Share on other sites
I love Hodgman's stack idea. In my games it's been a bit simpler - just store a list of modifiers/effects/buffs/whatever on the player, and when querying a stat, the query is always implemented as "base stat + (total of relevant modifiers)". In that situation you have to be careful about ordering because +10 followed by *2 is not the same as *2 followed by +10.

Share on other sites

Yep, this can lead to troubling bugs (or exploits) when attributes can change as well -- e.g. if you happen to level-up while a buf is enabled.

So:
3. Represent the stats as a stack of operations.
e.g. a stack for your speed stat might contain:
*Slow: Subtract 10
*Base: Set 50

When you evaluate that from the bottom up, you get (50-10) = 40.

When you cast the slow spell, the new instance of that spell adds an operator to speed's stack and retains a handle to it. When the spell ends, it uses that handle to remove the operator that it added earlier.

If the player levels up, you can modify the 'base' item in the stack above, and it will automatically allow you to recompute the new resulting speed value, including buffs.

You can keep a cache of the speed attribute as well as this stack, and update the cache whenever the stack is modified... But never change that cached value -- always change the stack of operators, and let the stack update the cache with the new value.

Yeah I like that. Nice to know that it was genuinely more complex than I had initially thought. Thanks!

Share on other sites

I all solutions above are great solutions for an RPG. Which one is better may depend on the requirements of your game.

However, one thing they all have in common is that the base speed is stored with the character and not the modified speed.

The modified speed is calculated when the speed is requested

A simple example of a GetSpeed function could look like the following:

class character {
private int _baseSpeed;
private bool _isSlowed;

public int GetSpeed() {
int speed = _baseSpeed;

if(_isSlowed) {
speed -= 10;
}

//return 0 if calculated speed < 0, otherwise return calculated speed
return speed < 0 ? 0 : speed;
}
}


Hope this adds some clarification, if it was not already clear.

Good luck on your RPG!

Edited by Senorit

Share on other sites

A quick and simple fix I use myself is just to let buffs and de-buffs effect the percentage of a stat, so: round(Speed/de-buff).

This is nice as it will also prevent the speed from reaching 0 in most cases.

Share on other sites

3. Represent the stats as a stack of operations.
e.g. a stack for your speed stat might contain:
*Slow: Subtract 10
*Base: Set 50

When you evaluate that from the bottom up, you get (50-10) = 40.

A similar approach, and the one we took, was to have two classes for characters (or enemies, but lets focus on characters). One is called GlobalCharacter, and this is the permanent class object that maintains all of the character's stats. When we enter a battle, we create a BattleCharacter class which contains a copy of all the GlobalCharacter stats. We don't touch the global character stats in battle, so we always have the original values. When the battle ends, we set the stats on the GlobalCharacter to those of the BattleCharacter to reflect changes like HP or mana.

This also has the convenience of allowing us to restore the conditions when a battle began, which is something we take advantage of as we allow the player to restart a battle a number of times if they are defeated.

Share on other sites

A good design pattern for this is the Decorator pattern. Applied to this problem, you can think of it as an object-based formalization of Hodgeman's stack suggestion, or some of the other suggestions here.

How I use it is this --

First, in my case, characters' stats are fixed per-level, and stored in a read-only array-of-structs -- there's one struct for each character and for each level. The character data structure points to this for its base stats. Weapon, armor, and item stats are similar, but separate -- You can think of all of this as being a big dictionary, or set of spreadsheets or database tables -- in fact, that's usually how I author this data, which gets fed into the build (or could be read from a file a load-time).

*side note* If you have non-static leveling (e.g. where the user allocates their own points when they level up) you would manage this base data differently, but the basic pattern and application stays the same. You have a couple obvious choices: One is that you do away with the dictionary and just have a base-stat data structure for each character/item that you modify directly; The second way is that you still have the dictionary of read-only base stats, and you implement the user-allocated points themselves using this pattern (just apply them before any other buffs/debuffs/effects).

Now you apply the decorator pattern to that base stat structure -- basically, you have a decorator that presents the same interface as the structure itself, and when a decorator is applied, the character points to the decorator, and the decorator points to the base stat. This means the character reads from the decorator, which is where it gets its opportunity to modify the base values. What about multiple effects/buffs/debuffs? Simple! Since the decorator has the same interface as the base state, a decorator can point to either the base state or another decorator as long as they derive from the same interface and you use a pointer to the base class -- you can stack them arbitrarily deep, and each decorator will modify the sum of the base stat and all the decorators that came before it.

This might sound like an awful lot of engineering for something so simple, but its very robust and the pattern isn't terribly complicated. One of the things that makes it nice is that it really decouples the implementation of effects from one another and from the base stats structure. They don't need to know anything about what the other states look like, how many there are, or what they can do. It communicates only the language of the character stats (though, in my implementation, I have a side-channel that allows an effect to know if a certain effect has already been applied -- for items, think of a set of armor that's stronger when all its pieces are equipped.)

Also worth noting, is that the reason I like to pass in the entire character stat-set, rather than having individual decorators for each stat is that it makes it much easier to have multi-dimensional effects that modify several stats, or which take into account multiple stats in determining its value (e.g. a character's defense against spells might be modified based on both their magic resistance and their intelligence) -- its also a whole lot less to manage and a whole lot less code to write.

To talk about implementation of the interface for a bit, it'll depend on whether you're programming in a language with properties (like C#) or without (like C++) -- if you have properties, then you can use them to implement getters for each base stat (and setters, if you don't go the dictionary of read-only structs route). Otherwise, you need to implement member functions to get the values out.

Another good shortcut to know about is that in C++ a virtual function can have a default implementation -- so what I do is when I define the base class for the decorators is give the virtual getter a default implementation that just reads the value form whatever it points to and passes it along unmodified. That way, when an implementation of a particular decorator only modified one stat, I only have to implement that one stat's getter without any other boilerplate. Not only does it saves me typing, it removes the opportunity to make mistakes.

Share on other sites

Use memoization/DRY, so do not store the final value of the stat. Instead recompute it each time it is asked.

So each effect to a stat is:

enum class StatAffectionType{
BaseStat, Buff, DeBuff
};

struct StrEffect{
unsigned int amount;
unsigned int millisecondsLeft;
unsigned int priority; //order in wich changes are applied
StatAffectionType type;
};

class Character{

std::vector<StrEffect> strArray;

public:

int GetStr(){
SortStrArrayByPriority();
int str = 0;
bool someEffectFinished = false;
for( auto effect: strArray){
switch(effect.type)
{
case StatAffectionType::BaseStat:
str+= effect.amount;
break;

case StatAffectionType::Buff:
if(effect.millisecondsLeft>0)
str+= effect.amount;
else
someEffectFinished = true;
break;

case StatAffectionType::DeBuff:
if(effect.millisecondsLeft>0)
str-= effect.amount;
else
someEffectFinished = true;
break;

}
}

if(someEffectFinished)
PurgeFinishedStrEffects();

return str<0? 0: str;
}
};


You can cache the result once per frame but it should be cheap by just ask it each time. In this way you avoid all kinds of bugs, note that even Morrowind and Oblivion had tons of bugs related to temporary stats, so I would go the "slow" but safe way, and later optimize only if needed.

If you use  a sorted list you do not need to sort, (each buff will be inserted at right position), I think this is one of the few cases where sorted lists are usefull.

While I agree this can be considered a monolitic class and some purist would refactor so that each effect has its own virtual class, consider also that as long as kinds of effects are limited in number you have just one place to check regarding your Str stat, so I would consider that a dirty code, but dirty on purpose.

Edited by DemonDar

Share on other sites

You can cache the result once per frame but it should be cheap by just ask it each time. In this way you avoid all kinds of bugs, note that even Morrowind and Oblivion had tons of bugs related to temporary stats, so I would go the "slow" but safe way, and later optimize only if needed.

If you have a single point where buff is added and removed, why not keep a dirty flag and recompute only when it's set to true? If buff can't be changed outside of those two methods, there is no reason why the value would change from one call to another.

I would remove any logic governing lifetime of an effect from this function though, just iterate over array of effects, set current value, clear dirty flag. If any effect is added or removed, set dirty flag, which forces stat to be recalculated. I just am not sure that function returning strength should care whether the effect should be removed or not, it just goes over effects in the array and applies them. Other part of code guards the lifetime and removes the modifier from the array at appropriate time.

Share on other sites

@noizex.. Very good point separating lifetime handling. :)

If an effect added or removed => just recompute the str value, no dirty flag required.

Ideas for handling lifetime? (already saw different blog posts of people having bugs with this kind of things.

Edited by DemonDar

Share on other sites
Lifetime management is as easy or as hard as you make it. The trivial approach is normally sufficient, i.e.:

for each character:
for each buff/modifier/whatever:
check its expiry time
if that time is >= now:
delete it
if you had some cached value for this stat, clear it
if you had a dirty flag for this stat, set it

Edited by Kylotan

Share on other sites

In my implementation I have two layers - stat modifiers and effects. Stat modifier may be caused by effect, but effects can do much much more (anything really, from various disease effects, to just lowering certain stats). So the idea is that effect has start_effect() and remove_effect() methods which in case of pure stat modifiers are the ones responsible for adding and removing them. So it looks a bit like this (some Angelscript pseudocode):

class NastyDisease: Effect

StatModifier @str_mod, @vit_mod;

void start_effect(object target)

{

@str_mod = target->add_stat_modifier(Stat::Strength, -20);

@vit_mod = target->add_stat_modifier(Stat::Vitality, -30);

}

// Called when effect expires

void remove_effect(object target)

{

target->remove_stat_modifier(str_mod);

target->remove_stat_modifier(vit_mod);

}

}

This makes StatModifier class just a dumb storage for how much and what stat is modified, and the expiration is handled by Effect class (on a usual timer basis, I don't check upon requsting stat that I should remove some modifier, if the effect expires appropriate function is called and it removes these modifiers.

There is slight problem with this, because if something goes wrong in remove_effect() function (runtime error), it may keep the effects on the player, but I guess if that happens something is really wrong.

Share on other sites
Looks nice, but if the main point of Effects is to apply (and de-apply) StatModifiers, why not just have Effects contain a list of Stat/value pairs, so you don't have to implement start_effect and remove_effect each time you define a new Effect?

Share on other sites

Looks nice, but if the main point of Effects is to apply (and de-apply) StatModifiers, why not just have Effects contain a list of Stat/value pairs, so you don't have to implement start_effect and remove_effect each time you define a new Effect?

Main point of effects is to give total flexibility on implementing various effects that can affect character - permanent curses, diseases, poisons, buffs and debuffs, spells - so these functions are just hooks that writer of effect uses for a starting/ending point of an effect. This goes way beyond stat modifiers, so I wanted to keep stats and effects separated, because some effects won't even touch stats but change appearance of character, modify it's behavior and so on. The effect could for example do this:

void start_effect()

{

print("You slowly turn into a frog!");

old_model = target->get_player_model();

target->set_player_model(frog);

}

void remove_effect()

{

print("You turn back into " + old_model->get_race() + "!");

target->set_player_model(old_model);

}

Though I guess it's a good idea for a base effect that only affects stats :) So instead of creating separate Effect classes I could write StatChangeEffect() and just pass array of stats to affect, without the need to care about adding/removing modifiers for each one. But the general idea is for the effect class to be as flexible as possible in terms of how it affects target.

Edited by noizex

Share on other sites

It's not too terribly bad to do actually. Currently, my architecture has a more programmatic approach. Which unfortunately makes it difficult to create effects in an editor, unless I build some sort of composite structure.

So to start it off, I have each Actor that requires some RPG stats, or conditions to have some data that can be implemented. This is something very basic, and does not actually represent what I use. I actually use a custom map. So it's just SetAV<"Health Total", struct> and AddAffliction<"Poison", struct>;

Class ActorValues : IStats{
public: // Functions that are related to the primary stats
...
private:
int[] Strength;
int[] Intelligence;
int[] Dexterity;
int[] Charisma;
int[] Wisdom;
public: //Functions related to the secondary stats.
...

private:
int[] m_Hitpoints_current;
int[] m_Hitpoints_total
int[] m_attack
int[] m_perception
int[] m_evasion
int[] m_defense
...
}


Each of these items are double buffered. Yes including current health for temporary hit points. Field 0 is the base. Field 1 is the final, all non permanent changes are represented here.

Next up comes the status effects.

Struct IEffectBase { // Makes it easier to allow editors to create more status conditions.
string TargetStat;
function* Math_Function;
int Value;
}

Class StatusEffectBase {
public:
void tick(); //Processes all items in Effects
...
private:
string Name
string Description
handle<FLAG_IMAGE> Icon
bool isHidden
float Duration
list<IEffectBase> Effects


In actual implementation. I use Lua to describe how all my statuses work. I loose the ability to let people who don't know how to code to add status effects. But I have a lot more control over it. It also makes it easier for me to store in my game's runtime database.

Edited by Tangletail

Share on other sites

I have most of this operational now:

class StatModifier
{
public:
virtual ~StatModifier() = default;
virtual int Apply(int statValue) = 0;

protected:
StatModifier() = default;
};

class AddStatModifier : public StatModifier
{
public:
: StatModifier()
, _delta( delta )
{
}

int Apply(int value) override
{
return(value + _delta);
}

private:
int _delta;
};

class PercentageStatModifier : public StatModifier
{
public:
PercentageStatModifier(int percent)
: StatModifier()
{

}

int Apply(int value) override
{
int delta = (_percent*value) / 100;
return value + delta;
}

private:
int _percent;
};

//-----------------------------------------------------------------------------

class Stat
{
public:
// Construct a stat to default value 0.
Stat();

// Construct a stat to a specific base value.
Stat(int baseValue, int minValue=1, int maxValue=100);

// Dtor.
~Stat();

// Gets the current stat value.
int GetValue() const;

// Get / set the current base value.
int GetBaseValue() const;
void SetBaseValue(int baseValue);

// Add / remove modifiers.
void AddModifier(StatModifier * mod);
void RemoveModifier(StatModifier * mod);
void ClearModifiers();

// Set the value range.
void SetMin(int min);
void SetMax(int max);

private:
int _baseValue;
int _min;
int _max;
mutable int _valueCache;
mutable bool _dirty;
TArray<StatModifier *> _modifiers;
};

Stat::Stat()
: Stat(1,1,100)
{

}

Stat::Stat( int value, int min, int max )
: _baseValue(value)
, _min(min)
, _max(max)
, _valueCache(0)
, _dirty(true)
, _modifiers()
{

}

Stat::~Stat()
{
ClearModifiers();
}

int Stat::GetValue() const
{
if (_dirty)
{
int value = _baseValue;
for (auto mod : _modifiers)
{
value = mod->Apply(value);
}

_valueCache = FMath::Clamp(value, _min, _max);
_dirty = false;
}

return _valueCache;
}

void Stat::SetBaseValue(int value)
{
_baseValue = value;
_dirty = true;
}

void Stat::AddModifier(StatModifier * mod)
{
_dirty = true;
}

void Stat::RemoveModifier(StatModifier * mod)
{
_modifiers.Remove(mod);
delete mod;
_dirty = true;
}

void Stat::ClearModifiers()
{
for (auto mod : _modifiers)
{
delete mod;
}
_modifiers.Empty();
_dirty = true;
}

void Stat::SetMin(int min)
{
_min = min;
}

void Stat::SetMax(int max)
{
_max = max;
}


I have a further question. Suppose I want to change HP, but in doing so I exceed the max HP. Do I change the base value to MAX, or do I adjust it by newHP-MAX so that the current total comes out as MAX? Either way seems wrong (somehow!)

eta: D'oh! I have a SetMax() method - this is what happens when you take a break from coding!

Edited by lordGoldemort

Share on other sites

_percent is not initialized in the the PercentageStatModifier

Share on other sites

Our game (Idle Raiders and its upcoming successor) deals a metric ton with stats, and it works like this:

We have "modifiers". They are triplets ( attribute, operator, value), i.e. the attribute to be changed (e.g. damage), the operator used (how the values are added the attribute, e.g. simple ADD which does base_value + value, ADDITIVE_MUL which does base = base_value * value, other stuff, etc.).

There core modifier system does no 'runtime tracking' (recomputing every frame or something) of stats because it's not necessary. Not really sure why you would need it... we only compute the values when they are changed by gameplay (e.g. player equips new item, player applies buff, buff runs out, etc.) and keep it like that until it gets changed again. We also don't use any dirty values and just recompute an attribute immediately when a modifier is applied/unapplied, because even though we have sometimes dozens of entities fighting, modifier changes are so rare relative to the frame update frequency that changing the same modifier on the same entity twice in a frame almost never happens, and even then the computations involved are nearly trivial in computational terms.

The modifier system also doesn't actually store 'active' modifiers that are used, and only stores the combined values per operator type. So when you want to compute the final result of an attribute from all its applied modifiers, it looks up combined values from the ADD, MUL, etc. modifiers and applies those to the base stat. Combine means... when you do some MULs like this

base_value += base_value * value1 + base_value * value2 + ...

it's of course the same as doing (this is the same for all other operators)

base_value += base_value * (value1 + value 2 + ...);

so you can take the

(value1 + value 2 + ...)

and store it somewhere. It only gets changed when modifiers are applied/unapplied, and when the value of an attribute is computed, you only need to do that one step using the cached 'combined' value per each operator type.

The tracking of the actual modifier objects that need to be applied/unapplied is left to the gameplay systems that actually use them, because their lifetimes are usually dealt with in different ways. For example, the equipment system just stores all modifiers associated with an item in the item itself, and when you equip/unequip it, applies/unapplies it. These modifiers are alive all game and applied/unapplied at the behest of the player's actions. The buff system on the contrary actually does some checks once a second to see which modifiers now have to run out, etc. and actually discards some of them.

We need ordering of those modifiers, so we use a layer system. Any layer can contain any number of modifiers with all their different operations. We apply the lowest first, from that it calculates basically a new "base value" (a copy of course, the original base value never gets changed) for the layer above. That layer also applies its modifiers, and moves it up the ladder all layers.

For example, an entity starts with 100 HP and has an item that gives +20 HP and another that gives +50% HP, then that results in 170 HP since equpiment modifiers are all in the same layer and operate on the base value. But when the player now triggers a temporary buff that increases the HP of an entity by 20%, that is in a layer above (since thats just how we want it), and the entity will have a total for 204 HP. And so on.

The math operators described above are applied independently from each other within the same layer. So layer 0 MUL does not take the computation result of layer 0 ADD into account. Instead, layer 1 will take the result of the final result of layer 0 into account, etc.

All gameplay systems target a pre-defined hardcoded layer, since it's important in terms of gameplay how the different sources of modifiers are supposed to "stack". There are many different ones... we have equpiment like armor and weapons that changes stats, all characters can have skills that modify some stats, then we have temporary buffs from usable items that modify stats, permanent unlockables that modify stats, a basebuilding system that modifies stats, etc...

As a final bonus step, before storing the computation result in the actual attribute variable (myEntity.damage for example) you can put that through a custom curve if you so desire.

And actually we don't use this layering system or custom curves yet so that was a lie  :D That's just how I would do it if I had the time to code it again. For now we basically make do with the same system but with only 1 layer where everything is thrown into, and we've been doing fine so far, except that our usable scrolls that increase raider damage by 10% for 30 seconds only do it based on the base value, but that's the only thing we currently don't like about it and we had more important stuff to work on so...

Edited by agleed

Share on other sites

Have had similar to those above.

There is a base unit stat.  It can be modified by attached buffs or by attached equipment.  When you query a stat you provide a simple struct and the system uses the visitor pattern to fill it out.

You'd do something like: actor->GetDefenseStats( target, &defenseStats)

The function fills out the base defense stats.  Then it iterates through all the attached armor that modifies the stats.  Any item can have any number of stats modifiers attached to it.

Armor called "Studded Leather Armor" with

{

target type: any

physical defense: 180

cold defense: 75

fire defense: 120

poison defense: 15

spirit defense: 20

}

Boots called "High Boots":

{

target type: any

physical defense: 40

cold defense: 20

fire defense: 20

poison defense: 20

spirit defense: 15

}

{

target type: stone

physical defense: 140

cold defense: 0

fire defense: 0

poison defense: 0

spirit defense: 0

}

Ring called "Dragon's Flame"

{

target type: any

physical defense: 20

cold defense: -40   <-- that this makes you more vulnerable to cold when worn

fire defense: 40

poison defense: 0

spirit defense: 0

}

{

target type: dragon

physical defense:200

cold defense: 40

fire defense: 200

poison defense: 100

spirit defense: 100

}

Amulet called "Demon's Bane"

{

target type: any

physical defense: 0

cold defense: 0

fire defense: 0

poison defense: 0

spirit defense: 55

}

{

target type: demon

physical defense: 150

cold defense: 150

fire defense: 200

poison defense: 150

spirit defense: 200

}

etc.

Then you just iterate over all the attached items. If that item has sub-items like runes attached, recursively travel the tree. For every attached stats modification, if the character type matches the one we're testing against add those values.

If you've got another set of stats that apply percentages, accumulate the multiplier rather than adjusting the stats, then apply the multiplier only when you finally use the final value.  Applying a multiplier like 120% any time earlier would give a wrong result, so save those for the end.

Share on other sites

If you've got another set of stats that apply percentages, accumulate the multiplier rather than adjusting the stats, then apply the multiplier only when you finally use the final value.  Applying a multiplier like 120% any time earlier would give a wrong result, so save those for the end.

If that's wrong depends on the game's design, though.

Design might dictate that, with the following stats, order matters:

Base: 100 Strength

Buff_A: +20 Strength

Buff_B: +10% Strength

AB could, by design, yield a different result then BA.

Most games would, I think, want to follow a system matching your description, it's just a note worth bearing in mind that what's wrong for some games might be correct/intended for others.

---

Like a lot of things, it boils down to having design be specific enough that you're able to create a system that matches the requirements.

Share on other sites

You can design such that it matters, however I am not convinced that it's good game play. It makes the assumption that players know enough math that they understand "x * a + b" is always less than "(x + b) * a". Not all players may have that insight, and it seems wrong to me to punish them for it.

Edited by Alberth

Share on other sites

I agree with that, it was more a comment on it not being mathematically wrong to do it in either order, as the design could call for it to be intended, and be perfectly valid.

As I said, I would expect most games to follow frob's advice, but I think "wrong" isn't objectively always necessarily correct =)