VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • C# -- 模拟扑克牌发牌

C# -- 模拟扑克牌发牌

1.  User 类: 玩家

复制代码
public class User
{
    private List<PaperCard> listCard = new List<PaperCard>();

    public string Name { get; set; }

    public User(string strName)
    {
        this.Name = strName;
    }
    public void Add(PaperCard p)
    {
        listCard.Add(p);
    }

    public void Reset()
    {
        listCard.Clear();
    }

    public void Introduce()
    {
        string strCards = "";

        for (int i = 0; i < listCard.Count; i++)
        {
            if (i == 0)
            {
                strCards += listCard[i].Name;
            }
            else
            {
                strCards += ", " + listCard[i].Name;
            }
        }
        Console.WriteLine("\r\n--------------------------------------------");
        Console.Write("我是{0},", Name);
        Console.Write("我手中的扑克牌有{0}张:\r\n{1}\r\n", listCard.Count,strCards);
    }
}
复制代码

 

2. PaperCard类:纸牌

复制代码
public class PaperCard
{
    public string Type { get; set; }
    public string Number { get; set; }
    public PaperCard(string strType, string strNumber)
    {
        this.Type = strType;
        this.Number = strNumber;
    }

    public string Name
    {
        get
        {
            return string.Format("{0}{1}", this.Type, this.Number);
        }

        private set { }
    }
}
复制代码

 

3. 模拟发牌过程

复制代码
public void TestPlay()
{
    //产生扑克牌
    Console.WriteLine("正在生成扑克牌...");
    List<PaperCard> myCards = new List<PaperCard>();
    string[] strType = { "红桃", "黑桃", "梅花", "方块" };
    string[] strNumber = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
    PaperCard[] OtherCard = { new PaperCard("大王", ""), new PaperCard("小王", "") };

    for (int i = 0; i < strNumber.Length; i++)
    {
        for (int j = 0; j < strType.Length; j++)
        {
            PaperCard p = new PaperCard(strType[j], strNumber[i]);
            myCards.Add(p);
        }
    }

    for (int j = 0; j < OtherCard.Length; j++)
    {
        myCards.Add(OtherCard[j]);
    }

    //洗牌
    Console.WriteLine("正在洗牌...");
    Stack<PaperCard> stackCard = new Stack<PaperCard>();
    Random r = new Random();

    while (myCards.Count>0)
    {
        int iIndex = r.Next(0, myCards.Count);
        stackCard.Push(myCards[iIndex]);
        myCards.RemoveAt(iIndex);
    }



    //发牌
    Console.WriteLine("开始发牌...");
    List<User> listUser = new List<User>() {
        new User("大师兄"),
        new User("二师兄"),
        new User("三师弟")
    };

    while (stackCard.Count > 0)
    {
        for (int s = 0; s < listUser.Count; s++)
        {
            listUser[s].Add(stackCard.Pop());
        }
    }
    Console.WriteLine("发牌完成!");


    //看牌
    foreach (var item in listUser)
    {
        item.Introduce();
    }
}
复制代码

 

测试:


相关教程