gpt4 book ai didi

C++ random_shuffle() 行为不正常

转载 作者:太空狗 更新时间:2023-10-29 21:02:17 25 4
gpt4 key购买 nike

我有一个 Blackjack 程序,它使用一个充满整数的 vector 来模拟一副纸牌:

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];

那么,为什么上面的代码可以工作,而当用户键入“hit”时却不能工作?而且,更重要的是,我该如何修复它(没有代码!)?

最佳答案

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

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

无论如何,套牌都是随机的,与您处理的方式无关。

关于C++ random_shuffle() 行为不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15856180/

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