首页 新闻 赞助 找找看

我还是初学者,有很多不懂的地方,麻烦懂得人帮我一一下,谢谢了,让我参考一下,

0
[已解决问题] 解决于 2018-06-14 14:01

定义一个角色(Role)类, 成员有 hp, atk, def, weapon实例

定义一个武器(Weapon)类, 成员有 name atk

在Main()实例化一个角色, 实例化 n 个武器

在 Role 中写方法, 装备武器,更换武器,拆下武器

当需要用角色的攻击力的时候:攻击 = 自身攻击力 + 武器攻击力

封装Role的hp, hp不能小于0大于9999,

武器的名字在构造函数中赋值,只读不能写

Cheers11的主页 Cheers11 | 菜鸟二级 | 园豆:215
提问于:2018-06-14 11:24
< >
分享
最佳答案
0

这样应该看的懂吧,基本是你的思路

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; }
}

奖励园豆:5
半路独行 | 小虾三级 |园豆:574 | 2018-06-14 12:50

谢谢

Cheers11 | 园豆:215 (菜鸟二级) | 2018-06-14 12:52

我打出来有一点报错,能加个微信请教一下么

Cheers11 | 园豆:215 (菜鸟二级) | 2018-06-14 13:29
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册