我的代码已经构成了纸牌,但是我该如何洗牌呢?我的随机播放功能似乎无法正常工作。
我可能在其他地方也有一些错误,如果您可以看到它们,请告诉我。它可以编译并运行,但会按顺序列出卡。
#include <iostream>
#include <string>
#include <ctime>
#include <vector>
using namespace std;
class Card{
public:
int face;
int suit;
void setData(int f, int s){
face = f;
suit = s;
}
string toString(int F, int S){
static string faces[13] = {"Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"};
static string suits[4] = {"Clubs", "Spades", "Diamonds", "Hearts"};
string FandS = faces[F] + " of " + suits[S] + "\n";
return FandS;
}
};
class DeckOfCards:public Card{
public:
Card deck[13][4];
int currentCard;
void shuffle(){
srand (time(0));
Card temp[13][4]; int R, r;
for(int shuf=0; shuf<52; shuf++){
for(int i=0; i<13; i++){
for(int j=0; j<4; j++){
R = rand()%13;
r = rand()%4;
temp[i][j] = deck[i][j];
deck[i][j] = deck[R][r];
deck[R][r] = temp[i][j];
}
}
}
}
bool moreCards(){
currentCard=52;
currentCard--;
if(currentCard>0){
return true;
}else
return false;
}
void dealCard(){
for(int i=0; i<13; i++){
for(int j=0; j<4; j++){
cout << toString(i, j);
}
}
}
DeckOfCards(){
for(int i=0; i<13; i++){
for(int j=0; j<4; j++){
deck[i][j].setData(face, suit);
}
}
}
};
int main(){
DeckOfCards myDeck;
myDeck.shuffle();
myDeck.dealCard();
return 0;
}
最佳答案
这就是您的卡片按顺序“降级”的原因:
void dealCard(){
for(int i=0; i<13; i++){
for(int j=0; j<4; j++){
cout << toString(i, j);
}
}
}
您根本不用甲板。您只需按顺序打印它们即可。
尝试这个:
cout << toString(deck[i][j].face, deck[i][j].suit);
您应该真正编写不带参数的
Card::toString
函数,并让其使用其face
和suit
成员。cout << deck[i][j].toString();
作为记录,我真的不喜欢您将卡座安排为2D阵列。绝对没有必要这样做。而且我更喜欢
DeckOfCards
从Card
继承。由于我很挑剔,因此您不需要整个卡座大小的数组作为临时交换变量。您只需要一个
Card
。实际上,您应该改用std::swap
。