gpt4 book ai didi

C++ 纸牌洗牌函数

转载 作者:太空狗 更新时间:2023-10-29 23:50:44 25 4
gpt4 key购买 nike

我正在尝试使用 C++ 构建扑克游戏。甲板洗牌功能给我带来了一些问题。每次我运行初始化牌组、洗牌、然后打印牌组的程序时,我都会得到相同的输出:

Shuffling the cards and dealing...
Printing deck...
KD
6S
7D
QD
5C
JH
9S
6D
7H
JD
QH
3C
7S
3H
TC
5D
5S
3D
AD
7C
4H
6H
JC
TS
4D
JS
QC
AH
9C
2D
5H
8C
TD
4S
2S
KS
2C
8D
KC
2H
9H
6C
KH
3S
QS
8S
8H
4C
AS
AC
9D
TH

使用 Deck 和 Card 类,我定义了如下相关函数:

Deck::Deck(){
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 13; j++) {
cards[i * 13 + j].suit = i;
cards[i * 13 + j].rank = j;
}
}
Card::suits[0] = "D";
Card::suits[1] = "S";
Card::suits[2] = "H";
Card::suits[3] = "C";
Card::ranks[0] = "2";
Card::ranks[1] = "3";
Card::ranks[2] = "4";
Card::ranks[3] = "5";
Card::ranks[4] = "6";
Card::ranks[5] = "7";
Card::ranks[6] = "8";
Card::ranks[7] = "9";
Card::ranks[8] = "T";
Card::ranks[9] = "J";
Card::ranks[10] = "Q";
Card::ranks[11] = "K";
Card::ranks[12] = "A";
}

void Deck::print(){
cout << "Printing deck..." << std::endl;
for (int i = 0; i < 52; i++) {
cout << Card::ranks[cards[i].rank] << Card::suits[cards[i].suit] << endl;
}
cout << endl;
}

void Deck::shuffle(){
top = 51;
int x;
Card tempCard;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 13; j++) {
cards[i * 13 + j].suit = i;
cards[i * 13 + j].rank = j;
}
}
cout << "Shuffling the cards and dealing..." << endl;
for (int i = 0; i < 52; i++) {
x = rand() % 52;
tempCard = cards[i];
cards[i] = cards[x];
cards[x] = tempCard;
}
}

我做错了什么吗?为什么我总是得到相同的结果,而它应该是随机的?谢谢。

最佳答案

假设您可以使用 C++11 功能,您可以使用这个(取自 https://stackoverflow.com/a/19728404/341065):

#include <random>

std::random_device rd; // only used once to initialise engine
std::mt19937 rng(rd); // random-number engine used
std::uniform_int_distribution<int> uni(min,max); // guaranteed unbiased

auto random_integer = uni(rng);

关于C++ 纸牌洗牌函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27759506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com