扑克牌c++

· · 个人记录

#include<bits/stdc++.h>
#define PLAYERCOUNT 3
#define CARDSCOUNT 54
#define CURRENTPLAYER 0
#define VALUECOUNT 17
#define ERROR -1

using namespace std;

const char toFigure[] = "34567890JQKA 2YZ";
const string CARD_NAMES[] = {"3","4","5","6","7","8","9","10","J","Q","K","A","2","小王","大王"};

enum COLOR {
    eHEART = 3,
    eDIAMOND,
    eCLUB,
    eSPADE
};

class Card;
class CardsType;
class CardGroup;
class Player;
class Landlords;
class LastCards;

bool makeChoice(const string& tip);
bool cmp(Card* a, Card* b);
string getColorChar(COLOR color);

class Card {
public:
    char figure;
    COLOR color;
    int value;

    Card(char _figure, COLOR _color) : figure(_figure), color(_color) {
        value = calValue();
    }

    int calValue() const {
        for(int i = 0; toFigure[i]; i++) {
            if(toFigure[i] == figure) {
                return i;
            }
        }
        return ERROR;
    }

    void print() const {
        assert(value != ERROR);
        if(figure == 'Z') {
            cout << "大王";
        } else if(figure == 'Y') {
            cout << "小王";
        } else {
            if(figure == '0') {
                cout << "10";
            } else {
                cout << figure;
            }
            cout << getColorChar(color);
        }
        cout << ' ';
    }
};

class CardsType {
public:
    int typeId;
    string typeStr;
    int cnt1, cnt2;
    bool isContinuous;

    CardsType() : typeId(ERROR), cnt1(0), cnt2(0), isContinuous(false) {}

    bool operator==(const CardsType& other) const {
        return typeId == other.typeId;
    }

    void init(const string& _typeStr, int _typeId, int _cnt1, bool _isContinuous, int _cnt2) {
        typeStr = _typeStr;
        typeId = _typeId;
        cnt1 = _cnt1;
        isContinuous = _isContinuous;
        cnt2 = _cnt2;
    }
};

class CardGroup {
public:
    vector<Card*> cards;
    CardsType type;

