葡京游戏网址HTML5坦克大战(韩顺平版本)

HTML5坦克大战(韩顺平版本)

 2017-3-22
22:46:22 by SemiconductorKING

 

  年暑假学习了瞬间HTML5实现简单的坦克大战,觉得对JavaScript初家的话,练习这个小游戏代码段可以学到广大东西,包括canvas的简约用,类的组织,类的继承等等。编写一个圆的玩一经出比强之逻辑性,这个demo的修视频以及demo文件下充斥见我享受的链接:

   链接:http://pan.baidu.com/s/1boAzSir
密码:mcp2

 

   demo截图:

 

  此demo只是一个大概的演习,效果low不low先不提,看代码吧:

 

  HTML文件代码:

  1 <!DOCTYPE html>
  2 <html>
  3 <head>
  4 <meta charset='utf-8'/>
  5 <script src='tank.js'></script>
  6 </head>
  7 <body onkeydown="changeDirect()">
  8 <h1 style="color: #0714b9;">html5坦克大战</h1>
  9 <div style="margin: 30px">
 10     <canvas id='tankMap' width='500px' height='300px' style='background-color:#3e0549;'>
 11         你的浏览器不支持canvas标签 ||||| You are seeing this message because your web browser does not support the canvas tag.
 12     </canvas>
 13 </div>
 14 <div id='add1'></div>
 15 <div id='add2'></div>
 16 <div id='add3'></div>
 17 <div style="margin: 30px;font-size: 12px">
 18     <p>控制方法:按下键盘w s a d或者↑ ↓ ← →分别是坦克的上下左右行驶<br/>按下j或者Enter键为射击</p>
 19 </div>
 20 </body>
 21 <script>
 22     var canvas = document.getElementById('tankMap');
 23     //获得画笔
 24     var ctx = canvas.getContext('2d');
 25 
 26     //定义炸弹数组
 27     var bombs = new Array();
 28 
 29     //构造英雄
 30     var hero = new Hero(380,260,0,heroColor);
 31 
 32     //创建敌人数组
 33     var enemyTanks = new Array();
 34 
 35     //创建敌人的子弹数组
 36     var enemyBullets = new Array();
 37     for(var i=0;i<6;i++){
 38         var enemyTank = new EnemyTank((i+1)*50,0,2,enemyColor);
 39         enemyTanks[i] = enemyTank;
 40         //drawTank(enemyTanks[i]);
 41         //让敌人的坦克动起来
 42         var timer = window.setInterval("enemyTanks["+i+"].run()",50);
 43         enemyTanks[i].timer = timer;
 44         //让敌人发射子弹
 45         var enemyBullet = new Bullet(enemyTanks[i].x+9,enemyTanks[i].y+30,enemyTanks[i].direct,enemyTanks[i],'enemy');
 46         enemyBullets.push(enemyBullet);
 47         enemyBullets[i].timer = window.setInterval("enemyBullets["+i+"].run()",50);
 48     }
 49 
 50     //定义英雄子弹数组
 51     var heroBullets = new Array();
 52     var heroBullet = null;
 53     
 54     if(hero.isLive){
 55             drawTank(hero);
 56         }
 57 
 58     //flashMap();
 59     //重置画布
 60     function flashMap(){
 61         ctx.clearRect(0,0,500,300);
 62         isHitHeroTank(enemyBullets,hero);
 63         if(hero.isLive){
 64             drawTank(hero);
 65         }
 66         
 67         isHitEnemyTank(heroBullets,enemyTanks);
 68         //画出自己坦克的子弹
 69         drawHeroBullet(heroBullets);
 70         //画出敌人坦克的子弹
 71         drawEnemyBullet(enemyBullets,enemyTanks);
 72         for(var i=0;i<6;i++){
 73             if(enemyTanks[i].isLive){
 74                 drawTank(enemyTanks[i]);
 75             }
 76         }
 77 
 78         //画出爆炸图片
 79         for(var k=0;k<bombs.length;k++){
 80             var img = new Image();
 81             img.src = 'bomb_1.gif';
 82             var x = bombs[k].x;
 83             var y = bombs[k].y;
 84             ctx.drawImage(img,x,y,30,30);
 85             ctx.drawImage(img,x,y,40,35);
 86             ctx.drawImage(img,x,y,35,40);
 87             bombs.splice(k,1);
 88         }
 89     }
 90 
 91     function changeDirect(){
 92         var keycode = event.keyCode;
 93         switch(keycode){
 94             case 38:;
 95             case 87:hero.moveUp();break;
 96             case 39:;
 97             case 68:hero.moveRight();break;
 98             case 40:;
 99             case 83:hero.moveBottom();break;
100             case 37:;
101             case 65:hero.moveLeft();break;
102             case 74:;
103             case 13:hero.shotEnemy();break;
104         }
105         flashMap();
106     }
107     window.setInterval("flashMap()",50);
108 </script>
109 </html>

 

  tank.js代码:

  1 //定义敌人和我们自己的坦克的颜色
  2 var enemyColor = new Array("#0BB","#0FF");
  3 var heroColor = new Array("#dc0","#ff5");
  4 //封装一个公用的坦克父类
  5 function Tank(x,y,direct){
  6     this.x = x;
  7     this.y = y;
  8     this.speed = 3;
  9     this.direct = direct;
 10     this.moveUp = function(){
 11         if (hero.y>0) {
 12             hero.y -= hero.speed;
 13         }
 14         hero.direct = 0;
 15     }
 16     this.moveRight = function(){
 17         if (hero.x+30<500) {
 18             hero.x += hero.speed;
 19         }
 20         hero.direct = 1;
 21     }
 22     this.moveBottom = function(){
 23         if (hero.y+30<300) {
 24             hero.y += hero.speed;
 25         }
 26         hero.direct = 2;
 27     }
 28     this.moveLeft = function(){
 29         if (hero.x>0) {
 30             hero.x -= hero.speed;
 31         }
 32         hero.direct = 3;
 33     }
 34 }
 35 
 36 //英雄坦克类
 37 function Hero(x,y,direct,color){
 38     //将坦克类的构造方法赋给hero
 39     this.hero = Tank;
 40     //调用,拥有坦克类的所有的属性和方法
 41     this.hero(x,y,direct);
 42     this.color = color;
 43     this.direct = direct;
 44     this.isLive = true;
 45     this.shotEnemy = function(){
 46         switch(this.direct){
 47             case 0:
 48                 heroBullet = new Bullet(this.x+9,this.y,this.direct);
 49             break;
 50             case 1:
 51                 heroBullet = new Bullet(this.x+30,this.y+9,this.direct);
 52             break;
 53             case 2:
 54                 heroBullet = new Bullet(this.x+9,this.y+30,this.direct);
 55             break;
 56             case 3:
 57                 heroBullet = new Bullet(this.x,this.y+9,this.direct);
 58             break;
 59         }
 60         heroBullets.push(heroBullet);
 61         heroBullets[heroBullets.length-1].timer = window.setInterval("heroBullets["+(heroBullets.length-1)+"].run()",50);
 62     }
 63 }
 64 //敌人的坦克
 65 function EnemyTank(x,y,direct,color){
 66     //将坦克类的构造方法赋给敌人坦克
 67     this.enemyTank = Tank;
 68     //调用,拥有坦克类的所有的属性和方法
 69     this.enemyTank(x,y,direct);
 70     this.color = color;
 71     this.isLive = true;
 72     this.timer = null;
 73     this.speed = 1;
 74     this.count = 0;
 75     this.direct = direct;
 76     this.bulletIsLive = true;
 77     this.run = function(){
 78         switch(this.direct){
 79             case 0:
 80                 if(this.y>0){
 81                 this.y--;
 82             }
 83             break;
 84             case 1:
 85                 if(this.x+30<500){
 86                 this.x += this.speed;
 87             }
 88             break;
 89             case 2:
 90                 if(this.y+30<300){
 91                 this.y += this.speed;
 92             }
 93             break;
 94             case 3:
 95                 if(this.x>0){
 96                 this.x -= this.speed;
 97             }
 98             break;
 99         }
100         
101         if(this.count>=30){
102             this.direct = Math.round(Math.random()*3);
103             this.count=0;
104         }
105         this.count++;
106         //在坦克走的过程中,判断一下,这个坦克的子弹是否活着
107         if(this.bulletIsLive == false && this.isLive){
108             //子弹over,加子弹
109             switch(this.direct){
110                 case 0:
111                     enemyBullets.push(new Bullet(this.x+9,this.y,this.direct,this,'enemy'));
112                 break;
113                 case 1:
114                     enemyBullets.push(new Bullet(this.x+30,this.y+9,this.direct,this,'enemy'));
115                 break;
116                 case 2:
117                     enemyBullets.push(new Bullet(this.x+9,this.y+30,this.direct,this,'enemy'));
118                 break;
119                 case 3:
120                     enemyBullets.push(new Bullet(this.x,this.y+9,this.direct,this,'enemy'));
121                 break;
122             }
123             enemyBullets[enemyBullets.length-1].timer = window.setInterval("enemyBullets["+(enemyBullets.length-1)+"].run()",50);
124                 this.bulletIsLive = true;
125         }
126     }
127 }
128 //绘制坦克
129     function drawTank(hero){
130     switch(hero.direct){
131         case 0:
132         case 2:
133             ctx.fillStyle = hero.color[0];
134             ctx.fillRect(hero.x,hero.y,5,30);
135             ctx.fillRect(hero.x+15,hero.y,5,30);
136             ctx.fillRect(hero.x+6,hero.y+5,8,20);
137             ctx.fillStyle = hero.color[1];
138             ctx.beginPath();
139             ctx.arc(hero.x+10,hero.y+15,3,0,Math.PI*2,true);
140             ctx.closePath();
141             ctx.fill();
142             //画出炮筒(直线)
143             ctx.strokeStyle = hero.color[1];
144             ctx.lineWidth = 2;
145             ctx.moveTo(hero.x+10,hero.y+15);
146             if(hero.direct==0){
147                 ctx.lineTo(hero.x+10,hero.y);
148             }else if(hero.direct==2){
149                 ctx.lineTo(hero.x+10,hero.y+30);
150             }
151             ctx.stroke();
152         break;
153         case 1:
154         case 3:
155             ctx.fillStyle = hero.color[0];
156             ctx.fillRect(hero.x,hero.y,30,5);
157             ctx.fillRect(hero.x,hero.y+15,30,5);
158             ctx.fillRect(hero.x+5,hero.y+6,20,8);
159             //需要注意,画圆的时候需要重新开启路径
160             ctx.fillStyle = hero.color[1];
161             ctx.beginPath();
162             ctx.arc(hero.x+15,hero.y+10,3,0,Math.PI*2,true);
163             ctx.closePath();
164             ctx.fill();
165             //画出炮筒(直线)
166             ctx.strokeStyle = hero.color[1];
167             ctx.lineWidth = 2;
168             ctx.moveTo(hero.x+15,hero.y+10);
169             if(hero.direct ==1){
170                 ctx.lineTo(hero.x+30,hero.y+10);
171             }else if(hero.direct ==3){
172                 ctx.lineTo(hero.x,hero.y+10);
173             }
174             ctx.stroke();
175         break;
176     }
177 }
178 
179 //定义一个子弹类
180 function Bullet(x,y,direct,tank,type){
181     this.x = x;
182     this.y = y;
183     this.speed = 3;
184     this.direct = direct;
185     this.timer = null;
186     this.isLive = true;
187     this.tank = tank;
188     this.type = type;
189     this.run = function(){
190         switch(this.direct){
191             case 0:
192                 this.y -= this.speed;
193             break;
194             case 1:
195                 this.x += this.speed;
196             break;
197             case 2:
198                 this.y += this.speed;
199             break;
200             case 3:
201                 this.x -= this.speed;
202             break;
203         }
204         document.getElementById('add1').innerText = " 子弹x轴:"+this.x+" 子弹y轴:"+this.y;
205         document.getElementById('add2').innerText = " 坦克x轴:"+hero.x+" 坦克y轴:"+hero.y;
206         document.getElementById('add3').innerText = " hero子弹数量:"+heroBullets.length;
207         if(this.x <0 || this.x>=500 ||this.y<0 || this.y>300 || this.isLive==false){
208             this.isLive = false;
209             if(this.type=='enemy'){
210                 this.tank.bulletIsLive = false;
211             }
212             window.clearInterval(this.timer);
213         }
214     }
215 }
216 function drawHeroBullet(bullets){
217     for(var i=0;i<bullets.length;i++){
218         var heroBullet = bullets[i];
219         if(heroBullet.isLive){
220             ctx.fillStyle = '#FEF26E';
221             ctx.fillRect(heroBullet.x,heroBullet.y,2,2);
222         }
223     }
224 }
225 //画出敌人坦克的子弹
226 function drawEnemyBullet(enemyBullets){
227     for(var i=0;i<enemyBullets.length;i++){
228         var enemyBullet = enemyBullets[i];
229         if(enemyBullet.isLive){
230             ctx.fillRect(enemyBullet.x,enemyBullet.y,2,2);
231         }
232     }
233 }
234 function isHitEnemyTank(heroBullets,enemyTanks){
235     for(var i=0;i<heroBullets.length;i++){
236         for(var j=0;j<enemyTanks.length;j++){
237             //判断一下自己的子弹和敌人的坦克坐标
238             if(enemyTanks[j].isLive){
239                 switch(enemyTanks[j].direct){
240                 case 0:
241                 case 2:
242                     if(heroBullets[i].x>=enemyTanks[j].x&&heroBullets[i].x<=enemyTanks[j].x+20&&heroBullets[i].y>=enemyTanks[j].y&&heroBullets[i].y<=enemyTanks[j].y+30){
243                         //标记敌人的坦克和我们的子弹已经死掉了
244                         heroBullets[i].isLive = false;
245                         enemyTanks[j].isLive = false;
246                         var bomb = new Bomb(enemyTanks[j].x,enemyTanks[j].y);
247                         bombs.push(bomb);
248 
249                 }
250                 break;
251                 case 1:
252                 case 3:
253                     if(heroBullets[i].x>=enemyTanks[j].x&&heroBullets[i].x<=enemyTanks[j].x+30&&heroBullets[i].y>=enemyTanks[j].y&&heroBullets[i].y<=enemyTanks[j].y+20){
254                         //标记敌人的坦克和我们的子弹已经死掉了
255                         heroBullets[i].isLive = false;
256                         enemyTanks[j].isLive = false;
257                         var bomb = new Bomb(enemyTanks[j].x,enemyTanks[j].y);
258                         bombs.push(bomb);
259                 }
260                 break;
261             }
262             }
263             
264         }
265     }
266 }
267 
268 //定义炸弹类
269 function Bomb(x,y){
270     this.x = x;
271     this.y = y;
272 }
273 
274 //判断敌人的子弹是否击中自己的坦克
275 function isHitHeroTank(enemyBullets,heroTank){
276     for(var i=0;i<enemyBullets.length;i++){
277         if(enemyBullets[i].isLive && heroTank.isLive){
278             switch(heroTank.direct){
279             case 0:
280             case 2:
281                 if(enemyBullets[i].x >= heroTank.x && enemyBullets[i].x <= heroTank.x+20 && enemyBullets[i].y >= heroTank.y && enemyBullets[i].y <= heroTank.y +30){
282                 heroTank.isLive = false;
283                 enemyBullets[i].isLive = false;
284             }
285             break;
286             case 1:
287             case 3:
288                 if(enemyBullets[i].x >= heroTank.x && enemyBullets[i].x <= heroTank.x+30 && enemyBullets[i].y >= heroTank.y && enemyBullets[i].y <= heroTank.y +20){
289                 heroTank.isLive = false;
290                 enemyBullets[i].isLive = false;
291             }
292             break;
293         }
294         }
295     }
296 }

