首页 > 解决方案 > 数组,比较数组的两个元素,简单的纸牌游戏,c++

问题描述

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

从牌堆中抽一张牌并决定获胜者。

如果玩家抽到一张更高的牌,他就赢了一张更强大的牌。如果计算机抽到更高的牌,则计算机获胜。

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

卡片从最弱的王牌到最强的国王堆叠在数组中。总共 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 中。 但是比较这两个变量来决定一个赢家对我不起作用..

标签: c++arrayscompareelement

解决方案


you_drew 和 comp_drew 是字符串。通过“>”或任何其他比较运算符比较字符串只会按字符串的大小比较字符串。

在您的字符串数组中,您有“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;

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


推荐阅读