繁体   English   中英

C ++ random_shuffle()表现不正常

[英]C++ random_shuffle() not behaving properly

我有一个二十一点程序,它使用一个完整的向量来模拟卡片组:

vector<short int> deck;

用1-10填充它:

for (int i=0; i<=4; ++i) // Populate the deck with 1-10
{
    for (int c=1; c<=10;++c)
    {
        deck.push_back(c);
    }
}
for (i=0; i<=12;++i)
{
    deck.push_back(10); // Face cards
}

然后播种随机数发生器:

srand(time(0)+1);

并试图用random_shuffle(deckofcards.begin(), deckofcards.end()); 但是,当用户决定点击时,他们发出的牌是整个游戏的精确相同,这里是一些示例输出:

Dealer: I'm gonna play it safe
Dealer bets $42
Dealing cards...
Dealer lays down a 5
You have a 3, and a 10 and your total is 13
Stand, or hit? Stand, or hit? hit
You have been dealt an Ace, your hand is soft, and your total is now 14
Stand, or hit? hit
You have been dealt an Ace, your hand is soft, and your total is now 15
Stand, or hit? hit
You have been dealt an Ace, your hand is soft, and your total is now 16
Stand, or hit? hit
You have been dealt an Ace, your hand is soft, and your total is now 17
Stand, or hit? hit
You have been dealt an Ace, your hand is soft, and your total is now 18
Stand, or hit? hit
You have been dealt an Ace, your hand is soft, and your total is now 19
Dealer calls stand
The dealer has a 3, a 10, an Ace , an Ace , an Ace , an Ace , an Ace , an Ace    for      total of 17, you have a 3, a 10, an Ace , an Ace , an Ace , an Ace , an Ace , an         Ace  you win 1042!

如果有帮助,这里是用户输入hit的代码:

playerhand.push_back(deck.front());
ptotal+=playerhand.back();
if (playerhand.back()!=1)
cout << "You have been dealt a "<<playerhand.back()<<", your total is now"<<ptotal<<endl;
else
    cout << "You have been dealt an Ace, your hand is soft, and your total is now "<<ptotal<<endl;
dealerhand.push_back(deck.front());
dtotal+=dealerhand.back();

但是,此代码有效,但可以处理两张卡:

cout << "Dealing cards...\n";
playerhand.clear();
dealerhand.clear();
playerhand.push_back(deck.back());
deck.pop_back();
dealerhand.push_back(deck.back());
deck.pop_back();
if (dealerhand.back()==1)
    dhsoft=true;
else
    dhsoft=false;
if (playerhand.back()==1)
{
    phsoft=true;
    cout << "Your hand is soft\n";
}
else
    phsoft=false;
playerhand.push_back(deck.back());
deck.pop_back();
dealerhand.push_back(deck.back());
deck.pop_back();
if (dealerhand.back()==1)
    dhsoft=true;
else
    dhsoft=false;
if (playerhand.back()==1)
{
    cout << "Your hand is soft\n";
    phsoft=true;
}
else
    phsoft=false;
unsigned int i;
for (i=0;i<=dealerhand.size()-1; ++i)
    dtotal+=dealerhand[i];
for (i=0;i<=playerhand.size()-1; ++i)
    ptotal+=playerhand[i];

那么,为什么上面的代码工作,但是当用户键入“命中”不起作用时呢? 而且,更重要的是,我该如何解决它(没有代码!)?

它一次又一次地返回同一张卡片的原因是deck.front()只返回对前面元素的引用,它不会删除它。 但由于vector没有方便的方法来实际删除前面的元素,我建议只删除后面的元素:

playerhand.push_back(deck.back());
deck.pop_back();

无论如何,套牌是随机的,无论你处理哪种方式都无关紧要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM