C ++ BlackJack试图编程Ace

时间:2017-10-15 08:01:06

标签: c++ oop blackjack

我必须为C ++课程的介绍编写一个简单的二十一点游戏,老师希望我们构建套牌的方式让我感到困惑的是如何编程Ace以自动选择是否为值11或1。

从阅读其他可能的解决方案,一直存在相互矛盾的想法,首先将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?他几乎没有过去创造一个朋友&#34;最后一堂课。我应该在deck中创建一个友元函数,将数组中Ace的值更改为1?如果我没有意义,我的大脑会痛,道歉。

1 个答案:

答案 0 :(得分:0)

您可以双向实施。

要稍后添加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;
}