• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
lordGoldemort

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

26 posts in this topic

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?

1

Share this post


Link to post
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!

2

Share this post


Link to post
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
2

Share this post


Link to post
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.

0

Share this post


Link to post
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.

1

Share this post


Link to post
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.

2

Share this post


Link to post
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
0

Share this post


Link to post
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
2

Share this post


Link to post
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?
1

Share this post


Link to post
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
2

Share this post


Link to post
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
1

Share this post


Link to post
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:
	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
0

Share this post


Link to post
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
0

Share this post


Link to post
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.

0

Share this post


Link to post
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.
 

(Emphasis added)

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.

0

Share this post


Link to post
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
0

Share this post


Link to post
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 =)

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0