    void calType() {
        int n = cards.size();

        if(n == 0) {
            type.init("不出", 14, 0, false, 0);
            return;
        }

        // 王炸
        if(n == 2) {
            bool hasKing = false, hasJoker = false;
            for(auto card : cards) {
                if(card->figure == 'Z') hasKing = true;
                if(card->figure == 'Y') hasJoker = true;
            }
            if(hasKing && hasJoker) {
                type.init("王炸", 0, 0, false, 0);
                return;
            }
        }

        // 统计点数
        int cntFlag[VALUECOUNT] = {0};
        for(auto card : cards) {
            cntFlag[card->value]++;
        }

        // 统计信息
        int maxCnt = 0, minCnt = 4, tripleCount = 0, pairCount = 0;
        int maxValue = -1;
        vector<int> tripleValues, pairValues, singleValues;

        for(int i = 0; i < VALUECOUNT; i++) {
            if(cntFlag[i] > 0) {
                if(cntFlag[i] > maxCnt) {
                    maxCnt = cntFlag[i];
                    maxValue = i;
                }
                if(cntFlag[i] < minCnt) minCnt = cntFlag[i];

                if(cntFlag[i] == 3) {
                    tripleCount++;
                    tripleValues.push_back(i);
                }
                if(cntFlag[i] == 2) pairValues.push_back(i);
                if(cntFlag[i] == 1) singleValues.push_back(i);
            }
        }

        // 炸弹
        if(n == 4 && maxCnt == 4) {
            type.init("炸弹", 1, 4, false, 0);
            return;
        }

        // 单牌
        if(n == 1) {
            type.init("单牌", 2, 1, false, 0);
            return;
        }

        // 对子
        if(n == 2 && maxCnt == 2) {
            type.init("对子", 3, 2, false, 0);
            return;
        }

        // 三张
        if(n == 3 && maxCnt == 3) {
            type.init("三张", 4, 3, false, 0);
            return;
        }

        // 三带一
        if(n == 4 && maxCnt == 3 && minCnt == 1) {
            type.init("三带一", 5, 3, false, 1);
            return;
        }

        // 三带一对
        if(n == 5 && maxCnt == 3 && minCnt == 2) {
            type.init("三带一对", 6, 3, false, 2);
            return;
        }

        // 四带二(单)
        if(n == 6 && maxCnt == 4) {
            type.init("四带二", 7, 4, false, 1);
            return;
        }

        // 四带二(对)
        if(n == 8 && maxCnt == 4) {
            type.init("四带二", 8, 4, false, 2);
            return;
        }

        // 顺子(至少5张连续单牌)
        if(maxCnt == 1 && n >= 5) {
            sort(cards.begin(), cards.end(), cmp);
            bool isStraight = true;
            for(int i = 1; i < n; i++) {
                if(cards[i-1]->value != cards[i]->value + 1) {
                    isStraight = false;
                    break;
                }
            }
            if(isStraight && cards[0]->value <= 12) { // A以下才能组成顺子
                type.init("顺子", 9, 1, true, 0);
                return;
            }
        }

        // 连对(至少3对连续对子)
        if(maxCnt == 2 && n >= 6 && n % 2 == 0) {
            sort(cards.begin(), cards.end(), cmp);
            bool isConsecutivePairs = true;
            for(int i = 0; i < n; i += 2) {
                if(i + 1 < n && cards[i]->value != cards[i+1]->value) {
                    isConsecutivePairs = false;
                    break;
                }
                if(i + 2 < n && cards[i]->value != cards[i+2]->value + 1) {
                    isConsecutivePairs = false;
                    break;
                }
            }
            if(isConsecutivePairs && n/2 >= 3) {
                type.init("连对", 10, 2, true, 0);
                return;
            }
        }

        // 飞机(连续三张)
        if(tripleCount >= 2) {
            sort(tripleValues.begin(), tripleValues.end(), greater<int>());
            bool isConsecutiveTriples = true;
            for(int i = 1; i < tripleCount; i++) {
                if(tripleValues[i-1] != tripleValues[i] + 1) {
                    isConsecutiveTriples = false;
                    break;
                }
            }

            if(isConsecutiveTriples) {
                int expectedSize = tripleCount * 3;
                if(n == expectedSize) {
                    type.init("飞机", 11, 3, true, 0);
                    return;
                } else if(n == expectedSize + tripleCount) {
                    type.init("飞机带单", 12, 3, true, 1);
                    return;
                } else if(n == expectedSize + tripleCount * 2) {
                    type.init("飞机带对", 13, 3, true, 2);
                    return;
                }
            }
        }
    }

    void init(const string& inputStr, vector<Card*>& cardsHolded) {
        cards.clear();

        if(inputStr == "N" || inputStr == "n") {
            calType();
            return;
        }

        // 解析输入
        vector<char> figures;
        for(int i = 0; i < inputStr.size(); i++) {
            if(inputStr[i] == '1' && i+1 < inputStr.size() && inputStr[i+1] == '0') {
                figures.push_back('0');
                i++;
            } else {
                figures.push_back(inputStr[i]);
            }
        }

        // 查找对应牌
        vector<bool> used(cardsHolded.size(), false);
        for(char fig : figures) {
            bool found = false;
            for(int j = 0; j < cardsHolded.size(); j++) {
                if(!used[j] && cardsHolded[j]->figure == fig) {
                    used[j] = true;
                    cards.push_back(cardsHolded[j]);
                    found = true;
                    break;
                }
            }
            if(!found) {
                cout << "错误:您没有牌 " << fig << endl;
                cards.clear();
                return;
            }
        }

        arrange();
    }

    void init(const vector<Card*>& newCards) {
        cards = newCards;
        arrange();
    }

