化学麻将,包好玩的

· · 个人记录

#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <unordered_map>
#include <limits>
#include <cctype>
using namespace std;

// 元素定义
const vector<string> ELEMENTS = {
    "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne",
    "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca",
    "Mn", "Fe", "Cu", "Zn", "Ag", "Au"
};

// 稀有气体
const set<string> NOBLE_GASES = {"He", "Ne", "Ar"};

// 双元素化合物定义
const map<string, set<string>> COMPOUNDS = {
    {"H", {"O", "F", "Cl"}},
    {"C", {"O"}},
    {"Na", {"Cl"}},
    {"K", {"Cl"}},
    {"Mg", {"O"}},
    {"Ca", {"O"}},
    {"Fe", {"O"}},
    {"Cu", {"O"}},
    {"Zn", {"O"}},
    {"Cl", {"H", "Na", "K"}},
    {"S", {"H", "O"}}
};

// 三元素化合物定义
const set<vector<string>> MULTI_COMPOUNDS = {
    {"H", "C", "O"}, {"C", "O", "O"}, {"H", "H", "O"},
    {"H", "O", "H"}, {"N", "H", "H"}, 
    {"H", "S", "O"}, {"S", "O", "O"}
};

// 元素周期表顺序
const vector<string> PERIODIC_ORDER = {
    "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne",
    "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca",
    "Mn", "Fe", "Cu", "Zn", "Ag", "Au"
};

// 清屏函数
void clearScreen() {
    #ifdef _WIN32
        system("cls");
    #else
        system("clear");
    #endif
}

class Player {
public:
    vector<string> hand;
    bool isOut = false;
    string name;

    Player(string n) : name(n) {}

    // 按元素周期表排序手牌
    void sortHand() {
        sort(hand.begin(), hand.end(), [](const string& a, const string& b) {
            auto it_a = find(PERIODIC_ORDER.begin(), PERIODIC_ORDER.end(), a);
            auto it_b = find(PERIODIC_ORDER.begin(), PERIODIC_ORDER.end(), b);

            if (it_a == PERIODIC_ORDER.end()) return false;
            if (it_b == PERIODIC_ORDER.end()) return true;

            return distance(PERIODIC_ORDER.begin(), it_a) < distance(PERIODIC_ORDER.begin(), it_b);
        });
    }

    // 显示手牌
    void displayHand() {
        sortHand();
        cout << name << "的手牌(" << hand.size() << "张): ";
        for (const string& card : hand) {
            cout << card << " ";
        }
        cout << endl;
    }

    // 检查胜利条件
    bool checkWin(bool verbose = false) {
        vector<string> noble;
        vector<string> nonNoble;

        // 分离稀有气体和非稀有气体
        for (const string& card : hand) {
            if (NOBLE_GASES.find(card) != NOBLE_GASES.end()) {
                noble.push_back(card);
            } else {
                nonNoble.push_back(card);
            }
        }

        // 检查稀有气体数量
        if (noble.size() > 2) {
            if (verbose) {
                cout << "? 稀有气体数量超过2个(当前有" << noble.size() << "个)" << endl;
            }
            return false;
        }

        // 检查非稀有气体牌数是否为偶数
        if (nonNoble.size() % 2 != 0) {
            if (verbose) {
                cout << "? 非稀有气体牌数为奇数(当前有" << nonNoble.size() << "张)" << endl;
            }
            return false;
        }

        // 统计元素数量
        unordered_map<string, int> countMap;
        for (const string& card : nonNoble) countMap[card]++;

        // 尝试分组
        vector<pair<string, int>> countVec(countMap.begin(), countMap.end());
        bool canWin = dfsGrouping(countVec, 0);

        if (!canWin && verbose) {
            cout << "? 当前手牌无法全部组成有效的单质或化合物" << endl;
            // 显示未匹配的牌
            cout << "  未匹配的牌: ";
            for (auto& pair : countVec) {
                while (pair.second-- > 0) cout << pair.first << " ";
            }
            cout << endl;
        }

        return canWin;
    }

private:
    // DFS分组算法
    bool dfsGrouping(vector<pair<string, int>>& countVec, int start) {
        int n = countVec.size();
        int i = start;

        // 跳过计数为0的元素
        while (i < n && countVec[i].second == 0) i++;
        if (i == n) return true;

        string elemX = countVec[i].first;
        int& countX = countVec[i].second;

        // 选项1: 两个相同元素组成单质
        if (countX >= 2) {
            countX -= 2;
            if (dfsGrouping(countVec, i)) return true;
            countX += 2;
        }

        // 选项2: 与不同元素组成化合物
        for (int j = i; j < n; j++) {
            int& countY = countVec[j].second;
            if (countY == 0) continue;

            string elemY = countVec[j].first;

            // 检查是否有效化合物
            if (canFormCompound(elemX, elemY)) {
                countX--;
                countY--;
                if (dfsGrouping(countVec, i)) return true;
                countX++;
                countY++;
            }
        }

        // 选项3: 尝试三元素化合物
        if (countX >= 1) {
            for (int j = i; j < n; j++) {
                if (countVec[j].second == 0) continue;

                for (int k = j; k < n; k++) {
                    if (countVec[k].second == 0) continue;

                    string elemY = countVec[j].first;
                    string elemZ = countVec[k].first;

                    if (canFormMultiCompound(elemX, elemY, elemZ)) {
                        countX--;
                        countVec[j].second--;
                        countVec[k].second--;
                        if (dfsGrouping(countVec, i)) return true;
                        countX++;
                        countVec[j].second++;
                        countVec[k].second++;
                    }
                }
            }
        }

        return false;
    }

