0

我正在尝试模拟一副牌,但我不知道如何制作它,所以它随机选择一张牌,但只有一次。我不断得到双倍牌。

#include <iostream>
#include <cstdlib> //for rand and srand
#include <cstdio>
#include <string>

using namespace std;

string suit[] = { "Diamonds", "Hearts", "Spades", "Clubs" };
string facevalue[] = { "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
        "Nine", "Ten", "Jack", "Queen", "King", "Ace" };

string getcard() {
    string card;
    int cardvalue = rand() % 13;
    int cardsuit = rand() % 4;

    card += facevalue[cardvalue];
    card += " of ";
    card += suit[cardsuit];

    return card;
}

int main() {
    int numberofcards = 52;

    for (int i = 0; i < numberofcards; i++) {
        cout << "You drew a " << getcard() << endl;
    }

    system("pause");
}

有什么建议么?

4

3 回答 3

4

它是一副纸牌。只需这样做:

  1. 初始化卡组。将所有 52 张卡片布置在一个固定的 52 张卡片阵列中。
  2. 洗牌。
  3. nextCard通过从零 (0) 开始将索引初始化到您的牌组来开始绘图循环。每次“抽牌”(在 处的牌deck[nextCard])前进nextCard一。当nextCard== 52 时,你就没有牌了。

以下是如何设置甲板的示例。我把nextCard索引和绘图算法留给你。

#include <iostream>
#include <algorithm>
using namespace std;

// names of ranks.
static const char *ranks[] =
{
    "Ace", "Two", "Three", "Four", "Five", "Six", "Seven",
    "Eight", "Nine", "Ten", "Jack", "Queen", "King"
};

// name of suites
static const char *suits[] =
{
    "Spades", "Clubs", "Diamonds", "Hearts"
};

void print_card(int n)
{
    cout << ranks[n % 13] << " of " << suits[n / 13] << endl;
}

int main()
{
    srand((unsigned int)time(NULL));

    int deck[52];

    // Prime, shuffle, dump
    for (int i=0;i<52;deck[i++]=i);
    random_shuffle(deck, deck+52);
    for_each(deck, deck+52, print_card);

    return 0;
}

甲板转储的示例如下:

Seven of Diamonds
Five of Hearts
Nine of Diamonds
Ten of Diamonds
Three of Diamonds
Seven of Clubs
King of Clubs
Five of Diamonds
Ace of Spades
Four of Spades
Two of Diamonds
Five of Clubs
Queen of Diamonds
Six of Spades
Three of Hearts
Ten of Spades
Two of Clubs
Ace of Hearts
Four of Hearts
Four of Diamonds
Ace of Diamonds
Six of Diamonds
Jack of Clubs
King of Spades
Jack of Diamonds
Four of Clubs
Eight of Diamonds
Queen of Hearts
King of Hearts
Ace of Clubs
Three of Spades
Two of Spades
Six of Clubs
Seven of Hearts
Nine of Clubs
Jack of Hearts
Nine of Hearts
Eight of Clubs
Ten of Clubs
Five of Spades
Three of Clubs
Queen of Clubs
Seven of Spades
Eight of Spades
Ten of Hearts
King of Diamonds
Jack of Spades
Six of Hearts
Queen of Spades
Nine of Spades
Two of Hearts
Eight of Hearts
于 2012-11-06T18:37:27.100 回答
2

您将需要模拟一副卡片,以便在选择卡片时将其从卡片列表中删除。

所以发生的情况是,您从一副完整的牌开始,然后当您从列表中随机选择一张牌时,您会将其从列表中删除。

于 2012-11-06T18:30:23.707 回答
0

您正在采样替换,这意味着一旦您选择了一张卡片,您就会将其留在牌组中。通过将其从数据结构中删除来将其从甲板上移除。您需要相应地调整随机采样,方法是根据数组/向量的长度/任何变化来更改cardvalue和范围。cardsuit

于 2012-11-06T18:30:24.043 回答