Jump to content

  • Log In with Google      Sign In   
  • Create Account

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

  • You cannot reply to this topic
26 replies to this topic

#1   Members   -  Reputation: 181

Like
1Likes
Like

Posted 25 July 2016 - 06:18 AM

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?



#2   Moderators   -  Reputation: 48696

Like
14Likes
Like

Posted 25 July 2016 - 06:30 AM

*
POPULAR

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.



#3   Members   -  Reputation: 5504

Like
0Likes
Like

Posted 25 July 2016 - 07:05 AM

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



#4   Moderators   -  Reputation: 4555

Like
4Likes
Like

Posted 25 July 2016 - 07:33 AM

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.

#5   Members   -  Reputation: 181

Like
2Likes
Like

Posted 25 July 2016 - 09:20 AM

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!



#6   Members   -  Reputation: 188

Like
2Likes
Like

Posted 25 July 2016 - 09:31 AM

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, 25 July 2016 - 10:56 PM.

Hobbyist game developer

 

Play my game on kongregate and let me know what you think: Digitwars


#7   Crossbones+   -  Reputation: 16030

Like
10Likes
Like

Posted 25 July 2016 - 11:30 AM

*
POPULAR

Massively simplify the amount of state you're modifying by using more code and data.

Store a base/"true" stat. Do not change this, unless some effect is supposed to _permanently_ alter the base state.

Keep a running/"current" stat value modified by effects. This should ideally be a cache, e.g. you should be able to recalculate this from all current effects. You can either invalidate the cache whenever an input changes (e.g., an effect is added/removed, the base stat changes, etc.) or design the system to require few invalidations (if effects are expensive to calculate). If doing the latter, keep this stat simple - do _not_ clamp the value here (let it go negative!).

Provide a public access for the stat that hides the differences between base, current, and clamped values. This accessor is what all your public interfaces should use, with a few exceptions (UI probably has places that it wants to show the base stat or compare and contrast the current with the base, so make a public readonly accessor for that too for UI).

Now you don't have a source of bugs. Base is base and doesn't get changed much (no source of bugs), current is recalculated when needed or has composable math (no source of bugs), and the accessor does any last-minute logic to ensure the value matches game rules (no source of bugs).

Edited by SeanMiddleditch, 25 July 2016 - 12:51 PM.

Game Developer, C++ Geek, Dragon Slayer - http://seanmiddleditch.com

C++ SG14 "Games & Low Latency" - Co-chair - public forums

Wargaming Seattle - Lead Server Engineer - We're hiring!


#8   Members   -  Reputation: 2271

Like
0Likes
Like

Posted 25 July 2016 - 12:44 PM

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.



#9   Members   -  Reputation: 1589

Like
1Likes
Like

Posted 25 July 2016 - 02:01 PM

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.


Hero of Allacrost - A free, open-source 2D RPG in development.
Latest release June, 2015 - GameDev annoucement


#10   GDNet+   -  Reputation: 13693

Like
2Likes
Like

Posted 25 July 2016 - 03:32 PM

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.


throw table_exception("(ノ ゜Д゜)ノ ︵ ┻━┻");


#11   Members   -  Reputation: 569

Like
3Likes
Like

Posted 26 July 2016 - 02:47 AM

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, 26 July 2016 - 02:51 AM.

Don't ask my opinion about Unity3D.. here it is ! :D

- Big middle finger to AAA engines, indies team spreaded the word

- Then license price increase, big middle finger to indie teams too

- They integrated third-party ads, they have analytics, and missing their own ad network, missed  opportunity of a big middle finger to advertising services.

A Good tool, with a bad marketing.
 


#12   Members   -  Reputation: 1261

Like
3Likes
Like

Posted 26 July 2016 - 03:19 AM

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. 



#13   Members   -  Reputation: 569

Like
0Likes
Like

Posted 26 July 2016 - 06:19 AM

@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, 26 July 2016 - 06:20 AM.

Don't ask my opinion about Unity3D.. here it is ! :D

- Big middle finger to AAA engines, indies team spreaded the word

- Then license price increase, big middle finger to indie teams too

- They integrated third-party ads, they have analytics, and missing their own ad network, missed  opportunity of a big middle finger to advertising services.

A Good tool, with a bad marketing.
 


#14   Moderators   -  Reputation: 4555

Like
2Likes
Like

Posted 26 July 2016 - 07:14 AM

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, 26 July 2016 - 07:14 AM.


#15   Members   -  Reputation: 1261

Like
3Likes
Like

Posted 26 July 2016 - 07:46 AM

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. 



#16   Moderators   -  Reputation: 4555

Like
1Likes
Like

Posted 26 July 2016 - 07:59 AM

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?

#17   Members   -  Reputation: 1261

Like
2Likes
Like

Posted 26 July 2016 - 08:11 AM

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, 26 July 2016 - 08:14 AM.


#18   Members   -  Reputation: 2519

Like
1Likes
Like

Posted 28 July 2016 - 09:45 PM

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, 28 July 2016 - 10:32 PM.


#19   Members   -  Reputation: 181

Like
0Likes
Like

Posted 04 August 2016 - 02:17 AM

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:
	AddStatModifier(int delta)
	: 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)
{
	_modifiers.Add(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, 04 August 2016 - 02:28 AM.


#20   Members   -  Reputation: 5504

Like
2Likes
Like

Posted 04 August 2016 - 10:35 AM

_percent is not initialized in the the PercentageStatModifier







PARTNERS