You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++简单卡牌游戏如何正确比较卡牌大小判定胜负

你直接比较字符串会出错是因为C++的字符串比较是逐位对比ASCII码值,比如牌面为10的字符串首字符是1,ASCII码值比2小,就会出现10的牌判定比2弱的错误,完全不符合你的强度规则。
要通过下标判定胜负,推荐两种实现方式:

方案1:修改抽卡逻辑直接返回下标(最高效,推荐)

你原来的抽卡函数只返回卡牌字符串,丢失了下标信息,直接改抽卡逻辑返回下标,需要展示卡牌时再从数组取对应字符串即可,修改后的完整代码如下:

#include <iostream>
#include <array>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

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" };

// 抽卡直接返回下标
int draw_card_index() {
    return rand() % 52;
}

int main()
{
    srand((unsigned int)time(NULL));
    int your_score{ 0 };
    int the_computers_score{ 0 };

    int your_index = draw_card_index();
    string you_drew = cards[your_index];
    cout << "You drew: " << you_drew << endl;

    int comp_index = draw_card_index();
    string comp_drew = cards[comp_index];
    cout << "The computer drew: " << comp_drew << endl;

    // 直接比较下标判定胜负
    if (your_index > comp_index) {
        cout << "You Won!" << endl;
        your_score++;
    } else if (your_index < comp_index) {
        cout << "You Lost.." << endl;
        the_computers_score++;
    } else {
        cout << "Draw!" << endl;
    }

    return 0;
}

方案2:保留原抽卡逻辑,新增查找下标的工具函数

如果你不想改动已有的draw_card函数定义,可以新增一个工具函数传入卡牌字符串返回对应下标:

// 传入卡牌字符串查找对应下标,cards数组需要定义为全局或作为参数传入
int get_card_index(string card) {
    for (int i = 0; i < 52; i++) {
        if (cards[i] == card) {
            return i;
        }
    }
    return -1; // 异常情况,正常抽卡不会触发
}

之后在胜负判定前先获取两张卡牌的下标再比较即可:

int your_index = get_card_index(you_drew);
int comp_index = get_card_index(comp_drew);

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

内容的提问来源于stack exchange,提问作者gunnar20008

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 02:15:02