C++ BlackJack Stuck 试图对 Ace 进行编程

C++ BlackJack Stuck trying to program Ace

我必须为我的 C++ 入门编写一个简单的 21 点游戏 class 并且老师希望我们搭建牌组的方式让我对我应该如何对 Ace 进行编程以自动选择是否或不是 11 或 1 的值。

从阅读其他可能的解决方案来看,有一些相互矛盾的想法,首先将 A 的值设置为 11,如果你爆牌则减去 10(我的教授希望如何),但我看到的大多数人都说设置该值到 1 并在需要时加 10。

下面是他希望我们如何设置卡片和套牌classes:

#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,我们在其中将手构建成向量

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 代码?他刚刚创建了一个 "friend" 最后一个 class。我应该在 deck 中创建一个 friend 函数,将数组中 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;
}