角色属性设计分析
目前数据库有两张表与角色属性有关heroinfo 和 userinfo
heroinfo
存放英雄的初始属性,和growth(升级后增加值),如英雄2级了总血量就是
hp + 2 * hp_growth
userinfo
存放英雄的当前属性,即所有属性影响的最终结果
影响角色属性的外因
可以看出主脚的属性其实就是各种状态的计算结果,从图可以看出其实就是一个树状结构,主角就是树的根,于是我用组合模式简单实验了一下。
类图
Attribute 为虚类,主要方法就是Caculate,通过递归计算总属性(这里是hpTotal和mpTotal)
public abstract class Attribute
{
public int Hp { get; set; }
public int Mp { get; set; }
public int HpTotal { get; set; }
public int MpTotal { get; set; }
private Attribute m_Parent;
private string m_Name;
public Attribute(int hp, int mp)
{
this.Hp = hp;
this.Mp = mp;
}
public Attribute(int hp, int mp, string name) : this(hp, mp)
{
this.m_Name = name;
}
public abstract void Calc();
public abstract int ChildCount();
protected void SetParent(Attribute child)
{
child.m_Parent = this;
}
public Attribute GetParent()
{
return this.m_Parent;
}
public void Show()
{
Calc();
Console.WriteLine(string.Format("{0} 属性为: HP {1} MP {2}",this.m_Name, this.HpTotal, this.MpTotal));
}
}
AttributeComponet为节点,实现了Attribute的方法,并且可以添加节点和删除节点
public class AttributeComponent:Attribute
{
private List<Attribute> m_AttributeList = new List<Attribute>();
public AttributeComponent(int hp, int mp) : base(hp, mp)
{
}
public AttributeComponent(int hp, int mp, string name) : base(hp, mp, name) { }
public override void Calc()
{
this.HpTotal = this.Hp;
this.MpTotal = this.Mp;
foreach (Attribute item in m_AttributeList)
{
//递归计算属性和
if (item.ChildCount() > 0)
item.Calc();
this.HpTotal += item.HpTotal;
this.MpTotal += item.MpTotal;
}
}
public override int ChildCount()
{
return m_AttributeList.Count;
}
public void AddAttribute(Attribute attribute)
{
SetParent(attribute);
this.m_AttributeList.Add(attribute);
}
public void RemoveAttribute(Attribute attribute)
{
m_AttributeList.Remove(attribute);
}
}
测试代码
[TestMethod]
public void TestMethod1()
{
AttributeComponent basic = new AttributeComponent(50, 100, "Ali");
AttributeComponent lvUp = new AttributeComponent(50, 100, "升级增加");
AttributeComponent weapon = new AttributeComponent(10, 20, "无级弓");
AttributeComponent weaponEnchanting = new AttributeComponent(5, 5, "附魔增加");
basic.Show();
Console.WriteLine("升级啦");
Console.WriteLine("---------------------------------------------------");
lvUp.Show();
basic.AddAttribute(lvUp);
basic.Show();
Console.WriteLine();
Console.WriteLine("装备了武器");
Console.WriteLine("---------------------------------------------------");
weapon.Show();
basic.AddAttribute(weapon);
basic.Show();
Console.WriteLine();
Console.WriteLine("武器附魔");
Console.WriteLine("---------------------------------------------------");
weaponEnchanting.Show();
weapon.AddAttribute(weaponEnchanting);
weapon.Show();
basic.Show();
Console.WriteLine();
Console.WriteLine("卸载装备");
Console.WriteLine("---------------------------------------------------");
basic.RemoveAttribute(weapon);
basic.Show();
}
测试结果