end…

园子荒废多年,闲来无事,用Unity3D来尝试做一个概括的小游戏,一方面是本着多年来研究的Unity3D有点总结,一方面与周边的园友相互学习及增长。话不多说,进入正题~

缔造项目

1.创造Unity2017之2D项目,暂且叫做ChinesePoker吧,就用自带的UGUI来编辑UI,
目前单导入iTween插件,用来便宜控制动画效果。

目结构如下:

  

设想卡牌需要动态变化,我把图片资源放到Resource目录,并遵照Card_类型(大小王,红桃,黑桃,方片,梅花
)_数字(卡牌所在类型中之数字)命名。

材料都是网上寻找的,没有图基础,就是这么个意,大家将就看吧,:)

2.建率先独现象,默认叫001_Playing,作为首要玩牌的情景,暂时作为第1只情景,后期新状况添加上,我们恐怕再也调整场景的逐条。

长一个UI->Image,选择一个背景图片;

丰富3独UI->Canvas,分别得到名叫Player0,Player1,Player2,代表玩家,对手1,对手2;

每个Player底下,添加一个Image,选择卡牌背面图片,分别表示发牌时各自牌堆的职,并于桌面放置一个总牌堆的职位,默认not
active;

建筑一个卡牌的图形,命名也Card,并视作预制件,放入Player0中间一个,稍微偏移一定位置更放置一个,用来计量各国张牌跟临牌相对位置,设置not
active;

