定义一个角色(Role)类, 成员有 hp, atk, def, weapon实例
定义一个武器(Weapon)类, 成员有 name atk
在Main()实例化一个角色, 实例化 n 个武器
在 Role 中写方法, 装备武器,更换武器,拆下武器
当需要用角色的攻击力的时候:攻击 = 自身攻击力 + 武器攻击力
封装Role的hp, hp不能小于0大于9999,
武器的名字在构造函数中赋值,只读不能写
这样应该看的懂吧,基本是你的思路
class Program
{
static void Main(string[] args)
{
var role = new Role() { Atk = 1000, HP = 1000 };
var weapon1 = new Weapon("刀") { };
var weapon2 = new Weapon("枪") { };
var weapon3 = new Weapon("剑") { };
role.AddWeapon(weapon1);
role.ChangeWeapon(weapon2);
role.DeleteWeapon(weapon3);
Console.ReadKey();
}
}
public class Weapon
{
public Weapon(string name)
{
this.Name = name;
}
public string Name { get; }
public int Atk { get; set; }
}
public class Role
{
private int _hp;
public int HP
{
get { return _hp; }
set
{
if (value < 0 || value > 9999) throw new Exception("设置不在范围");
_hp = value;
}
}
public int Atk { get; set; }
public string Def { get; set; }
public Weapon Weapon { get; set; }
public int GetAtk()
{
int atk = (Weapon == null) ? 0 : Weapon.Atk;
return Atk + atk;
}
public void AddWeapon(Weapon weapon) { this.Weapon = weapon; }
public void ChangeWeapon(Weapon weapon) { this.Weapon = weapon; }
public void DeleteWeapon(Weapon weapon) { this.Weapon = null; }
}
谢谢
我打出来有一点报错,能加个微信请教一下么