Unity3D手机斗地主游戏开发实战(01)_发牌功能实

日期:2019-11-07编辑作者:跳舞机游戏

园子荒疏多年,闲来无事,用Unity3D来尝试做叁个简易的小游戏,一方面是对新近商量的Unity3D有一点点计算,一方面跟相近的园友相互学习和增强。话相当的少说,步入正题Unity3D手机斗地主游戏开发实战(01)_发牌功能实现。~

创造项目

1.成立Unity2017的2D项目,近些日子叫做ChinesePoker吧,就用自带的UGUI来编辑UI, 近来只导入iTween插件,用来低价调节动漫效果。

目录结构如下:

图片 1  图片 2

思考卡牌须求动态变化,小编把图片能源放到Resource目录,并依据卡德_类型(大小王,红桃,黑桃,方片,梅花 )_Unity3D手机斗地主游戏开发实战(01)_发牌功能实现。Unity3D手机斗地主游戏开发实战(01)_发牌功能实现。Unity3D手机斗地主游戏开发实战(01)_发牌功能实现。数字(卡片所在类型中的数字卡塔 尔(英语:State of Qatar)命名。

Unity3D手机斗地主游戏开发实战(01)_发牌功能实现。材料都以网上找的,没有摄影幼功,就是如此个乐趣,我们将就看吗,:卡塔 尔(阿拉伯语:قطر‎

2.建率先个现象,暗中同意叫001_Playing,作为关键玩牌的现象,一时半刻作为第一个情景,前期新情景增加进去,大家恐怕再调节场景的相继。

丰硕一个UI->Image,选用三个背景图片;

增加3个UI->Canvas,分别取名字为Player0,Player1,Player2,代表游戏的使用者,对手1,对手2;

各类Player底下,增多多少个Image,接纳卡片背面图片,分别代表发放营业牌照时各自牌堆的职位,并在桌面放置二个总牌堆的职位,私下认可not active;

建三个卡片的图样,命名字为Card,并视作预制件,放入Player0中间三个,稍稍偏移一定地点再停放二个,用来测算每张牌跟临牌相对地点,设置not active;

建三个卡片的北侧图片,命名Cover,也充当预制件;

增进七个测验按钮TestButton;

非常多了,大致结构如下:

图片 3

创制卡片、游戏者音信

1.新建CardInfo类,主要不要世襲暗中同意的MonoBehaviour类,用来作为卡牌的实体类;

得以达成IComparable接口,前边手牌排序会用到。

图片 4图片 5

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预制件上,增添卡德脚本,主要保存对应卡德Info新闻、选中状态,并加载卡片图片;

图片 6图片 7

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体系别,先制造三个集体的基类,达成玩家公共的方法,比如扩展一张卡片、清空全数卡牌、排序等;

图片 8图片 9

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对象上;

实现整合治理手牌的逻辑:发放营业证照后,从西路的职位,根据大小顺序将牌张开;

赢得牌面点击事件,将牌选中或打消选中;

图片 10图片 11

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.增加另意气风发种游戏用户(对手游戏用户卡塔 尔(英语:State of Qatar)PlayerOther,世袭Player,并挂载到Player1,Player2对象上;

一时半刻并未有落到实处任何其它效能:

图片 12图片 13

public class PlayerOther : Player
{

}

View Code

福寿康宁发放营业证件照逻辑

在Camera上增添卡片管理脚本:CardManager

1.落实洗牌逻辑,这里用生成GUID随机性后排序,到达洗牌的指标;

2.笔录当前发牌回合,每发一张牌,跳转给下一个游戏用户;

3.记下当前玩牌回合(今后大概用到卡塔尔国,每玩风华正茂局,跳转下个游戏的使用者起先发放营业证件照;

4.发放营业许可证逻辑:

安装牌堆的来得,动漫依次给各位游戏者发一张卡片,发完牌后,隐蔽牌堆,并将游戏者的卡片排序并展现;

图片 14图片 15

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集中管理,大家能够优化一下。

大抵逻辑实现,我们作证下效果啊:

图片 16

资源

花色源码

本文由新金沙国际手机版发布于跳舞机游戏,转载请注明出处:Unity3D手机斗地主游戏开发实战(01)_发牌功能实

关键词:

一定要骑行的理由

爱怜出行的人压力易释放 生命在于运动,骑行则是超级选择之风流浪漫。 人生在世,何人还平素不压力啊,骑行则是...

详细>>

《日赚1000元》1014 - 空手套白狼式赚钱思路

周末,接待了两拨客人。 一拨是来找媳妇推销产品的,另一波是来找我的。 先说第一波,是媳妇很长时间没联系的闺...

详细>>

庐山行

庐山行。庐山行。庐山行。     毛主席名诗《七律·登庐山》里用“跃上葱茏四百旋”来形容庐山山路弯道之多。而...

详细>>

雅筝琴社举办“喜迎元旦”汇报演出——叶子铭

      改头换面,面目一新。值此二零一七年新禧来到之际,雅筝琴社在毛先生的精心策划和团组织下,于今早(...

详细>>