建造一个卡牌的反面图片,命名Cover,也当预制件;

丰富一个测试照钮TestButton;

多了,大概结构如下:

创造卡牌、玩家信息

1.新建CardInfo类,主要不设继续默认的MonoBehaviour类,用来作卡牌的实业类;

实现IComparable接口,后面手牌排序会用到。

public class CardInfo : IComparable
{
    public string cardName; //卡牌图片名
    public CardTypes cardType; //牌的类型
    public int cardIndex;      //牌在所在类型的索引1-13

    public CardInfo(string cardName)
    {
        this.cardName = cardName;
        var splits = cardName.Split('_');

        switch (splits[1])
        {
            case "1":
                cardType = CardTypes.Hearts;
                cardIndex = int.Parse(splits[2]);
                break;
            case "2":
                cardType = CardTypes.Spades;
                cardIndex = int.Parse(splits[2]);
                break;
            case "3":
                cardType = CardTypes.Diamonds;
                cardIndex = int.Parse(splits[2]);
                break;
            case "4":
                cardType = CardTypes.Clubs;
                cardIndex = int.Parse(splits[2]);
                break;
            case "joker":
                cardType = CardTypes.Joker;
                cardIndex = int.Parse(splits[2]);
                break;
            default:
                throw new Exception(string.Format("卡牌文件名{0}非法!", cardName));
        }
    }

