C++ BlackJack Stuck试图编程王牌
问题描述:
我必须编程一个简单的二十一点游戏为我的介绍C++类和老师希望我们建立甲板的方式让我感到困惑与我如何编程的Ace自动选择不管是否为11或1的值。C++ BlackJack Stuck试图编程王牌
从阅读其他可能的解决方案,出现了相互冲突的想法,首先将ace的值设置为11,如果你破产,则减去10(教授如何选择),但大多数我看到说,将值设置为1,如果需要添加10。
下面是他如何希望我们建立我们的卡和甲板类:
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
using namespace std;
class card
{
string rank;
string suit;
int value;
public:
string get_rank()
{
return rank;
}
string get_suit()
{
return suit;
}
int get_value()
{
return value;
}
//Contstructor
card(string rk = " ", string st = " ", int val = 0)
{
rank = rk;
suit = st;
value = val;
}
//print function
void print()
{
cout << rank << " of " << suit << endl;
}
};
class deck
{
card a_deck[52];
int top;
public:
card deal_card()
{
return a_deck[top++];
}
//Deck constructor
deck()
{
top = 0;
string ranks[13] = { "Ace", "King", "Queen", "Jack", "Ten", "Nine",
"Eight", "Seven", "Six", "Five", "Four", "Three", "Two" };
string suits[4] = { "Spades", "Diamonds", "Hearts", "Clubs" };
int values[13] = { 11,10,10,10,10,9,8,7,6,5,4,3,2 };
for (int i = 0; i < 52; i++)
a_deck[i] = card(ranks[i % 13], suits[i % 4], values[i % 13]);
srand(static_cast<size_t> (time(nullptr)));
}
void shuffle()
{
for (int i = 0; i < 52; i++)
{
int j = rand() % 52;
card temp = a_deck[i];
a_deck[i] = a_deck[j];
a_deck[j] = temp;
}
}
};
然后,他把我们创造一个我们所建立的手放进载体的播放器类
class player
{
string name;
vector<card>hand;
double cash;
double bet;
public:
//Constructor
player(double the_cash)
{
cash = the_cash;
bet = 0;
}
void hit(card c)
{
hand.push_back(c);
}
int total_hand()
{
int count = 0;
for (int i = 0; i < hand.size(); i++)
{
card c = hand[i];
count = count + c.get_value();
}
return count;
}
};
如何我会去编码Ace吗?他几乎没有去创造一个“朋友”最后一堂课。我应该在甲板内创建一个将数组中的Ace值改为1的朋友函数吗?如果我没有道理,我的大脑会受到伤害,道歉。
答
您可以通过两种方式实施。
要添加10后,你可以改变你的total_hand()函数成为:
int total_hand
{
int count = 0;
int num_of_aces = 0;
for (int i = 0; i < hand.size(); i++)
{
card c = hand[i];
if (c.get_value() == 11){
num_of_aces += 1;
count += 1;
}
else
count = count + c.get_value();
}
for (int i = 0; i < num_of_aces; i++){
if (count + 10 <= 21)
count += 10;
return count;
}
要减去10后(如你的直觉建议),你可以做到以下几点:
int total_hand
{
int count = 0;
int num_of_aces = 0;
for (int i = 0; i < hand.size(); i++)
{
card c = hand[i];
if (c.get_value() == 11)
num_of_aces += 1;
count = count + c.get_value();
}
while(count > 21 && num_of_aces--)
count -=10;
return count;
}
+0
“添加10”的情况可以变得更简单和更快,因为没有必要数一数。只要保持一个标志,不管是否已经看到任何王牌,并且如果总数小于12,则只添加10次,而不是循环。 –
*我如何去编码Ace?* - 听说过if-else语句?您发布的所有代码都无法在任何地方使用,这可能是您如何根据特定场景编码具有两个值之一的特殊卡的方式。 – PaulMcKenzie