using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ch10CardLib;
namespace Execise05
{
class Program
{
static void Main(string[] args)
{
Deck playDeck = new Deck();
playDeck.Shuffle();
bool isFlush = false;
int flushHandIndex = 0;
for (int hand = 0; hand < 10;hand++ )
{
isFlush = true;
Suit flushSuit = playDeck.GetCard(hand * 5).suit;//第一张牌,第6张,第13张牌……45张
for (int card = 1; card < 5;card++ )//抽取5张牌
{
//hand*5=+card=0*5+1=1,从第二张牌开始抽取,看是否与第一次抽取的牌,flushSuit,花色是否相同
if (playDeck.GetCard(hand*5+card).suit!=flushSuit)
{
isFlush = false;
break;
}
}
if (isFlush)
{
flushHandIndex = hand * 5;
break;
}
}
if (isFlush)
{
Console.WriteLine("同花色!");
for (int card = 0; card < 5;card++)
{
Console.WriteLine(playDeck.GetCard(flushHandIndex + card));
}
}
else
{
Console.WriteLine("没有同花色!");
}
Console.ReadKey();
}
}
}
对参考答案的修改为此段:
for (int card = 1; card < 5;card++ )//抽取5张牌
{
//hand*5=+card=0*5+1=1,从第二张牌开始抽取,看是否与第一次抽取的牌,flushSuit,花色是否相同
if (playDeck.GetCard(hand*5+card).suit!=flushSuit)
{
isFlush = false;
break;
}
}
因为是5张牌要连续抽取,且需要同花色,于是如果有一张不是同花色,就可以跳出此循环, 不然循环次数为36次,使用break后最多十几次循环。 CLassLib.dll中的类图: ![]() 关键类Deck:
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++ )
{
//举例:suitVal=0,rankVal=1;cards[0*13+1-1]=cards[0],new Card((Suit)0,(Rank)1).
//枚举默认值为0,所以Suit从0开始,Rank默认值设定为1
cards[suitVal * 13 + rankVal - 1] = 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, "值必须在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);
}
}
|