码迷,mamicode.com
首页 > 其他好文 > 详细

拉米纸牌游戏开发之路学习篇2

时间:2015-09-11 20:47:03      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

在篇1中的Deck类中表示一副纸牌采用的是Card数组的方法,该种方法灵活性较小,在纸牌游戏中经常会用到一组纸牌的操作,在此有必要创建纸牌集合类Cards

1.通过继承集合类实现

首先介绍System.Collection空间中的ArryList类吧,该类继承了IList接口,可以动态添加或者移去元素,很好用.对之前的代码只需略加修改.具体修改如下:

(1)处,需要修改Deck类的字段

        //private Card[] _Cards=new Card[52];
        private ArrayList _CardsList = new ArrayList();

(2)处,需要修改Deck类构造器

public Deck()
        {
            for (int i = 0; i < 4; i++)
            {
                for (int j = 1; j <= 13; j++)
                {
                   // _Cards[i * 13 + j - 1] = new Card((CardSuit)i, (CardRank)j);
                    _CardsList.Add(new Card((CardSuit)i, (CardRank)j));
                }
            }
        }

(3)处,需要修改洗牌方法Shuffle() 

        public void Shuffle()
        {
            // Card[] cards=new Card[52];
            ArrayList cardsList = new ArrayList();
            bool[] isFind=new bool[52];
            Random rand=new Random();
            int index;
            for (int i = 0; i < 52; i++)
            {
                do
                {
                    index=rand.Next(52);
                }
                while(isFind[index]);
                //cards[i]=_Cards[index];
                cardsList.Add(_CardsList[index]);
                isFind[index] = true;
            }
            //cards.CopyTo(_Cards, 0);
            _CardsList=(ArrayList)cardsList.Clone();
        }

(4)处,需要修改GetCard()方法

        public Card GetCard(int cardIndex)
        {
            if(cardIndex<0 || cardIndex>=52)
                throw(new Exception("超过了索引范围[0,51]"));
            //return _Cards[cardIndex];
            return (Card)_CardsList[cardIndex];
        }

到此,修改全部完事,运行结果一样.但是这个类有一个致命的缺点,敬请下次分解.

拉米纸牌游戏开发之路学习篇2

标签:

原文地址:http://www.cnblogs.com/zhang-peng/p/4735221.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!