事件和委託的應用:英雄和怪物之間進行攻擊,每次攻擊之後並會掉相應的血量

一直以來,對於事件和委託都感覺理解得很深刻,剛好最近突發奇想,平時打遊戲的時候英雄和怪物之間的攻擊行爲,可以作爲一個實例來寫。一般攻擊都會造成血量的下降,但是沒有辦法知道攻擊方什麼時候會攻擊,因此,可以將攻擊行爲定義爲一個事件,而掉血行爲寫成一個函數,這個函數訂閱上述攻擊行爲的事件,從而保證,每次攻擊完成後,被攻擊方發生掉血的行爲。下面是具體的實現代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace hero_and_monster
{
    public delegate void heroattackmonsterEventHandler();//定義委託
    public delegate void monsterattackheroEventHadler();//定義委託

    class hero
    {
        public hero()//構造函數
        {
            Console.ReadKey();
            Console.WriteLine("看吶,我們的英雄正緩緩向我們走來");
            Console.ReadKey();
        }
        public event heroattackmonsterEventHandler heroAttackEvent;//定義事件,英雄有攻擊的行爲
        protected void OnheroAttack()
        {
            if (heroAttackEvent!=null)
            {
                heroAttackEvent();
            }
        }
        public void attack(string str)//定義相應的函數,英雄有攻擊的行爲
        {
            if (str.Equals("monster"))
            {
                OnheroAttack();
            }
        }
        public void heroloseblood()//定義相應的函數,英雄受到攻擊時有掉血的行爲
        {
            Console.WriteLine("hero血量減少10%");
        }
    }
    class monster
    {
        public monster()//構造函數
        {
            Console.WriteLine("史上最強monster登場!");
            Console.ReadKey();
        }
        public event monsterattackheroEventHadler monsterAttackEvent;
        protected void OnmonsterAttack()
        {
            if (monsterAttackEvent!=null)
            {
                monsterAttackEvent();
            }
        }
        public void attack(string str)
        {
            if (str.Equals("hero"))
            {
                OnmonsterAttack();
            }
        }
        public void monsterloseblood()
        {
            Console.WriteLine("monster血量減少10%");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //實例化
            hero abravehero = new hero();
            monster aevilmonster = new monster();

            //訂閱事件
            abravehero.heroAttackEvent += new heroattackmonsterEventHandler(aevilmonster.monsterloseblood);
            aevilmonster.monsterAttackEvent += new monsterattackheroEventHadler(abravehero.heroloseblood);

            //英雄攻擊
            abravehero.attack("monster");
            Console.ReadKey();
            aevilmonster.attack("hero");
            Console.ReadKey();
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章