Я ищу простой способ перемешать колоду карт. Я закончил колоду, какой простой способ создать функцию, которая перемешивает 52 карты? Я не ищу сложные способы перемешивания, я предпочитаю код, который я могу легко прочитать. Я пытался поместить rand () в часть cout
, но он просто случайным образом выбирает и масти, и лица, и я получаю неправильные карты.
struct Card
{
int value;
char suit;
};
Card cards[52]; //global variables
int main()
{
int play;
shuffleDeck();
cout << endl<<endl;
cout << "---------------------------" << endl;
cout << "|Welcome to The Game Of 31| " << endl;
cout << "---------------------------" << endl;
cout << "Would you like to play? (1 for 'YES', 0 for 'NO'): ";
cin >> play;
if (play == 1) { shuffleDeck(); }
else { cout << "See yaa!"; exit(0); }
}
void shuffleDeck() {
for (int i = 0; i < 52; i++)
{
cards[i].value = i % 13; // 13 values
if (cards[i].value == 0) {
cards[i].value = 1;
}
else if (cards[i].value == 1) {
cards[i].value = 2;
}
else if (cards[i].value == 2) {
cards[i].value = 3;
}
else if (cards[i].value == 3) {
cards[i].value = 4;
}
else if (cards[i].value == 4) {
cards[i].value = 5;
}
else if (cards[i].value == 5) {
cards[i].value = 6;
}
else if (cards[i].value == 6) {
cards[i].value = 7;
}
else if (cards[i].value == 7) {
cards[i].value = 8;
}
else if (cards[i].value == 8) {
cards[i].value = 9;
}
else if (cards[i].value == 9) {
cards[i].value = 10;
}
else if (cards[i].value == 10) {
cards[i].value = 10;
}
else if (cards[i].value == 11) {
cards[i].value = 10;
}
else if (cards[i].value == 12) {
cards[i].value = 10;
}
cards[i].suit = i / 13;// 4 suits
if (cards[i].suit == 0) {
cards[i].suit = 'D';
}
else if (cards[i].suit == 1) {
cards[i].suit = 'H';
}
else if (cards[i].suit == 2) {
cards[i].suit = 'C';
}
else if (cards[i].suit == 3) {
cards[i].suit = 'S';
}
}
for (int count = 0; count < 52; count++) {
int count2 = 0;
cout << " | " << cards[count].value;
cout << cards[count].suit << " | ";
if (count == 13) { cout << endl; }
else if (count == 26) { cout << endl; }
else if (count == 39) { cout << endl; }
else if (count == 52) { cout << endl; }
}
}
Редактировать:
void shuffleDeck() {
theDeck();
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(cards, cards + 52, g);
for (int count = 0; count < 52; count++) {
int count2 = 0;
cout << " | " << cards[count].value;
cout << cards[count].suit << " | ";
if (count == 13) { cout << endl; }
else if (count == 26) { cout << endl; }
else if (count == 39) { cout << endl; }
else if (count == 52) { cout << endl; }
}