只要是同一个namespace,就可以当作是在一个文件中一样!
Suit.cs
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Demo{ public enum Suit { 梅花, 黑桃, 红桃, 方片 }}
Rank.cs
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Demo{ public enum Rank { Ace = 1, Deuce, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, }}
Card.cs基础
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Demo{ public class Card { public readonly Suit suit; public readonly Rank rank; public Card(Suit newSuit,Rank newRank) { suit = newSuit; rank = newRank; } private Card() { } public override string ToString() { return "The " + rank + " of " + suit; } }}
Deck.cs核心
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Demo{ public class Deck { private Card[] cards; public Deck() { cards = new Card[52]; for (int suitVal = 0;suitVal < 4;suitVal ++) { for (int rankVal = 1;rankVal < 14;rankVal ++) { cards[suitVal * 13 + rankVal - 1] = new Card((Suit)suitVal,(Rank)rankVal); } } } // 获取牌 public Card GetCard(int cardNum) { if (cardNum >=0 && cardNum <= 51) // 共52张牌,不包含大小王 { return cards[cardNum]; } else { throw (new System.ArgumentOutOfRangeException("cardNum",cardNum, "cardNum必须是0到51的数字")); } } // 随机发牌 public void Shuffle() { Card[] newDeck = new Card[52]; bool[] assigned = new bool[52]; Random sourceGen = new Random(); for (int i=0;i<52;i++) { int destCard = 0; bool foundCard = false; while(foundCard == false) { destCard = sourceGen.Next(52); //返回一个小于所指定最大值的非负随机数 if (assigned[destCard] == false) // 如果这个数字没有复制就跳出循环,给这个数字赋值 { foundCard = true; } } assigned[destCard] = true; newDeck[destCard] = cards[i]; } newDeck.CopyTo(cards,0); } }}
Program.cs主执行
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Demo{ class Program { static void Main(string[] args) { Deck myDeck = new Deck(); myDeck.Shuffle(); // 随机创建52张牌 for (int i=0;i<52;i++) { Card tempCard = myDeck.GetCard(i); Console.WriteLine(tempCard.ToString()); } Console.ReadKey(); } }}