    bool canBeat(const CardGroup& other) const {
        // 空牌不能管牌
        if(type.typeStr == "不出") return false;

        // 王炸最大
        if(type.typeStr == "王炸") return true;
        if(other.type.typeStr == "王炸") return false;

        // 炸弹比较
        if(type.typeStr == "炸弹") {
            if(other.type.typeStr == "炸弹") {
                return getMainValue() > other.getMainValue();
            }
            return true;
        }
        if(other.type.typeStr == "炸弹") return false;

        // 同类型比较
        if(type.typeId == other.type.typeId && cards.size() == other.cards.size()) {
            return getMainValue() > other.getMainValue();
        }

        return false;
    }

    int getMainValue() const {
        // 获取主牌的点数(用于比较大小)
        if(cards.empty()) return 0;

        // 统计点数
        int cntFlag[VALUECOUNT] = {0};
        for(auto card : cards) {
            cntFlag[card->value]++;
        }

        // 找出现次数最多的点数
        int maxCnt = 0, mainValue = 0;
        for(int i = 0; i < VALUECOUNT; i++) {
            if(cntFlag[i] > maxCnt) {
                maxCnt = cntFlag[i];
                mainValue = i;
            }
        }

        return mainValue;
    }

    void arrange() {
        sort(cards.begin(), cards.end(), cmp);
        calType();
    }

    void print() const {
        cout << type.typeStr << ": ";
        for(auto card : cards) {
            card->print();
        }
        cout << endl;
    }

    bool isEmpty() const {
        return cards.empty();
    }
};

class LastCards {
private:
    static LastCards* instance;
    LastCards() : player(nullptr) {}

public:
    Player* player;
    CardGroup cardGroup;

    static LastCards* getInstance() {
        if(!instance) {
            instance = new LastCards();
        }
        return instance;
    }

    void reset() {
        player = nullptr;
        cardGroup.cards.clear();
        cardGroup.calType();
    }

