类入门例-猫狗互咬

以下例子演示动物类的写法,其中用到了构造函数。

在Main函数中,使用动物类创造出一只猫,一条狗。

猫狗互相攻击,直到一方死去。

代码如下:

class Animal
    {
        public string name;//动物名称
        public int hp, attack, speed;//动物血量、攻击力、攻击速度
        public Animal(string n,int life,int force,int s)
        {
            name = n;
            hp = life;
            attack = force;
            speed = s;
        }
        public void Attack(Animal x)
        {
            x.hp -= attack*speed;
        }
        public void show_Me()
        {
            Console.WriteLine(name+"还剩"+hp.ToString()+"点血");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Animal a, b;
            a = new Animal("dogy", 100, 20, 1);
            b = new Animal("caty", 80, 15, 2);
            do
            {
                a.Attack(b);
                b.show_Me();
                b.Attack(a);
                a.show_Me();
            }
            while (a.hp >= 0 && b.hp >= 0);
            Console.ReadKey();
        }
    }

运行效果:

当然,也可以使用随机函数让结果出现变数。

猜你喜欢

转载自www.cnblogs.com/wanjinliu/p/11518790.html
今日推荐