编写一个c++程序,设计一个扑克类card和测试程序,实现一副扑克牌的发牌
时间: 2024-10-25 07:08:07 浏览: 21
在C++中,我们可以创建一个名为`Card`的类来表示扑克牌,并在另一个`Deck`类中管理整副牌。这里是一个简单的实现:
```cpp
#include <iostream>
#include <vector>
#include <string>
// 定义扑克牌的花色和数值
enum Suit { SPADES, HEARTS, DIAMONDS, CLUBS };
enum Rank { ACE = 1, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING };
// 卡片类
class Card {
public:
Card(Suit suit, Rank rank) : suit_(suit), rank_(rank) {}
std::string toString() const {
switch (rank_) {
case ACE: return "A";
// ...处理剩余的牌面
default: return to_string(rank_);
}
}
private:
Suit suit_;
Rank rank_;
};
// 扑克牌堆类
class Deck {
public:
void shuffle() {
// 使用Fisher-Yates算法或其他随机化方法打乱牌序
for (size_t i = deck_.size(); i > 0; --i) {
size_t j = rand() % i; // 生成[0, i-1]范围内的随机数
std::swap(deck_[i - 1], deck_[j]);
}
}
Card dealCard() {
if (deck_.empty()) {
throw std::runtime_error("No more cards in the deck.");
}
Card card = deck_.front();
deck_.pop_front();
return card;
}
private:
std::vector<Card> deck_;
};
int main() {
Deck deck;
for (Suit s : {SPADES, HEARTS, DIAMONDS, CLUBS}) {
for (Rank r : {ACE, TWO, ..., KING}) {
deck.addCard(s, r);
}
}
deck.shuffle();
while (!deck.isEmpty()) {
try {
Card card = deck.dealCard();
std::cout << "Dealing card: " << card.toString() << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}
return 0;
}
阅读全文