    bool canFormCompound(const string& elem1, const string& elem2) {
        string e1 = min(elem1, elem2);
        string e2 = max(elem1, elem2);

        // 检查预定义化合物
        auto it = COMPOUNDS.find(e1);
        return it != COMPOUNDS.end() && it->second.find(e2) != it->second.end();
    }

    bool canFormMultiCompound(const string& elem1, const string& elem2, const string& elem3) {
        vector<string> compounds = {elem1, elem2, elem3};
        sort(compounds.begin(), compounds.end());

        // 检查是否匹配任何多元素化合物
        for (const auto& compound : MULTI_COMPOUNDS) {
            vector<string> sortedCompound(compound.begin(), compound.end());
            sort(sortedCompound.begin(), sortedCompound.end());

            if (compounds == sortedCompound) {
                return true;
            }
        }

        return false;
    }
};

class ChemicalMahjong {
private:
    vector<Player> players;
    vector<string> drawPile;
    vector<string> discardPile;
    int currentPlayerIndex;
    int totalPlayers;

public:
    ChemicalMahjong(int numPlayers) : totalPlayers(numPlayers), currentPlayerIndex(0) {
        srand(time(0));
        for (int i = 0; i < numPlayers; i++) {
            players.emplace_back("玩家 " + to_string(i + 1));
        }
        initializeDrawPile();
        shuffleDrawPile();
        dealCards();
    }

    // 初始化牌堆
    void initializeDrawPile() {
        for (const string& elem : ELEMENTS) {
            int count = (elem == "H" || elem == "C" || elem == "O") ? 6 : 4;
            for (int i = 0; i < count; i++) {
                drawPile.push_back(elem);
            }
        }
    }

    // 洗牌
    void shuffleDrawPile() {
        random_shuffle(drawPile.begin(), drawPile.end());
    }

    // 发牌
    void dealCards() {
        for (int i = 0; i < 13; i++) {
            for (int j = 0; j < totalPlayers; j++) {
                if (drawPile.empty()) break;
                players[j].hand.push_back(drawPile.back());
                drawPile.pop_back();
            }
        }
    }

    // 从牌堆抽一张牌
    string drawCard() {
        if (drawPile.empty()) {
            if (discardPile.empty()) return "";  // 无牌可抽

            // 用弃牌堆重建牌堆
            drawPile = discardPile;
            discardPile.clear();
            shuffleDrawPile();
            cout << "牌堆已用尽,重新洗入弃牌堆!" << endl;
        }

        string card = drawPile.back();
        drawPile.pop_back();
        return card;
    }

    // 显示游戏状态
    void displayGameState() {
        cout << "\n当前游戏状态:" << endl;
        cout << "牌堆剩余: " << drawPile.size() << "张" << endl;
        cout << "弃牌堆顶: " << (discardPile.empty() ? "空" : discardPile.back()) << endl;

        for (Player& p : players) {
            if (!p.isOut) {
                p.displayHand();
            } else {
                cout << p.name << "已出局" << endl;
            }
        }
    }

    // 玩家选择出牌
    string playerChooseCard(Player& player) {
        while (true) {
            cout << player.name << "请选择要打出的牌(输入元素符号): ";
            string choice;
            cin >> choice;

            // 转换为首字母大写,其余小写
            if (!choice.empty()) {
                choice[0] = toupper(choice[0]);
                if (choice.size() > 1) {
                    choice[1] = tolower(choice[1]);
                }
            }

            // 检查输入是否为有效元素
            bool validElement = false;
            for (const string& elem : ELEMENTS) {
                if (elem == choice) {
                    validElement = true;
                    break;
                }
            }

            if (!validElement) {
                cout << "无效元素符号! 请输入有效的元素符号。" << endl;
                cout << "有效元素包括: ";
                for (const string& elem : ELEMENTS) {
                    cout << elem << " ";
                }
                cout << endl;
                continue;
            }

            // 检查手牌中是否有该牌
            auto it = find(player.hand.begin(), player.hand.end(), choice);
            if (it == player.hand.end()) {
                cout << "你手上没有 " << choice << " 牌! 请从你的手牌中选择。" << endl;
                player.displayHand();
                continue;
            }

            player.hand.erase(it);
            return choice;
        }
    }