    //卡牌大小比较
    public int CompareTo(object obj)
    {
        CardInfo other = obj as CardInfo;

        if (other == null)
            throw new Exception("比较对象类型非法!");

        //如果当前是大小王
        if (cardType == CardTypes.Joker)
        {
            //对方也是大小王
            if (other.cardType == CardTypes.Joker)
            {
                return cardIndex.CompareTo(other.cardIndex);
            }
            //对方不是大小王
            return 1;
        }
        //如果是一般的牌
        else
        {
            //对方是大小王
            if (other.cardType == CardTypes.Joker)
            {
                return -1;
            }
            //如果对方也是一般的牌
            else
            {
                //计算牌力
                var thisNewIndex = (cardIndex == 1 || cardIndex == 2) ? 13 + cardIndex : cardIndex;
                var otherNewIndex = (other.cardIndex == 1 || other.cardIndex == 2) ? 13 + other.cardIndex : other.cardIndex;

                if (thisNewIndex == otherNewIndex)
                {
                    return -cardType.CompareTo(other.cardType);
                }

                return thisNewIndex.CompareTo(otherNewIndex);
            }
        }
    }

}

View Code

2.Card预制桩及,添加Card脚本,主要保存对许CardInfo信息、选中状态,并加载卡牌图片;

public class Card : MonoBehaviour
{
    private Image image;        //牌的图片
    private CardInfo cardInfo;  //卡牌信息
    private bool isSelected;    //是否选中

