我正在设计一款扑克游戏。将有一个 PokerHand 类用于用户拥有的牌(总是 5 张牌)。 PokerHand 有不同的类别,例如顺子、同花、满堂等
现在我希望所有 PokerHand 都具有可比性。类别之间有一个明确的顺序:同花顺 > 同花顺 > 葫芦 > ... 对于每个类别,都有一个不同的比较规则。例如。对于顺子,高牌决定。对于“4 of a kind”,由 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
,无论它持有葫芦、同花顺还是一组完全无用的牌。 [如果你用五张牌、七张牌玩扑克,或者展示或不展示你的牌是什么等等,你可能会发现你需要有几种——但是为了评估你的手牌“值多少钱”,你需要一种类(class)]。
你需要的是一个可以告诉你实际拥有什么的函数。为此,我假设您有一个包含以下内容的 struct Card
:
struct Card
{
int suite; (1..4)
int value; (2..14)
};
然后我假设我们正在玩 5 张牌,如果您正在玩可变数量的牌,那么您可能想要使用 vector 。
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;
}
您可能会发现,如果您对这两个步骤分别按组或按值对手牌进行排序,则编写此函数会更容易。您需要考虑卡片的值(value),例如3 个 A 击败 3 个 K 击败 3 个 Q,等等。您还必须处理“同等值(value),更好的套房”类型的情况,例如3张K,并使用剩余牌的值(value)(例如3张有两张“未使用的牌”)来确定最高值(value)。
关于c++ - 比较没有 RTTI 的抽象类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16009175/