我正在尝试模拟一副纸牌,但我不知道如何制作,因此它随机选择一张纸牌,但只能选择一次。我不断得到双打牌。

#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");
}


有什么建议么?

最佳答案

它是一副扑克牌。只是这样做:


初始化卡座。将所有52张卡布置在固定的52张卡中。
洗净甲板。
通过在甲板上初始化一个从零(0)开始的nextCard索引来开始绘制循环。每进行一次“抽奖”(卡在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

10-08 09:04