    void Awake()
    {
        image = GetComponent<Image>();
    }

    /// <summary>
    /// 初始化图片
    /// </summary>
    /// <param name="cardInfo"></param>
    public void InitImage(CardInfo cardInfo)
    {
        this.cardInfo = cardInfo;
        image.sprite = Resources.Load("Images/Cards/" + cardInfo.cardName, typeof(Sprite)) as Sprite;
    }
    /// <summary>
    /// 设置选择状态
    /// </summary>
    public void SetSelectState()
    {
        if (isSelected)
        {
            iTween.MoveTo(gameObject, transform.position - Vector3.up * 10f, 1f);
        }
        else
        {
            iTween.MoveTo(gameObject, transform.position + Vector3.up * 10f, 1f);
        }

        isSelected = !isSelected;
    }
}

View Code

3.设想玩家分为2种门类,先创造一个集体的基类,实现玩家公共的法,比如增加一布置卡牌、清空所有卡片、排序等;

public class Player : MonoBehaviour
{
    protected List<CardInfo> cardInfos = new List<CardInfo>();  //个人所持卡牌

    private Text cardCoutText;

    void Start()
    {
        cardCoutText = transform.Find("HeapPos/Text").GetComponent<Text>();
    }

    /// <summary>
    /// 增加一张卡牌
    /// </summary>
    /// <param name="cardName"></param>
    public void AddCard(string cardName)
    {
        cardInfos.Add(new CardInfo(cardName));
        cardCoutText.text = cardInfos.Count.ToString();
    }
    /// <summary>
    /// 清空所有卡片
    /// </summary>
    public void DropCards()
    {
        cardInfos.Clear();
    }

