【发布时间】:2015-03-01 19:24:48
【问题描述】:
我正在尝试使用 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/c++ 程序,它会执行 cout
-
我认为你是最近几天出现的第 5 个与 C++ 和扑克有关的问题的家伙。这是学校的工作吗?
标签: c++ class random playing-cards