使用vector,创建Poker类,并创建出54张牌。随机分3个人的牌,每人17张。
时间: 2024-09-26 20:04:44 浏览: 31
首先,我们假设你需要创建一个扑克牌游戏中的`PokerCard`类,它包含卡的花色(Suit)和点数(Rank)。然后我们可以使用`std::vector`来存储所有牌,并将其分为三组代表三位玩家的牌。
```cpp
#include <iostream>
#include <vector>
#include <random> // 需要随机库
// 定义扑克牌类
class PokerCard {
public:
enum Rank {Ace = 1, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King};
enum Suit {Hearts, Diamonds, Clubs, Spades};
PokerCard(Rank rank, Suit suit) : rank(rank), suit(suit) {}
// 显示牌的信息
void display() const {
switch (rank) {
case Ace:
std::cout << "A of ";
break;
default:
std::cout << rank << " of ";
}
switch (suit) {
case Hearts: std::cout << "Hearts"; break;
case Diamonds: std::cout << "Diamonds"; break;
case Clubs: std::cout << "Clubs"; break;
case Spades: std::cout << "Spades"; break;
}
std::cout << "\n";
}
private:
Rank rank;
Suit suit;
};
// 创建扑克牌容器并随机分配给玩家
int main() {
const int total_cards = 52; // 一副扑克牌去掉大小王
const int players = 3;
const int cards_per_player = 17;
std::vector<PokerCard> deck(total_cards);
for (int i = 0; i < total_cards; ++i) {
deck[i] = {static_cast<PokerCard::Rank>(i % 13 + 1), static_cast<PokerCard::Suit>((i / 13) % 4)};
}
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(deck.begin(), deck.end(), g);
std::vector<std::vector<PokerCard>> players_deck(players);
for (size_t i = 0; i < players * cards_per_player; ++i) {
players_deck[i / cards_per_player].push_back(deck[i]);
}
for (int player = 0; player < players; ++player) {
std::cout << "Player " << player + 1 << ":\n";
for (const auto& card : players_deck[player]) {
card.display();
}
std::cout << "\n";
}
return 0;
}
```
在这个示例中,我们首先创建了一个52张牌的`deck`,然后通过随机排序将它们分配给三个玩家,每个人17张。每张牌都有一个`display()`函数来展示其花色和点数。
阅读全文