using System;
namespace OOP01
{
public class Monster
{
// 创建私有属性
private string mName;
private int mLevel;
private int mHp;
private int mAttack;
private int mDefence;
// 创建写入和读取方法
public string Name
{
set { this.mName = value; }
get { return this.mName; }
}
public int Level
{
set { this.mLevel = value;}
get
{
if (this.mLevel<1)
{
return 1;
}
if (this.mLevel>100)
{
return 100;
}
return this.mLevel;
}
}
public int Hp
{
set
{
if (value <= 0)
{
this.mHp = 0;
Console.WriteLine("{0}的血量为0,已死亡!",this.Name);
return;
}
this.mHp = value;
}
get { return this.mHp; }
}
public int Attack
{
set
{
this.mAttack = value;
}
get
{
return this.mAttack;
}
}
public int Defence
{
set { this.mDefence = value; }
get
{
if (this.mDefence<0)
{ return 0; }
return this.mDefence;
}
}
// 创建行为方法
public void AttackAction()
{
Console.WriteLine("我是怪物{0},等级{1},攻击力为{2}",this.Name,this.Level,this.Attack);
}
// 创建行为方法
public void Damage(int val)
{
this.Hp = this.Hp - val + this.Defence;
if (this.Hp > 0)
Console.WriteLine("{0}说:\"我受伤了,血量为{1},救我!\"",this.Name,this.Hp);
}
// 无参构造函数
public Monster(){}
// 有参构造函数
public Monster(string name, int level,int hp, int attack, int defence)
{
this.mName = name;
this.mLevel = level;
this.mHp = hp;
this.mAttack = attack;
this.mDefence = defence;
}
}
}
调用类
using System;
namespace OOP01
{
class Program
{
static void Main(string[] args)
{
Monster godzilla1 = new Monster();
Monster godzilla2 = new Monster("哥斯拉",90,100,30,50);
godzilla2.AttackAction();
godzilla2.Damage(90);
godzilla2.Damage(90);
Console.WriteLine("Finish!");
}
}
}