Tuesday, December 13, 2016

How to design the attack class in an RPG game?


I am in the planning phase of a small RPG style game.


The character will have have a set of attributes, like strength, agility, etc which are represented as integers. The character also will have a set of attacks represented as an attack class.



On each attack I want it to do damage based on the characters attributes, eg: the attack "sword slash" will do 10 dmg + the value of the characters strength.


The way I was thinking to do this is to have an abstract attack class, which has an abstract Attack method, and for each attack I create one class that implements the Attack method.


public class SwordSlash:Attack
{
public void Attack(Character attacker, Character defender)
{
defender.DoDamage(10 + attacker.Strength);
}
}


I see that this will make it a nightmare to maintain.


Does anyone have an idea of how I can accomplish this in a nicer way?


What I think is the main problem is how to input the correct attribute, based on the attack.



Answer



You should probably go for a data-driven design here.


Make a generic Attack class which contains the parameters you want to work with - base damage, which stats affects the damage, a set of potential status effects... stuff like that:


public enum AttackStat
{
Strength,
Agility,

Intellect
// etc.
}

public class Attack
{
private int baseDamage;
private AttackStat stat;
private double damageMultiplier;
// ...and so on


public void Attack(Character attacker, Character defender)
{
defender.DoDamage(baseDamage + attacker.GetStatValue(stat) * damageMultiplier);
}
}

// Put a method on Character to fetch the appropriate value given an AttackStat:
public int GetStatValue(AttackStat s)
{

switch(s)
{
case AttackStat.Strength:
return strength;
case AttackStat.Agility:
return agility;
// etc.
}
}


Then, place your attacks in a file, e.g. an XML file, and load the data from there:







You could even extend this to draw values from multiple stats, say, a Fireball where the damage is calculated from both an Intellect and a Fire stat:








If you don't want to use the same basic damage formula for everything (e.g. calculate magic damage differently from physical damage), create subclasses of Attack for each formula you need and override Attack, and specify which type you want in your XML file.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...