    // 执行一个玩家回合
    void playTurn() {
        Player& currentPlayer = players[currentPlayerIndex];
        if (currentPlayer.isOut) {
            advanceTurn();
            return;
        }

        clearScreen();
        cout << "\n=== " << currentPlayer.name << "的回合 ===" << endl;
        displayGameState();

        // 每回合开始时检查是否可以获胜
        if (currentPlayer.checkWin(true)) {
            declareWinner(currentPlayer);
        }

        bool extraTurn = false;
        do {
            extraTurn = false;

            // 抽牌阶段
            string drawnCard = drawCard();
            if (drawnCard.empty()) {
                cout << "无牌可抽! 游戏结束。" << endl;
                exit(0);
            }
            cout << currentPlayer.name << "抽到了: " << drawnCard << endl;
            currentPlayer.hand.push_back(drawnCard);
            currentPlayer.displayHand();

            // 出牌阶段
            string playedCard = playerChooseCard(currentPlayer);
            cout << currentPlayer.name << "打出了: " << playedCard << endl;
            discardPile.push_back(playedCard);

            // 检查特殊规则
            if (discardPile.size() >= 2) {
                string lastCard = discardPile.back();
                string prevCard = discardPile[discardPile.size() - 2];

                // 规则1: 相同牌
                if (lastCard == prevCard) {
                    cout << "打出相同牌! " << currentPlayer.name << "获得额外回合!" << endl;
                    extraTurn = true;
                }
                // 规则2: 组成化合物
                else if (canFormCompound(lastCard, prevCard)) {
                    handleCompoundRule(currentPlayer);
                }
            }

            // 检查胜利条件
            if (currentPlayer.checkWin(true)) {
                declareWinner(currentPlayer);
            }

        } while (extraTurn);

        cout << "\n按Enter键结束本回合...";
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cin.get();
        advanceTurn();
    }

    // 处理化合物规则
    void handleCompoundRule(Player& player) {
        cout << "形成化合物! " << player.name << "可以拿走弃牌堆顶的牌!" << endl;

        while (true) {
            if (discardPile.size() < 2) break;

            // 取最后两张牌
            string lastCard = discardPile.back();
            string prevCard = discardPile[discardPile.size() - 2];

            // 检查是否仍能组成化合物
            if (!canFormCompound(lastCard, prevCard)) break;

            // 移除倒数第二张牌给玩家
            discardPile.erase(discardPile.end() - 2);
            player.hand.push_back(prevCard);
            cout << player.name << "获得了: " << prevCard << endl;
            player.displayHand();

            // 检查是否可以立即获胜
            if (player.checkWin(true)) {
                declareWinner(player);
            }

            // 玩家必须再出一张牌
            if (player.hand.empty()) break;

            string newCard = playerChooseCard(player);
            cout << player.name << "打出了: " << newCard << endl;
            discardPile.push_back(newCard);

            // 检查新出牌与上一张牌的关系
            if (discardPile.size() < 2) break;

            string newLast = discardPile.back();
            string newPrev = discardPile[discardPile.size() - 2];

            // 检查规则1: 相同牌
            if (newLast == newPrev) {
                cout << "打出相同牌! " << player.name << "获得额外回合!" << endl;
                players[currentPlayerIndex].hand = player.hand;
                playTurn();  // 立即进行额外回合
                return;
            }
        }
    }

    // 宣布获胜者
    void declareWinner(Player& player) {
        clearScreen();
        cout << "====================================" << endl;
        cout << "   " << player.name << " 获胜!" << endl;
        cout << "====================================" << endl;
        cout << "获胜条件满足:" << endl;
        cout << "? 所有手牌都能组成纯净物" << endl;
        cout << "? 稀有气体数量不超过2个" << endl;
        cout << "\n获胜牌组组合:" << endl;
        displayWinningCombination(player);

        cout << "\n游戏结束,按Enter键退出...";
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cin.get();
        exit(0);
    }

