我正在设计一个扑克游戏。将为用户拥有的扑克牌开设一个PokerHand类(总共5张牌)。 PokerHand有不同的类别,例如直管,同花,满座等
现在,我希望所有PokerHand都具有可比性。类别之间有明确的顺序:同花> 4种>满屋> ...对于每个类别,都有一个不同的比较规则。例如。对于直觉,高牌决定。对于“ 4种”,由4张相同的牌决定。
class PokerHand {
public:
int CompareTo(const PokerHand* another) = 0;
Category GetCagegory();
...
}
使用RTTI,我可以将CompareTo实现为
class Straight : public PokerHand {
...
}
int Straight::CompareTo(const PokerHand& another) OVERRIDE {
const Straight* s = dynamic_cast<const Straight*>(another);
if (s == NULL) {
// Not a straight. Compare category.
...
} else {
// compare high card
...
}
}
现在,我的问题是,考虑到RTTI通常被视为“不建议使用”,是否有一种不使用RTTI进行比较的好方法?
最佳答案
我很确定您的处理方式是错误的。PokerHand
是PokerHand
,无论它容纳满屋,同花顺还是一组完全没用的牌。 [[您可能发现,如果您用五张牌,七张牌玩扑克,或者显示或不显示自己的牌是什么,等等,但是-为了评估您的手的“价值”,您需要一种。类]。
您需要的是一个可以告诉您实际拥有的功能的函数。为此,我假设您有一个包含以下内容的struct Card
:
struct Card
{
int suite; (1..4)
int value; (2..14)
};
然后,我假设我们正在玩5张纸牌,如果您正在玩可变数量的纸牌,那么您可能想使用向量。
class PokerHand
{
...
Card cards[5];
}
int PokerHand::value()
// return 0 for "useless, nothing", otherwise how good -> better is higher
{
int ret = 0;
... check if they are the same suite (flush)
... if so, are they in sequence (straight flush)
... if so, is the highest a king - (royal straight flush)
return ret;
else
... here we write code to check how many cards have the same value
(2, 3, 4 of a kind or full house)
if at least two same value:
return ret;
return ret;
}
您可能会发现,如果您分别为这两个步骤按套件或按值对手进行排序,则编写此功能会更容易。您需要考虑卡的价值,例如3个ace击败3个国王击败3个女王,依此类推。您还必须处理“同等价值,更好的套装”类型的情况,例如3张国王,并使用剩余卡片的价值(例如,某张3张拥有两张“未使用的卡片”)来确定最高价值。
这里列出了一些规则:
http://en.wikipedia.org/wiki/List_of_poker_hands