我正在尝试用 C# 编写一个扑克牌评估方法。除了顺子之外,我已经成功地为使用 linq 的每一手扑克牌做到了这一点。 对于那些不玩顺子的人来说,顺子由 5 张牌组成,每张牌增加 1 点。 A 可以高也可以低。
我创建了一个名为 card 的对象,它具有花色、等级和值(value)(J = 11,Q = 12 等)。我的方法将传递一个包含 7 张牌(底牌和棋盘)的对象列表。
另一件要记住的事情是,只有当玩家有 5 或 10 时才能形成顺子。
请参阅下面我针对其他扑克手牌的方法,如果您对直接方法有任何想法,请告诉我。伪代码也可以。
public bool CheckPair(List<Card> cards)
{
//see if exactly 2 cards card the same rank.
return cards.GroupBy(card => card.Rank).Count(group => group.Count() == 2) == 1;
}
public bool CheckTwoPair(List<Card> cards)
{
//see if there are 2 lots of exactly 2 cards card the same rank.
return cards.GroupBy(card => card.Rank).Count(group => group.Count() >= 2) == 2;
}
public bool CheckTrips(List<Card> cards)
{
//see if exactly 3 cards card the same rank.
return cards.GroupBy(card => card.Rank).Any(group => group.Count() == 3);
}
public bool CheckStraight(List<Card> cards)
{
// order by decending to see order
var cardsInOrder = cards.OrderByDescending(a => a.Value).ToList();
// check for ace as can be high and low
if (cardsInOrder.First().Rank == "A")
{
// check if straight with ace has has 2 values
bool highStraight = cards.Where(a => a.Rank == "K" || a.Rank == "Q" || a.Rank == "J" || a.Rank == "10").Count() == 4;
bool lowStraight = cards.Where(a => a.Rank == "2" || a.Rank == "3" || a.Rank == "4" || a.Rank == "5").Count() == 4;
// return true if straight with ace
if (lowStraight == true || highStraight == true)
{
return true;
}
}
else
{
// check for straight here
return true;
}
// no straight if reached here.
return false;
}
public bool CheckFlush(List<Card> cards)
{
//see if 5 or more cards card the same rank.
return cards.GroupBy(card => card.Suit).Count(group => group.Count() >= 5) == 1;
}
public bool CheckFullHouse(List<Card> cards)
{
// check if trips and pair is true
return CheckPair(cards) && CheckTrips(cards);
}
public bool CheckQuads(List<Card> cards)
{
//see if exactly 4 cards card the same rank.
return cards.GroupBy(card => card.Rank).Any(group => group.Count() == 4);
}
// need to check same 5 cards
public bool CheckStraightFlush(List<Card> cards)
{
// check if flush and straight are true.
return CheckFlush(cards) && CheckStraight(cards);
}
最佳答案
这可能不是性能最好的检查,但我会说它的可读性很强,这通常是一个很好的属性。
只需抓取 5 张牌,每次迭代时跳过您已经看过的牌,并检查每个序列的顺子。如果有序序列不包含 double 并且第一张和最后一张牌的差值为 5,则它是顺子。
public bool CheckStraight(List<Card> cards)
{
//maybe check 5 and 10 here first for performance
var ordered = cards.OrderByDescending(a => a.Value).ToList();
for(i = 0; i < ordered.Count - 5; i++) {
var skipped = ordered.Skip(i);
var possibleStraight = skipped.Take(5);
if(IsStraight(possibleStraight)) {
return true;
}
}
return false;
}
public bool IsStraight(List<Card> fiveOrderedCards) {
var doubles = cards.GroupBy(card => card.Rank).Count(group => group.Count() > 1);
var inARow = cards[4] - cards[0] = 5; //Ace is 0
return !doubles && inARow;
}
关于c# 直接检查扑克牌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39637965/