    // 显示获胜组合
    void displayWinningCombination(Player& player) {
        vector<string> noble;
        vector<string> nonNoble;

        // 分离稀有气体和非稀有气体
        for (const string& card : player.hand) {
            if (NOBLE_GASES.find(card) != NOBLE_GASES.end()) {
                noble.push_back(card);
            } else {
                nonNoble.push_back(card);
            }
        }

        // 显示稀有气体
        if (!noble.empty()) {
            cout << "稀有气体(" << noble.size() << "个): ";
            for (const string& gas : noble) cout << gas << " ";
            cout << endl;
        }

        // 统计非稀有气体元素
        unordered_map<string, int> countMap;
        for (const string& card : nonNoble) countMap[card]++;

        // 显示组合
        vector<pair<string, int>> countVec(countMap.begin(), countMap.end());
        findAndDisplayCombinations(countVec, 0);
    }

    // 查找并显示牌组组合
    void findAndDisplayCombinations(vector<pair<string, int>>& countVec, int start) {
        int n = countVec.size();
        int i = start;

        // 跳过计数为0的元素
        while (i < n && countVec[i].second == 0) i++;
        if (i == n) return;

        string elemX = countVec[i].first;
        int& countX = countVec[i].second;

        // 单质
        if (countX >= 2) {
            cout << "单质: " << elemX << elemX << endl;
            countX -= 2;
            findAndDisplayCombinations(countVec, i);
            countX += 2;
            return;
        }

        // 双元素化合物
        for (int j = i; j < n; j++) {
            int& countY = countVec[j].second;
            if (countY == 0) continue;

            string elemY = countVec[j].first;

            if (canFormCompound(elemX, elemY)) {
                cout << "化合物: " << elemX << elemY << endl;
                countX--;
                countY--;
                findAndDisplayCombinations(countVec, i);
                countX++;
                countY++;
                return;
            }
        }

        // 三元素化合物
        if (countX >= 1) {
            for (int j = i; j < n; j++) {
                if (countVec[j].second == 0) continue;

                for (int k = j; k < n; k++) {
                    if (countVec[k].second == 0) continue;

                    string elemY = countVec[j].first;
                    string elemZ = countVec[k].first;

                    vector<string> compounds = {elemX, elemY, elemZ};
                    sort(compounds.begin(), compounds.end());

                    for (const auto& compound : MULTI_COMPOUNDS) {
                        vector<string> sortedCompound(compound.begin(), compound.end());
                        sort(sortedCompound.begin(), sortedCompound.end());

                        if (compounds == sortedCompound) {
                            cout << "化合物: " << elemX << elemY << elemZ << endl;
                            countX--;
                            countVec[j].second--;
                            countVec[k].second--;
                            findAndDisplayCombinations(countVec, i);
                            countX++;
                            countVec[j].second++;
                            countVec[k].second++;
                            return;
                        }
                    }
                }
            }
        }
    }

    // 检查是否能组成双元素化合物
    bool canFormCompound(const string& elem1, const string& elem2) {
        string e1 = min(elem1, elem2);
        string e2 = max(elem1, elem2);

        auto it = COMPOUNDS.find(e1);
        return it != COMPOUNDS.end() && it->second.find(e2) != it->second.end();
    }

    // 前进到下一个玩家
    void advanceTurn() {
        do {
            currentPlayerIndex = (currentPlayerIndex + 1) % totalPlayers;
        } while (players[currentPlayerIndex].isOut && countActivePlayers() > 1);
    }

    // 计算活跃玩家数量
    int countActivePlayers() {
        int count = 0;
        for (Player& p : players) {
            if (!p.isOut) count++;
        }
        return count;
    }

    // 开始游戏
    void startGame() {
        clearScreen();
        cout << "化学麻将游戏开始! 共" << totalPlayers << "名玩家" << endl;
        cout << "游戏规则:" << endl;
        cout << "1. 每人初始13张牌,轮流抽牌和出牌" << endl;
        cout << "2. 打出与上家相同的牌可获得额外回合" << endl;
        cout << "3. 打出能与上家牌组成化合物的牌可拿走上家牌并继续出牌" << endl;
        cout << "4. 当你的13张牌都能组成纯净物(单质或化合物)且稀有气体不超过2个时获胜" << endl;
        cout << "--------------------------------------------------" << endl;
        cout << "按Enter键开始游戏...";
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cin.get();

        while (countActivePlayers() > 1) {
            playTurn();
        }

        clearScreen();
        cout << "游戏结束! 没有玩家满足获胜条件" << endl;
    }
};

int main() {
    int numPlayers;
    cout << "输入玩家数量 (2-4): ";
    cin >> numPlayers;

    if (numPlayers < 2 || numPlayers > 4) {
        cout << "玩家数量必须是3或4!" << endl;
        return 1;
    }

    // 清除输入缓冲区
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    ChemicalMahjong game(numPlayers);
    game.startGame();

    return 0;
}