    protected void Sort()
    {
        cardInfos.Sort();
        cardInfos.Reverse();
    }
}

View Code

4.添加首先种植玩家(自身玩家)PlayerSelf,继承Player,并挂载到Player0对象上;

兑现整治手牌的逻辑:发牌后,从中间的职位,根据大小顺序将牌展开;

得到牌面点击事件,将牌选中或取消选中;

public class PlayerSelf : Player
{
    public GameObject prefab;   //预制件

    private Transform originPos1; //牌的初始位置
    private Transform originPos2; //牌的初始位置
    private List<GameObject>  cards=new List<GameObject>();

    void Awake()
    {
        originPos1 = transform.Find("OriginPos1");
        originPos2 = transform.Find("OriginPos2");
    }

    //整理手牌
    public void GenerateAllCards()
    {
        //排序
        Sort();
        //计算每张牌的偏移
        var offsetX = originPos2.position.x - originPos1.position.x;
        //获取最左边的起点
        int leftCount = (cardInfos.Count / 2);
        var startPos = originPos1.position + Vector3.left * offsetX * leftCount;

        for (int i = 0; i < cardInfos.Count; i++)
        {
            //生成卡牌
            var card = Instantiate(prefab, originPos1.position, Quaternion.identity, transform);
            card.GetComponent<RectTransform>().localScale = Vector3.one * 0.6f;
            card.GetComponent<Card>().InitImage(cardInfos[i]);

            var targetPos = startPos + Vector3.right * offsetX * i;
            card.transform.SetAsLastSibling();
            //动画移动
            iTween.MoveTo(card, targetPos, 2f);

            cards.Add(card);
        }
    }

    public void DestroyAllCards()
    {
        cards.ForEach(Destroy);
        cards.Clear();
    }

    /// <summary>
    /// 点击卡牌处理
    /// </summary>
    /// <param name="data"></param>
    public void CardClick(BaseEventData data)
    {
        //叫牌或出牌阶段才可以选牌
        if (CardManager._instance.cardManagerState == CardManagerStates.Bid ||
            CardManager._instance.cardManagerState == CardManagerStates.Playing)
        {
            var eventData = data as PointerEventData;
            if (eventData == null) return;

            var card = eventData.pointerCurrentRaycast.gameObject.GetComponent<Card>();
            if (card == null) return;

            card.SetSelectState();
        }
    }
}

View Code

5.添加另一样种玩家(对手玩家)PlayerOther,继承Player,并挂载到Player1,Player2对象上;

临时没有落实任何其它职能:

public class PlayerOther : Player
{

}

View Code

落实发牌逻辑

在Camera上加加卡牌管理脚本:CardManager

1.贯彻洗牌逻辑,这里用生成GUID随机性后排序,达到洗牌的目的;

2.笔录时发牌回合,每发一样张牌,跳反受下一个玩家;

3.笔录时玩牌回合(将来或就此到),每玩一企业,跳反下只玩家开始发牌;

4.发牌逻辑:

安装牌堆的显得,动画依次给每人玩下发一样布置卡牌,发为止牌后,隐藏牌堆,并将玩家的卡牌排序并展示;

