【发布时间】:2018-03-26 22:48:49
【问题描述】:
我必须为我的 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 代码?上节课他只是勉强创建了一个“朋友”。我应该在deck 中创建一个将数组中Ace 的值更改为1 的友元函数吗?我的脑子很痛,如果我说得不好,请道歉。
【问题讨论】:
-
我将如何编写 Ace 代码? -- 听说过
if-else语句吗?您发布的整套代码在任何地方都没有使用它,这可能就是您编写一张特殊卡片的方式,该卡片根据特定场景具有两个值之一。