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 = { "1", "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(); } }
测试: