C# 給 CardLib 添加 Cards 集合
這個(gè)新類Cards是Card對(duì)象的一個(gè)定制集合。在C:\BegirniingCSharp7\Chapter11目錄中創(chuàng)建一個(gè)新的類庫(kù)CMICardLib。然后刪除自動(dòng)生成的 Classl.cs 文件,再通過(guò) Project 丨 Add Existing Item 命令選擇 C:\BeginningCSharp7\Chapter10\Chl10CardLib目錄中的Card.cs、Deck.cs、Suit.cs和Rank.cs文件,把它們添加到項(xiàng)目中。
如果要自己創(chuàng)建這個(gè)項(xiàng)目,就應(yīng)添加一個(gè)新類Cards,并修改Cards.cs中的代碼,如下所示:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System,Threading.Tasks;
namespace ChllCardLib
{
public class Cards : CollectionBase
{
public void Add(Card newCard} => List.Add(newCard);
public void Remove(Card oldCard) => List.Remove(oldCard);
public Card this[int cardlndex]
{
get { return (Card)List[cardlndex]; }
set { List[cardlndex] = value; }
}
/// <summary>
/// Utility method for copying card instances into another Cards
/// instanco—used in Deck.Shuffle(). This implementation assumes that
/// source and target collections are the same size.
/// </summary>
public void CopyTo(Cards targetCards)
{
for (int index = 0; index < this.Count; index++)
{
targetCards[index] = this[index];
}
}
/// <sumzoary>
/// Check to see if the Cards collection contains a particular card.
/// This calls the Contains() method of the ArrayList for the collection,
/// which you access through the InnerList property.
/// </suromary>
public bool Contains(Card card) => InnerList.Contains(card);
}
}
然后需要修改Deck.cs,以利用這個(gè)新集合(而不是數(shù)組):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChllCardLib
{
public class Deck
{
private Cards cards = new Cards();
public Deck()
{
// Line of code removed here
for (int suitVal = 0; suitVal < 4; suitVal++)
{
for (int rankVal = 1; rankVal < 14; rankVal++)
{
cards.Add(new Card((Suit)suitVal, (Rank)rankVal));
}
}
}
public Card GetCard(int cardNum)
{
if (cardNum >= 0 && cardNum <= 51)
return cards[cardNum];
else
throw (new System.ArgumentOutOfRangeException{"cardNum", cardNum, "Value must be between 0 and 51."));
}
public void Shuffle()
{
Cards newDeck ? new Cards();
bool[] assigned = new bool[52];
Random sourceGen = new Random ();
for (int i = 0; i < 52; i++)
{
int sourceCard = 0;
bool foundCard = false;
while {foundCard == false)
{
sourceCard = sourceGen.Next(52);
if (assigned[sourceCard] == false)
foundCard = true;
}
assigned[sourceCard] = true;
newDeclc .Add(cards [sourceCard]};
}
newDeck.CopyTo < cards);
}
}
}
在此不需要做很多修改。其中大多數(shù)修改都涉及改變洗牌邏輯,才能把cards中隨機(jī)的一張牌添加到新Cards集合newDeck的開(kāi)頭,而不是把cards集合中順序位置的一張牌添加newDeck集合的隨機(jī)位置上。
ChlOCardLib解決方案的客戶控制臺(tái)應(yīng)用程序ChlOCardClient可使用這個(gè)新庫(kù)得到與以前相同的結(jié)果,因?yàn)镈eck的方法簽名沒(méi)有改變。這個(gè)類庫(kù)的客戶程序現(xiàn)在可以使用Caixls集合類,而不是依賴于CanI對(duì)象數(shù)組,例如,在撲克牌游戲應(yīng)用程序中定義一手牌。
點(diǎn)擊加載更多評(píng)論>>