public class CardManager : MonoBehaviour
{
    public float dealCardSpeed = 20;  //发牌速度
    public Player[] Players;    //玩家的集合

    public GameObject coverPrefab;      //背面排预制件
    public Transform heapPos;           //牌堆位置
    public Transform[] playerHeapPos;    //玩家牌堆位置


    public static CardManager _instance;    //单例
    public CardManagerStates cardManagerState;

    private string[] cardNames;  //所有牌集合
    private int termStartIndex = 0;  //回合开始玩家索引
    private int termCurrentIndex = 0;  //回合当前玩家索引
    private List<GameObject> covers = new List<GameObject>();   //背面卡牌对象,发牌结束后销毁

    void Awake()
    {
        _instance = this;

        cardNames = GetCardNames();
    }
    /// <summary>
    /// 洗牌
    /// </summary>
    public void ShuffleCards()
    {
        //进入洗牌阶段
        cardManagerState = CardManagerStates.ShuffleCards;
        cardNames = cardNames.OrderBy(c => Guid.NewGuid()).ToArray();
    }
    /// <summary>
    /// 发牌
    /// </summary>
    public IEnumerator DealCards()
    {
        //进入发牌阶段
        cardManagerState = CardManagerStates.DealCards;

        //显示牌堆
        heapPos.gameObject.SetActive(true);
        playerHeapPos.ToList().ForEach(s => { s.gameObject.SetActive(true); });

        foreach (var cardName in cardNames)
        {
            //给当前玩家发一张牌
            Players[termCurrentIndex].AddCard(cardName);

            var cover = Instantiate(coverPrefab, heapPos.position, Quaternion.identity, heapPos.transform);
            cover.GetComponent<RectTransform>().localScale = Vector3.one;
            covers.Add(cover);
            iTween.MoveTo(cover, playerHeapPos[termCurrentIndex].position, 0.3f);

            yield return new WaitForSeconds(1 / dealCardSpeed);

            //下一个需要发牌者
            SetNextPlayer();
        }

        //隐藏牌堆
        heapPos.gameObject.SetActive(false);
        playerHeapPos[0].gameObject.SetActive(false);

        //显示玩家手牌
        Players.ToList().ForEach(s =>
        {
            var player0 = s as PlayerSelf;
            if (player0 != null)
            {
                player0.GenerateAllCards();
            }
        });
        //动画结束,进入叫牌阶段
        yield return new WaitForSeconds(2f);
        covers.ForEach(Destroy);
        cardManagerState = CardManagerStates.Bid;
    }
    /// <summary>
    /// 清空牌局
    /// </summary>
    public void ClearCards()
    {
        //清空所有玩家卡牌
        Players.ToList().ForEach(s => s.DropCards());

        //显示玩家手牌
        Players.ToList().ForEach(s =>
        {
            var player0 = s as PlayerSelf;
            if (player0 != null)
            {
                player0.DestroyAllCards();
            }
        });
    }

    /// <summary>
    /// 获取下个玩家
    /// </summary>
    /// <returns></returns>

    private void SetNextPlayer()
    {
        termCurrentIndex = (termCurrentIndex + 1) % Players.Length;
    }
    /// <summary>
    /// 切换开始回合玩家
    /// </summary>
    public void SetNextTerm()
    {
        termStartIndex = (termStartIndex + 1) % Players.Length;
    }
    private string[] GetCardNames()
    {
        //路径  
        string fullPath = "Assets/Resources/Images/Cards/";

        if (Directory.Exists(fullPath))
        {
            DirectoryInfo direction = new DirectoryInfo(fullPath);
            FileInfo[] files = direction.GetFiles("*.png", SearchOption.AllDirectories);

            return files.Select(s => Path.GetFileNameWithoutExtension(s.Name)).ToArray();
        }
        return null;
    }

    //for test
    public void OnTestClick()
    {
        ClearCards();
        ShuffleCards();
        StartCoroutine(DealCards());
    }

}

View Code

总结

实则发牌后的卡通片,可以由override基类的办法,交由Player子类处理,不用CardManager集中管理,大家可优化一下。

大约逻辑完成,我们证实下效果吧:

资源

类型源码