数组,比较数组的两个元素,简单的纸牌游戏,c++



简而言之,我正在制作一个简单的游戏。

从牌组中抽一张牌,选出一名获胜者。

如果玩家抽到一张更高的牌,他就会赢得一张更有力的牌。如果计算机抽到一张更高的牌,则计算机获胜。

牌的力量从王牌(最弱(开始,然后是1强、2强、3强等王最强。如果玩家抽到一张王牌,而电脑抽到一个国王,玩家就输了。

牌从最弱的,王牌,到最强的国王,排列在阵列中。一场纸牌游戏总共有52张牌。

数组如下所示。从王牌到王者。

array<string, 52> cards = { "ace 3", "ace 4", "ace 5", "ace 6","2 3","2 4","2 5","2 6","3 3","3 4","3 5","3 6","4 3","4 4","4 5","4 6","5 3","5 4","5 5","5 6","6 3","6 4","6 5","6 6","7 3","7 4","7 5","7 6","8 3","8 4","8 5","8 6","9 3","9 4","9 5","9 6","10 3","10 4","10 5","10 6","Jacks 3","Jacks 4","Jacks 5","Jacks 6","Queen 3","Queen 4","Queen 5","Queen 6","King 3","King 4","King 5","King 6" };

The function.
string draw_card() {
int random_index = rand() % 52;
string card = cards[random_index];
return card;
}
int main()
{
srand ( (unsigned int)time(NULL) );
string you_drew = draw_card();                          // calling the function and storing the card in the variable you_drew
cout << "You drew: " << you_drew << endl;
string comp_drew = draw_card();
cout << "The computer drew: " << comp_drew << endl;     // calling the function and storing the card in the variable computer_drew

到目前为止,这是正确的。

现在是我的问题。。

我想决定一个胜利者。拥有最强力牌的人应该会赢,我想不通。。。

目前,决定获胜者的过程是这样的。

int your_score{ 0 };
int the_computers_score{ 0 };

if (you_drew > comp_drew) {
cout << "You Won!" << endl;
your_score++;
}
else if (comp_drew > you_drew) {
cout << "You Lost.." << endl;
the_computers_score++;
}

return 0;
}

它几乎总是宣布错误的获胜者,程序不起作用。。我的比较方式,决定一个赢家是行不通的。如何决定获胜者?

我想我必须将数组中的元素相互比较。。。更远的元素应该是最强大的。我该怎么做?

数组元素中的值和卡片正确存储在变量you_drewcomp_drew中但比较这两个变量来决定赢家对我来说不起作用。

you_drew和comp_drew是字符串。通过">quot;或者任何其他比较运算符将简单地通过字符串的大小来比较字符串。

在字符串数组中,字符串的形式为";ace"3";,我不明白。如果3是数组的值,您可以这样做:

if(you_drew.back() > comp_drew.back())
{
cout << "You Won!" << endl;
}

.back((将返回字符串中的最后一个字符。您可以将它们转换为整数,但没有必要,因为这些值都是一位数。

另一方面,如果卡的值只是由它在阵列中的距离决定的,那么你可以这样做:

pair<string, int> draw_card()
{
int random_index = rand() % 52;
string card = cards[random_index];
return { card, random_index };
}

pair<string, int> you_drew = draw_card();
cout << "You drew: " << you_drew.first << endl;
...
if (you_drew.second > comp_drew.second)
cout << "You Won!" << endl;

在这种情况下,您返回卡片的索引,返回字符串和索引,然后数组中索引最高的卡片获胜。

相关内容

  • 没有找到相关文章

最新更新