    vector<Card*> findCanBeatFrom(vector<Card*>& cardsHolded) {
        vector<Card*> result;

        // 没有上家牌或上家没出牌
        if(!player || cardGroup.isEmpty()) {
            return result;
        }

        // 王炸无法被击败
        if(cardGroup.type.typeStr == "王炸") {
            return result;
        }

        int n = cardsHolded.size();
        int targetValue = cardGroup.getMainValue();
        int targetSize = cardGroup.cards.size();

        // 先生成所有可能的牌型组合进行测试
        vector<Card*> testCards;

        // 1. 查找炸弹(优先使用)
        if(cardGroup.type.typeStr != "炸弹") {
            vector<int> bombValues;
            for(int i = 0; i < VALUECOUNT; i++) {
                int cnt = 0;
                for(auto card : cardsHolded) {
                    if(card->value == i) cnt++;
                }
                if(cnt >= 4) bombValues.push_back(i);
            }

            if(!bombValues.empty()) {
                // 找到最小的能管上的炸弹
                sort(bombValues.begin(), bombValues.end());
                for(int bombVal : bombValues) {
                    if(bombVal > targetValue || cardGroup.type.typeStr == "炸弹") {
                        result.clear();
                        for(auto card : cardsHolded) {
                            if(card->value == bombVal) {
                                result.push_back(card);
                                if(result.size() == 4) break;
                            }
                        }
                        return result;
                    }
                }
            }
        }

        // 2. 查找同类型更大的牌
        if(cardGroup.type.typeStr != "炸弹" && cardGroup.type.typeStr != "王炸") {
            // 根据牌型查找
            if(cardGroup.type.typeStr == "单牌") {
                for(int i = targetValue + 1; i < VALUECOUNT; i++) {
                    for(auto card : cardsHolded) {
                        if(card->value == i && find(result.begin(), result.end(), card) == result.end()) {
                            result.push_back(card);
                            return result;
                        }
                    }
                }
            }
            else if(cardGroup.type.typeStr == "对子") {
                for(int i = targetValue + 1; i < VALUECOUNT; i++) {
                    result.clear();
                    for(auto card : cardsHolded) {
                        if(card->value == i) {
                            result.push_back(card);
                            if(result.size() == 2) return result;
                        }
                    }
                }
            }
            else if(cardGroup.type.typeStr == "三张") {
                for(int i = targetValue + 1; i < VALUECOUNT; i++) {
                    result.clear();
                    for(auto card : cardsHolded) {
                        if(card->value == i) {
                            result.push_back(card);
                            if(result.size() == 3) return result;
                        }
                    }
                }
            }
            else if(cardGroup.type.typeStr == "三带一") {
                for(int i = targetValue + 1; i < VALUECOUNT; i++) {
                    // 找三张
                    vector<Card*> triple;
                    for(auto card : cardsHolded) {
                        if(card->value == i) {
                            triple.push_back(card);
                            if(triple.size() == 3) break;
                        }
                    }
                    if(triple.size() == 3) {
                        // 找一张单牌
                        for(auto card : cardsHolded) {
                            if(card->value != i && find(triple.begin(), triple.end(), card) == triple.end()) {
                                result = triple;
                                result.push_back(card);
                                return result;
                            }
                        }
                    }
                }
            }
            else if(cardGroup.type.typeStr == "三带一对") {
                for(int i = targetValue + 1; i < VALUECOUNT; i++) {
                    // 找三张
                    vector<Card*> triple;
                    for(auto card : cardsHolded) {
                        if(card->value == i) {
                            triple.push_back(card);
                            if(triple.size() == 3) break;
                        }
                    }
                    if(triple.size() == 3) {
                        // 找一对
                        for(int j = 0; j < VALUECOUNT; j++) {
                            if(j != i) {
                                vector<Card*> pair;
                                for(auto card : cardsHolded) {
                                    if(card->value == j && find(triple.begin(), triple.end(), card) == triple.end()) {
                                        pair.push_back(card);
                                        if(pair.size() == 2) {
                                            result = triple;
                                            result.insert(result.end(), pair.begin(), pair.end());
                                            return result;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else if(cardGroup.type.typeStr == "顺子") {
                int len = targetSize;
                for(int start = targetValue + 1; start + len - 1 < VALUECOUNT; start++) {
                    result.clear();
                    bool canForm = true;
                    for(int k = 0; k < len; k++) {
                        bool found = false;
                        for(auto card : cardsHolded) {
                            if(card->value == start + k && find(result.begin(), result.end(), card) == result.end()) {
                                result.push_back(card);
                                found = true;
                                break;
                            }
                        }
                        if(!found) {
                            canForm = false;
                            break;
                        }
                    }
                    if(canForm && result.size() == len) {
                        return result;
                    }
                }
            }
            else if(cardGroup.type.typeStr == "连对") {
                int len = targetSize / 2;
                for(int start = targetValue + 1; start + len - 1 < VALUECOUNT; start++) {
                    result.clear();
                    bool canForm = true;
                    for(int k = 0; k < len; k++) {
                        int pairCount = 0;
                        for(auto card : cardsHolded) {
                            if(card->value == start + k && find(result.begin(), result.end(), card) == result.end()) {
                                result.push_back(card);
                                pairCount++;
                                if(pairCount == 2) break;
                            }
                        }
                        if(pairCount < 2) {
                            canForm = false;
                            break;
                        }
                    }
                    if(canForm && result.size() == targetSize) {
                        return result;
                    }
                }
            }
        }

        result.clear();
        return result;
    }
};

LastCards* LastCards::instance = nullptr;

class Player {
public:
    string name;
    vector<Card*> cards;

    void arrange() {
        sort(cards.begin(), cards.end(), cmp);
    }

    void print() const {
        cout << name << ":\t";
        if(cards.empty()) {
            cout << "无牌";
        } else {
            for(auto card : cards) {
                card->print();
            }
        }
        cout << "[" << cards.size() << "张]" << endl;
    }

    vector<Card*> tip() {
        // 简单的提示:出最小的单牌
        if(cards.empty()) return vector<Card*>();

        // 尝试出最小的单牌
        Card* minCard = cards.back(); // 已排序,最后一张最小
        return vector<Card*>{minCard};
    }

    void playCards(CardGroup& cardGroup) {
        cout << name << ":\t";
        if(cardGroup.type.typeStr == "不出") {
            cout << "不出" << endl;
        } else {
            cardGroup.print();
            // 移除打出的牌
            for(auto card : cardGroup.cards) {
                auto it = find(cards.begin(), cards.end(), card);
                if(it != cards.end()) {
                    cards.erase(it);
                }
            }
        }
        cout << "\t剩余[" << cards.size() << "张]" << endl;

        // 记录到LastCards
        if(cardGroup.type.typeStr != "不出") {
            LastCards::getInstance()->player = this;
            LastCards::getInstance()->cardGroup.init(cardGroup.cards);
        } else {
            // 不出牌也要记录是谁不出
            LastCards::getInstance()->player = this;
        }
    }

    bool hasCards() const {
        return !cards.empty();
    }
};

class Landlords {
private:
    Player* players[PLAYERCOUNT];
    vector<Card*> allCards;
    bool finished;
    bool youWin;
    int landlordIndex;

public:
    Landlords() {
        for(int i = 0; i < PLAYERCOUNT; i++) {
            players[i] = new Player();
        }

        // 初始化54张牌
        for(int i = 0; i < 15; i++) {
            if(toFigure[i] == ' ') continue;
            if(toFigure[i] == 'Y' || toFigure[i] == 'Z') continue;
            for(COLOR color = eHEART; color <= eSPADE; color = (COLOR)(color + 1)) {
                allCards.push_back(new Card(toFigure[i], color));
            }
        }
        allCards.push_back(new Card('Y', eSPADE));
        allCards.push_back(new Card('Z', eHEART));
    }

    ~Landlords() {
        for(int i = 0; i < PLAYERCOUNT; i++) {
            delete players[i];
        }
        for(auto card : allCards) {
            delete card;
        }
    }

    void init() {
        players[CURRENTPLAYER]->name = "【玩家】";
        players[1]->name = "【电脑A】";
        players[2]->name = "【电脑B】";
        finished = false;
        youWin = false;

        // 抢地主
        landlordIndex = ERROR;
        while(landlordIndex == ERROR) {
            srand(time(nullptr));
            shuffle();
            landlordIndex = chooseLandlord();
        }

        cout << endl << "═══════════════════════════════════════" << endl;
        cout << "  " << players[landlordIndex]->name << " 成为地主!" << endl;
        cout << "═══════════════════════════════════════" << endl << endl;

        addThreeCards();
        LastCards::getInstance()->reset();
    }

    void startGame() {
        string inputStr;
        CardGroup inputCards;
        int turnCount = 0;

        for(int turn = landlordIndex; !finished; turn = (turn + 1) % PLAYERCOUNT, turnCount++) {
            if(turnCount > 100) break; // 防止死循环

            cout << "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" << endl;

            if(turn == CURRENTPLAYER) {
                cout << endl;
                players[turn]->print();
                cout << "\n请出牌(例如:3334 或 10JQKA 或 N): ";

                do {
                    cin >> inputStr;
                    inputCards.init(inputStr, players[turn]->cards);
                    if(inputCards.type.typeStr == "不出") break;
                } while(!isValidPlay(inputCards, turn));
            } else {
                // 电脑出牌

                if(LastCards::getInstance()->player == players[turn]) {
                    // 上次是自己出的,出最小的牌
                    inputCards.init(players[turn]->tip());
                } else {
                    // 尝试管上家
                    auto beatCards = LastCards::getInstance()->findCanBeatFrom(players[turn]->cards);
                    if(beatCards.empty()) {
                        inputCards.init("N", players[turn]->cards);
                    } else {
                        inputCards.init(beatCards);
                    }
                }
            }

            players[turn]->playCards(inputCards);

            // 检查游戏结束
            if(!players[turn]->hasCards()) {
                finished = true;
                bool landlordWin = (turn == landlordIndex);
                youWin = (landlordWin && landlordIndex == CURRENTPLAYER) || 
                        (!landlordWin && landlordIndex != CURRENTPLAYER);
            }
        }

        cout << "\n═══════════════════════════════════════" << endl;
        cout << "          " << (youWin ? "** 恭喜获胜! **" : "** 遗憾落败! **") << endl;
        cout << "═══════════════════════════════════════\n" << endl;
    }

private:
    void addThreeCards() {
        cout << "地主底牌: ";
        for(int i = PLAYERCOUNT * 17; i < CARDSCOUNT; i++) {
            allCards[i]->print();
            players[landlordIndex]->cards.push_back(allCards[i]);
        }
        cout << endl;
        players[landlordIndex]->arrange();
        cout << endl;
    }

    int chooseLandlord() {
        cout << "\n════════════════ 抢地主 ════════════════\n" << endl;

        int first = -1, last = -1, cnt = 0;
        int start = rand() % PLAYERCOUNT;

        for(int i = 0; i < PLAYERCOUNT; i++) {
            int idx = (start + i) % PLAYERCOUNT;
            bool decision;

            if(idx == CURRENTPLAYER) {
                decision = makeChoice(players[idx]->name + " 是否抢地主?(Y/N): ");
            } else {
                decision = (rand() % 2 == 1);
            }

            if(decision) {
                cnt++;
                last = idx;
                if(first == -1) first = idx;
                cout << players[idx]->name << " ** 抢地主!" << endl;
            } else {
                cout << players[idx]->name << " * 不抢" << endl;
            }
        }

        if(cnt == 0) {
            cout << "\n无人抢地主,重新发牌..." << endl;
            return ERROR;
        }

        if(cnt == 1) return first;

        // 二次抢地主
        cout << "\n────── 决胜局 ──────" << endl;
        if(first == CURRENTPLAYER) {
            bool decision = makeChoice(players[first]->name + " 是否抢地主?(Y/N): ");
            if(decision) {
                cout << players[first]->name << " ** 抢地主!" << endl;
                return first;
            }
        } else if(rand() % 2 == 1) {
            cout << players[first]->name << " ** 抢地主!" << endl;
            return first;
        }

        cout << players[first]->name << " * 放弃" << endl;
        return last;
    }

    void shuffle() {
        random_shuffle(allCards.begin(), allCards.end());

        int k = 0;
        for(int i = 0; i < PLAYERCOUNT; i++) {
            players[i]->cards.clear();
            for(int j = 0; j < 17; j++) {
                players[i]->cards.push_back(allCards[k++]);
            }
            players[i]->arrange();
            players[i]->print();
        }
        cout << endl;
    }

    bool isValidPlay(CardGroup& cardGroup, int playerIdx) {
        if(cardGroup.type.typeId == ERROR) {
            cout << "* 无效牌型,请重新出牌!" << endl;
            return false;
        }

        if(cardGroup.type.typeStr == "不出") {
            return true;
        }

        LastCards* last = LastCards::getInstance();
        if(last->player && last->player != players[playerIdx] && !last->cardGroup.isEmpty()) {
            if(!cardGroup.canBeat(last->cardGroup)) {
                cout << "* 管不上,请重新出牌!" << endl;
                return false;
            }
        }

        return true;
    }
};

string getColorChar(COLOR color) {
    switch(color) {
        case eHEART: return "红心";
        case eDIAMOND: return "黑桃";
        case eCLUB: return "梅花";
        case eSPADE: return "方块";
        default: return "";
    }
}

bool makeChoice(const string& tip) {
    cout << tip;
    string input;
    cin >> input;
    return input == "Y" || input == "y";
}

bool cmp(Card* a, Card* b) {
    if(a->value == b->value) {
        return a->color > b->color;
    }
    return a->value > b->value;
}

#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#define Sleep(x) usleep((x)*1000)
#endif

int main() {
    srand(time(nullptr));
    Landlords* game = new Landlords();

    do {
        game->init();
        game->startGame();
    } while(makeChoice("\n是否继续游戏?(Y/N): "));

    delete game;
    cout << "\n感谢游玩!" << endl;
    return 0;
}