跳到正文

个人记录

I love mine 9(c++14)

zhoumoshu约 195 分钟
原文
文章信息与版本

文章信息

发布
2025年10月24日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 195 分钟

版本

  1. v2当前
  2. v1
C++
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <windows.h>
#include <algorithm>
#include <cmath>

using namespace std;

// 矿物结构体
struct Mineral {
    string name;
    string description;
    int rarity;  // 1-5,1最常见,5最稀有
    double baseValue;  // 单位价值(人民币),根据unit不同含义不同
    bool discovered;
    string colorCode;
    string type;       // 矿石类型:造岩矿物、金属矿石、宝石、工业矿物
    int minPickaxeLevel;
    string source;      // 来源:mine-挖掘, chop-砍伐, both-两者均可
    bool processable;
    string unit;        // 单位:g-克, kg-千克, t-吨, ct-克拉
    double unitWeight;  // 单位重量(克)

    bool operator==(const Mineral& other) const {
        return name == other.name;
    }
};

// 加工后的物品结构体
struct ProcessedItem {
    string name;
    string originalName;
    int quality; // 1-5,1最差,5最好
    double value;
    double weight;
    string colorCode;
    string description;
    string unit;

    bool operator==(const ProcessedItem& other) const {
        return name == other.name && quality == other.quality;
    }
};

// 镐子结构体
struct Pickaxe {
    string name;
    int level;
    int durability;
    int maxDurability;
    int efficiency;    // 采矿效率加成
    int luck;          // 幸运值,影响稀有矿物出现率
    int speed;         // 挖掘速度(毫秒)
    int multiMine;     // 一次挖掘获得矿物数量
    vector<pair<string, double>> requiredMinerals; // 制作所需材料(重量)

    Pickaxe(string n = "", int lvl = 1, int dur = 30, int maxDur = 30,
            int eff = 0, int lck = 0, int spd = 300, int multi = 1,
            vector<pair<string, double>> req = {})
        : name(n), level(lvl), durability(dur), maxDurability(maxDur),
          efficiency(eff), luck(lck), speed(spd), multiMine(multi), requiredMinerals(req) {}

    bool operator==(const Pickaxe& other) const {
        return name == other.name;
    }
};

// 成就结构体
struct Achievement {
    string name;
    string description;
    bool unlocked;
    string rewardType; // "money", "item", "skill"
    double rewardValue;
    string requiredMineral;
    double requiredAmount;
    int requiredLevel;
    double requiredMoney;

    Achievement(string n, string desc, string rType, double rValue,
                string reqMineral = "", double reqAmount = 0,
                int reqLevel = 0, double reqMoney = 0)
        : name(n), description(desc), unlocked(false), rewardType(rType),
          rewardValue(rValue), requiredMineral(reqMineral), requiredAmount(reqAmount),
          requiredLevel(reqLevel), requiredMoney(reqMoney) {}
};

// 市场商品结构体
struct MarketItem {
    string mineralName;
    double priceMultiplier; // 价格乘数 (0.5-2.0)
    int stock; // 库存 (-1表示无限)
    bool isSpecial; // 是否为特殊商品
    int availableDays; // 剩余天数
    double purchasePrice; // 购买时的价格(用于计算盈亏)
    double purchaseWeight; // 购买的重量

    MarketItem(string name, double multiplier, int stk = -1, bool special = false, int days = 3,
               double purchase = 0, double weight = 0)
        : mineralName(name), priceMultiplier(multiplier), stock(stk), isSpecial(special),
          availableDays(days), purchasePrice(purchase), purchaseWeight(weight) {}
};

// 玩家数据
struct PlayerData {
    double money;  // 改为人民币
    int level;
    int experience;
    int maxEnergy;
    int currentEnergy;
    Pickaxe currentPickaxe;
    vector<Mineral> inventory;
    vector<ProcessedItem> processedInventory;
    vector<string> unlockedPickaxeNames;
    double debt; // 负债(人民币)
    int totalDays;
    int processingSkill;
    vector<Achievement> achievements;
    map<string, int> mineralsMined; // 记录每种矿物挖掘数量
    vector<MarketItem> purchasedItems; // 记录从市场购买的商品(用于卖出)
};

class MiningGame {
private:
    vector<Mineral> minerals;
    vector<Pickaxe> allPickaxes;
    PlayerData player;
    int dayCount;
    vector<MarketItem> marketItems;
    int marketRefreshDays;

    // 颜色代码
    const string RED = "\033[31m";
    const string GREEN = "\033[32m";
    const string YELLOW = "\033[33m";
    const string BLUE = "\033[34m";
    const string MAGENTA = "\033[35m";
    const string CYAN = "\033[36m";
    const string WHITE = "\033[37m";
    const string GRAY = "\033[90m";
    const string ORANGE = "\033[38;5;214m";
    const string BROWN = "\033[38;5;130m";
    const string GOLD = "\033[38;5;220m";
    const string PURPLE = "\033[38;5;129m";
    const string SILVER = "\033[38;5;252m";
    const string PINK = "\033[38;5;205m";
    const string BLACK = "\033[38;5;232m";
    const string RESET = "\033[0m";

public:
    MiningGame() {
        InitializeGameData();
        dayCount = 1;
        marketRefreshDays = 0;
        InitializeAchievements();
        InitializeMarket();
        LoadGame();
    }

    // 初始化成就系统
    void InitializeAchievements() {
        player.achievements.clear();

        // 基础成就
        player.achievements.push_back(Achievement("初出茅庐", "挖掘第一个矿物", "money", 100, "", 0, 1, 0));
        player.achievements.push_back(Achievement("财富积累", "拥有1000元", "money", 500, "", 0, 0, 1000));
        player.achievements.push_back(Achievement("中级矿工", "达到5级", "skill", 1, "", 0, 5, 0));

        // 矿物收集成就
        player.achievements.push_back(Achievement("石头爱好者", "收集1000kg石头", "money", 1000, "石头", 1000000, 0, 0));
        player.achievements.push_back(Achievement("木材大师", "收集500kg木材", "money", 800, "木材", 500000, 0, 0));
        player.achievements.push_back(Achievement("宝石猎人", "发现5种宝石", "money", 2000, "", 0, 0, 0));

        // 高级成就
        player.achievements.push_back(Achievement("百万富翁", "拥有100万元", "money", 10000, "", 0, 0, 1000000));
        player.achievements.push_back(Achievement("顶级矿工", "达到20级", "skill", 3, "", 0, 20, 0));
        player.achievements.push_back(Achievement("矿物学家", "发现30种矿物", "money", 5000, "", 0, 0, 0));
    }

    // 初始化市场(修改:每次进入市场都刷新,只显示7个商品)
    void InitializeMarket() {
        marketItems.clear();

        // 生成3个特价商品
        vector<string> specialMinerals;
        for(const auto& mineral : minerals) {
            if(mineral.rarity >= 3 && mineral.rarity <= 5) {
                specialMinerals.push_back(mineral.name);
            }
        }

        // 随机选择3个特价商品
        for(int i = 0; i < 3 && !specialMinerals.empty(); i++) {
            int index = rand() % specialMinerals.size();
            string mineralName = specialMinerals[index];
            specialMinerals.erase(specialMinerals.begin() + index);

            double multiplier = 0.5 + (rand() % 30) * 0.01; // 0.5-0.8
            int stock = 1 + rand() % 3;
            marketItems.push_back(MarketItem(mineralName, multiplier, stock, true, 3));
        }

        // 生成4个普通商品
        vector<string> commonMinerals;
        for(const auto& mineral : minerals) {
            if(mineral.rarity <= 3) {
                commonMinerals.push_back(mineral.name);
            }
        }

        // 随机选择4个普通商品
        for(int i = 0; i < 4 && !commonMinerals.empty(); i++) {
            int index = rand() % commonMinerals.size();
            string mineralName = commonMinerals[index];
            commonMinerals.erase(commonMinerals.begin() + index);

            double multiplier = 0.8 + (rand() % 40) * 0.01; // 0.8-1.2
            int stock = -1;
            marketItems.push_back(MarketItem(mineralName, multiplier, stock, false, 7));
        }

        marketRefreshDays = 1; // 每天刷新市场
    }

    // 检查并更新成就
    void CheckAchievements() {
        int mineralsDiscovered = 0;
        int gemsDiscovered = 0;

        for(const auto& mineral : minerals) {
            if(mineral.discovered) {
                mineralsDiscovered++;
                if(mineral.type == "宝石" || mineral.type == "玉石") {
                    gemsDiscovered++;
                }
            }
        }

        for(auto& achievement : player.achievements) {
            if(!achievement.unlocked) {
                bool unlocked = false;

                if(achievement.name == "初出茅庐") {
                    unlocked = (player.mineralsMined.size() > 0);
                }
                else if(achievement.name == "财富积累") {
                    unlocked = (player.money >= achievement.requiredMoney);
                }
                else if(achievement.name == "中级矿工") {
                    unlocked = (player.level >= achievement.requiredLevel);
                }
                else if(achievement.name == "石头爱好者") {
                    if(player.mineralsMined.find("石头") != player.mineralsMined.end()) {
                        unlocked = (player.mineralsMined["石头"] >= achievement.requiredAmount);
                    }
                }
                else if(achievement.name == "木材大师") {
                    if(player.mineralsMined.find("木材") != player.mineralsMined.end()) {
                        unlocked = (player.mineralsMined["木材"] >= achievement.requiredAmount);
                    }
                }
                else if(achievement.name == "宝石猎人") {
                    unlocked = (gemsDiscovered >= 5);
                }
                else if(achievement.name == "百万富翁") {
                    unlocked = (player.money >= achievement.requiredMoney);
                }
                else if(achievement.name == "顶级矿工") {
                    unlocked = (player.level >= achievement.requiredLevel);
                }
                else if(achievement.name == "矿物学家") {
                    unlocked = (mineralsDiscovered >= 30);
                }

                if(unlocked) {
                    UnlockAchievement(achievement);
                }
            }
        }
    }

    // 解锁成就
    void UnlockAchievement(Achievement& achievement) {
        achievement.unlocked = true;

        system("cls");
        cout << GOLD << "?? 成就解锁! ??" << RESET << endl;
        cout << GOLD << "★ " << achievement.name << " ★" << RESET << endl;
        cout << "描述: " << achievement.description << endl;
        cout << "奖励: ";

        if(achievement.rewardType == "money") {
            player.money += achievement.rewardValue;
            cout << GREEN << FormatMoney(achievement.rewardValue) << RESET << endl;
        } else if(achievement.rewardType == "skill") {
            player.processingSkill += achievement.rewardValue;
            cout << "加工技能 +" << achievement.rewardValue << endl;
        }

        cout << "\n按任意键继续..." << endl;
        cin.ignore();
        cin.get();
    }

    // 显示成就界面
    void ShowAchievements() {
        while(true) {
            system("cls");
            cout << GOLD << "===== 成就系统 =====" << RESET << endl;

            int unlockedCount = 0;
            for(const auto& achievement : player.achievements) {
                if(achievement.unlocked) {
                    unlockedCount++;
                }
            }

            cout << "成就进度: " << unlockedCount << "/" << player.achievements.size() << endl;
            cout << "=====================" << endl;

            for(const auto& achievement : player.achievements) {
                if(achievement.unlocked) {
                    cout << GOLD << "? " << achievement.name << RESET << endl;
                } else {
                    cout << GRAY << "○ " << achievement.name << RESET << endl;
                }
                cout << "   " << achievement.description << endl;

                // 显示进度
                if(achievement.requiredMineral != "") {
                    if(player.mineralsMined.find(achievement.requiredMineral) != player.mineralsMined.end()) {
                        double progress = min(100.0, (player.mineralsMined[achievement.requiredMineral] / achievement.requiredAmount) * 100);
                        cout << "   进度: " << progress << "%" << endl;
                    } else {
                        cout << "   进度: 0%" << endl;
                    }
                } else if(achievement.requiredMoney > 0) {
                    double progress = min(100.0, (player.money / achievement.requiredMoney) * 100);
                    cout << "   进度: " << progress << "%" << endl;
                } else if(achievement.requiredLevel > 0) {
                    double progress = min(100.0, (player.level * 100.0 / achievement.requiredLevel));
                    cout << "   进度: " << progress << "%" << endl;
                }

                cout << endl;
            }

            cout << "0. 返回" << endl;
            cout << "选择: ";

            int choice;
            cin >> choice;

            if(choice == 0) break;
        }
    }

    // 显示市场界面(修改:修复矿物名称显示问题,确保价格更新)
    void ShowMarket() {
        // 每次进入市场都刷新
        InitializeMarket();

        while(true) {
            system("cls");
            cout << GREEN << "===== 矿物市场 =====" << RESET << endl;
            cout << "市场每日刷新" << endl;
            cout << "你的资金: " << FormatMoney(player.money) << endl;
            cout << "=====================" << endl;

            // 显示可购买商品(7个)
            cout << CYAN << "--- 可购买商品 (7个) ---" << RESET << endl;
            for(int i = 0; i < marketItems.size(); i++) {
                const auto& item = marketItems[i];
                // 修复:确保获取到正确的矿物信息
                Mineral mineral;
                bool found = false;
                for(const auto& m : minerals) {
                    if(m.name == item.mineralName) {
                        mineral = m;
                        found = true;
                        break;
                    }
                }

                if(!found) {
                    cout << i + 1 << ". " << RED << "未知商品" << RESET << endl;
                    continue;
                }

                double unitPrice = CalculateUnitPrice(mineral, item.priceMultiplier);

                cout << i + 1 << ". " << mineral.colorCode << mineral.name << RESET;
                cout << " - 价格: " << GREEN << FormatMoney(unitPrice);

                // 显示单位
                if(mineral.unit == "ct") {
                    cout << "/克拉";
                } else if(mineral.unit == "g") {
                    cout << "/克";
                } else {
                    cout << "/千克";
                }
                cout << RESET;

                cout << " (" << (item.priceMultiplier > 1.0 ? RED : GREEN)
                     << (item.priceMultiplier > 1.0 ? "↑" : "↓") << fabs(item.priceMultiplier - 1.0) * 100 << "%" << RESET << ")";

                if(item.stock > 0) {
                    cout << " - 库存: " << item.stock;
                } else if(item.stock == 0) {
                    cout << " - " << RED << "售罄" << RESET;
                }

                if(item.isSpecial) {
                    cout << " - " << PURPLE << "特价!" << RESET;
                }

                cout << endl;
            }

            // 显示可出售商品(5个)
            cout << CYAN << "\n--- 可出售商品 (5个) ---" << RESET << endl;

            // 1. 显示市场购买的商品(最多3个)
            int purchasedCount = min(3, (int)player.purchasedItems.size());
            for(int i = 0; i < purchasedCount; i++) {
                const auto& item = player.purchasedItems[i];
                Mineral mineral = GetMineralByName(item.mineralName);

                // 修复:获取当前市场价格
                double currentMultiplier = 1.0;
                for(const auto& marketItem : marketItems) {
                    if(marketItem.mineralName == item.mineralName) {
                        currentMultiplier = marketItem.priceMultiplier;
                        break;
                    }
                }

                double currentUnitPrice = CalculateUnitPrice(mineral, currentMultiplier);
                double profitLoss = currentUnitPrice - item.purchasePrice;
                string profitColor = (profitLoss >= 0) ? GREEN : RED;
                string profitSymbol = (profitLoss >= 0) ? "+" : "";

                cout << i + 1 + marketItems.size() << ". " << mineral.colorCode << mineral.name << RESET;
                cout << " - 重量: " << FormatWeight(item.purchaseWeight);
                cout << " - 购买价: " << FormatMoney(item.purchasePrice);
                cout << " - 当前价: " << FormatMoney(currentUnitPrice);
                cout << " - " << profitColor << profitSymbol << FormatMoney(profitLoss) << RESET;
                cout << " [市场购买]" << endl;
            }

            // 2. 显示自己挖掘的商品(最多2个)
            vector<string> minedItems;
            map<string, double> minedWeights;

            // 计算自己挖掘的矿物重量(总重量减去市场购买的重量)
            for(const auto& mineral : player.inventory) {
                minedWeights[mineral.name] += mineral.unitWeight;
            }

            // 减去市场购买的重量
            for(const auto& purchased : player.purchasedItems) {
                minedWeights[purchased.mineralName] -= purchased.purchaseWeight;
            }

            // 收集有重量的自己挖掘矿物
            for(const auto& pair : minedWeights) {
                if(pair.second > 0) {
                    minedItems.push_back(pair.first);
                }
            }

            int minedCount = min(2, (int)minedItems.size());
            for(int i = 0; i < minedCount; i++) {
                string itemName = minedItems[i];
                Mineral mineral = GetMineralByName(itemName);
                double weight = minedWeights[itemName];

                // 修复:使用当前市场价格计算价值
                double currentMultiplier = 1.0;
                for(const auto& marketItem : marketItems) {
                    if(marketItem.mineralName == itemName) {
                        currentMultiplier = marketItem.priceMultiplier;
                        break;
                    }
                }

                double baseValue = CalculateMineralValue(mineral, weight);
                double sellValue = baseValue * 0.7 * currentMultiplier; // 使用当前市场价格

                cout << i + 1 + marketItems.size() + purchasedCount << ". " << mineral.colorCode << mineral.name << RESET;
                cout << " - 重量: " << FormatWeight(weight);
                cout << " - 可卖: " << GREEN << FormatMoney(sellValue) << RESET;
                cout << " [自己挖掘]" << endl;
            }

            // 如果可出售商品不足5个,显示提示
            int totalSellable = purchasedCount + minedCount;
            if(totalSellable < 5) {
                for(int i = totalSellable; i < 5; i++) {
                    cout << i + 1 + marketItems.size() << ". " << GRAY << "空位" << RESET << endl;
                }
            }

            cout << "\n0. 返回" << endl;
            cout << "选择: ";

            int choice;
            cin >> choice;

            if(choice == 0) break;

            int totalOptions = marketItems.size() + 5; // 7个可买 + 5个可卖
            if(choice > 0 && choice <= totalOptions) {
                if(choice <= marketItems.size()) {
                    // 购买商品
                    BuyFromMarket(choice - 1);
                } else {
                    // 出售商品
                    int sellIndex = choice - 1 - marketItems.size();

                    if(sellIndex < purchasedCount) {
                        // 出售市场购买的商品
                        SellPurchasedItem(sellIndex);
                    } else if(sellIndex < totalSellable) {
                        // 出售自己挖掘的商品
                        int minedIndex = sellIndex - purchasedCount;
                        SellMinedItem(minedItems[minedIndex]);
                    } else {
                        cout << RED << "该位置没有商品!" << RESET << endl;
                        Sleep(1000);
                    }
                }
            } else {
                cout << RED << "无效选择!" << RESET << endl;
                Sleep(1000);
            }
        }
    }

    // 计算单位价格
    double CalculateUnitPrice(const Mineral& mineral, double multiplier) {
        if (mineral.unit == "ct") {
            // 宝石:baseValue是每克拉的价值
            return mineral.baseValue * multiplier;
        } else if (mineral.unit == "g") {
            // 贵金属:baseValue是每克的价值
            return mineral.baseValue * multiplier;
        } else {
            // 普通矿物:baseValue是每千克的价值
            return mineral.baseValue * multiplier;
        }
    }

    // 从市场购买
    void BuyFromMarket(int index) {
        if(index < 0 || index >= marketItems.size()) return;

        MarketItem& marketItem = marketItems[index];
        Mineral mineral = GetMineralByName(marketItem.mineralName);

        if(marketItem.stock == 0) {
            cout << RED << "该商品已售罄!" << RESET << endl;
            Sleep(1000);
            return;
        }

        double unitPrice = CalculateUnitPrice(mineral, marketItem.priceMultiplier);

        cout << "购买 " << mineral.colorCode << mineral.name << RESET << endl;
        cout << "单价: " << GREEN << FormatMoney(unitPrice) << RESET;
        if(mineral.unit == "ct") cout << "/克拉";
        else if(mineral.unit == "g") cout << "/克";
        else cout << "/千克";
        cout << endl;

        cout << "输入购买数量: ";
        double quantity;
        cin >> quantity;

        if(quantity <= 0) {
            cout << RED << "无效数量!" << RESET << endl;
            Sleep(1000);
            return;
        }

        // 根据单位计算总价和重量
        double totalCost = 0;
        double weightGrams = 0;

        if (mineral.unit == "ct") {
            // 克拉转克:1克拉 = 0.2克
            weightGrams = quantity * 0.2;
            totalCost = unitPrice * quantity;
        } else if (mineral.unit == "g") {
            weightGrams = quantity;
            totalCost = unitPrice * quantity;
        } else {
            // 千克转克
            weightGrams = quantity * 1000;
            totalCost = unitPrice * quantity;
        }

        if(player.money < totalCost) {
            cout << RED << "资金不足!需要 " << FormatMoney(totalCost) << RESET << endl;
            Sleep(1000);
            return;
        }

        // 检查库存
        if(marketItem.stock > 0 && quantity > marketItem.stock) {
            cout << RED << "库存不足!只有 " << marketItem.stock << " 件可用" << RESET << endl;
            Sleep(1000);
            return;
        }

        player.money -= totalCost;

        // 添加到背包
        Mineral newMineral = mineral;
        newMineral.unitWeight = weightGrams;
        player.inventory.push_back(newMineral);

        // 记录购买的商品信息(用于股票模拟)
        MarketItem purchasedItem = marketItem;
        purchasedItem.purchasePrice = unitPrice;
        purchasedItem.purchaseWeight = weightGrams;
        player.purchasedItems.push_back(purchasedItem);

        // 将矿物标记为已发现
        for(auto& m : minerals) {
            if(m.name == mineral.name) {
                m.discovered = true;
                break;
            }
        }

        if(marketItem.stock > 0) {
            marketItem.stock -= quantity;
        }

        cout << GREEN << "购买成功!花费 " << FormatMoney(totalCost) << RESET << endl;
        cout << "获得: " << FormatWeight(weightGrams) << " " << mineral.name << endl;
        cout << YELLOW << "注意: 该商品已计入图鉴,可以在市场卖出观察价格变化" << RESET << endl;
        Sleep(1000);
    }

    // 出售市场购买的商品(修复:使用当前市场价格)
    void SellPurchasedItem(int index) {
        if(index < 0 || index >= player.purchasedItems.size()) return;

        MarketItem item = player.purchasedItems[index];
        Mineral mineral = GetMineralByName(item.mineralName);

        // 修复:获取当前市场价格
        double currentMultiplier = 1.0;
        for(const auto& marketItem : marketItems) {
            if(marketItem.mineralName == item.mineralName) {
                currentMultiplier = marketItem.priceMultiplier;
                break;
            }
        }

        double currentUnitPrice = CalculateUnitPrice(mineral, currentMultiplier);

        // 计算总价值和盈亏
        double totalValue = 0;
        if (mineral.unit == "ct") {
            totalValue = currentUnitPrice * (item.purchaseWeight / 0.2);
        } else if (mineral.unit == "g") {
            totalValue = currentUnitPrice * item.purchaseWeight;
        } else {
            totalValue = currentUnitPrice * (item.purchaseWeight / 1000);
        }

        double originalValue = 0;
        if (mineral.unit == "ct") {
            originalValue = item.purchasePrice * (item.purchaseWeight / 0.2);
        } else if (mineral.unit == "g") {
            originalValue = item.purchasePrice * item.purchaseWeight;
        } else {
            originalValue = item.purchasePrice * (item.purchaseWeight / 1000);
        }

        double profitLoss = totalValue - originalValue;

        cout << "出售投资商品 " << mineral.colorCode << mineral.name << RESET << endl;
        cout << "重量: " << FormatWeight(item.purchaseWeight) << endl;
        cout << "购买价格: " << FormatMoney(item.purchasePrice) << " (" << FormatMoney(originalValue) << ")" << endl;
        cout << "当前价格: " << FormatMoney(currentUnitPrice) << " (" << FormatMoney(totalValue) << ")" << endl;

        if(profitLoss >= 0) {
            cout << "盈利: " << GREEN << "+" << FormatMoney(profitLoss) << RESET << endl;
        } else {
            cout << "亏损: " << RED << FormatMoney(profitLoss) << RESET << endl;
        }

        cout << "确认出售? (y/n): ";

        char confirm;
        cin >> confirm;

        if(confirm == 'y' || confirm == 'Y') {
            // 移除购买记录
            player.purchasedItems.erase(player.purchasedItems.begin() + index);

            // 从背包中移除对应的矿物
            double weightToRemove = item.purchaseWeight;
            for(auto it = player.inventory.begin(); it != player.inventory.end(); ) {
                if(it->name == mineral.name && weightToRemove > 0) {
                    if(it->unitWeight <= weightToRemove) {
                        weightToRemove -= it->unitWeight;
                        it = player.inventory.erase(it);
                    } else {
                        it->unitWeight -= weightToRemove;
                        weightToRemove = 0;
                        ++it;
                    }
                } else {
                    ++it;
                }
            }

            // 获得当前价值
            player.money += totalValue;

            cout << GREEN << "出售成功!获得 " << FormatMoney(totalValue) << RESET << endl;

            if(profitLoss > 0) {
                cout << GREEN << "投资盈利: " << FormatMoney(profitLoss) << RESET << endl;
            }
        }

        Sleep(1000);
    }

    // 出售自己挖掘的商品(修复:使用当前市场价格)
    void SellMinedItem(const string& itemName) {
        Mineral mineral = GetMineralByName(itemName);

        // 计算自己挖掘的总重量
        double totalWeight = 0;
        for(const auto& m : player.inventory) {
            if(m.name == itemName) {
                totalWeight += m.unitWeight;
            }
        }

        // 减去市场购买的重量
        for(const auto& purchased : player.purchasedItems) {
            if(purchased.mineralName == itemName) {
                totalWeight -= purchased.purchaseWeight;
            }
        }

        if(totalWeight <= 0) {
            cout << RED << "没有可出售的自己挖掘的" << itemName << "!" << RESET << endl;
            Sleep(1000);
            return;
        }

        // 修复:获取当前市场价格
        double currentMultiplier = 1.0;
        for(const auto& marketItem : marketItems) {
            if(marketItem.mineralName == itemName) {
                currentMultiplier = marketItem.priceMultiplier;
                break;
            }
        }

        double baseValue = CalculateMineralValue(mineral, totalWeight);
        double sellValue = baseValue * 0.7 * currentMultiplier; // 使用当前市场价格

        cout << "出售 " << mineral.colorCode << itemName << RESET << endl;
        cout << "自己挖掘的重量: " << FormatWeight(totalWeight) << endl;
        cout << "可获得: " << GREEN << FormatMoney(sellValue) << RESET << endl;
        cout << "确认出售? (y/n): ";

        char confirm;
        cin >> confirm;

        if(confirm == 'y' || confirm == 'Y') {
            // 从背包中移除自己挖掘的矿物
            double weightToRemove = totalWeight;
            for(auto it = player.inventory.begin(); it != player.inventory.end(); ) {
                if(it->name == itemName && weightToRemove > 0) {
                    if(it->unitWeight <= weightToRemove) {
                        weightToRemove -= it->unitWeight;
                        it = player.inventory.erase(it);
                    } else {
                        it->unitWeight -= weightToRemove;
                        weightToRemove = 0;
                        ++it;
                    }
                } else {
                    ++it;
                }
            }

            player.money += sellValue;

            cout << GREEN << "出售成功!获得 " << FormatMoney(sellValue) << RESET << endl;
        }

        Sleep(1000);
    }

    // 获取单位重量
    double GetUnitWeight(const Mineral& mineral) {
        if (mineral.unit == "ct") {
            return 0.2; // 1克拉 = 0.2克
        } else if (mineral.unit == "g") {
            return 1.0;
        } else {
            return 1000.0; // 1千克 = 1000克
        }
    }

    // 更新市场
    void UpdateMarket() {
        marketRefreshDays--;
        if(marketRefreshDays <= 0) {
            marketRefreshDays = 1;
        }
    }

    // 重量转换函数
    string FormatWeight(double grams) {
        if (grams >= 1000000) {
            double tons = grams / 1000000;
            char buffer[20];
            snprintf(buffer, sizeof(buffer), "%.2f 吨", tons);
            return string(buffer);
        } else if (grams >= 1000) {
            double kg = grams / 1000;
            char buffer[20];
            snprintf(buffer, sizeof(buffer), "%.2f 千克", kg);
            return string(buffer);
        } else if (grams >= 1) {
            char buffer[20];
            snprintf(buffer, sizeof(buffer), "%.1f 克", grams);
            return string(buffer);
        } else {
            double carats = grams * 5; // 1克 = 5克拉
            char buffer[20];
            snprintf(buffer, sizeof(buffer), "%.2f 克拉", carats);
            return string(buffer);
        }
    }

    // 格式化货币显示
    string FormatMoney(double amount) {
        if (amount >= 100000000) {
            double yi = amount / 100000000;
            char buffer[20];
            snprintf(buffer, sizeof(buffer), "%.2f 亿元", yi);
            return string(buffer);
        } else if (amount >= 10000) {
            double wan = amount / 10000;
            char buffer[20];
            snprintf(buffer, sizeof(buffer), "%.2f 万元", wan);
            return string(buffer);
        } else if (amount >= 1) {
            char buffer[20];
            snprintf(buffer, sizeof(buffer), "%.2f 元", amount);
            return string(buffer);
        } else {
            char buffer[20];
            snprintf(buffer, sizeof(buffer), "%.2f 元", amount);
            return string(buffer);
        }
    }

    // 计算矿物的单位价值
    double CalculateUnitValue(const Mineral& mineral) {
        if (mineral.unit == "ct") {
            return mineral.baseValue;
        } else if (mineral.unit == "g") {
            return mineral.baseValue;
        } else {
            return mineral.baseValue;
        }
    }

    // 计算矿物的总价值(考虑重量)
    double CalculateMineralValue(const Mineral& mineral, double weight) {
        double unitValue = mineral.baseValue;

        if (mineral.unit == "ct") {
            return unitValue * (weight / 0.2);
        } else if (mineral.unit == "g") {
            return unitValue * weight;
        } else {
            return unitValue * (weight / 1000);
        }
    }

    void InitializeGameData() {
        minerals.clear();

        // 基础材料 - baseValue是每千克的价值
        minerals.push_back({"木材", "基本的建筑材料", 1, 3.0, true, BROWN, "材料", 1, "chop", true, "kg", 1000});
        minerals.push_back({"石头", "常见的建筑材料", 1, 1.0, true, GRAY, "材料", 1, "both", true, "kg", 1000});
        minerals.push_back({"黏土", "湿润的泥土", 1, 0.5, true, BROWN, "材料", 1, "both", true, "kg", 1000});

        // 造岩矿物
        minerals.push_back({"石英", "非常坚硬,玻璃光泽", 1, 2.0, true, WHITE, "造岩矿物", 1, "mine", true, "kg", 1000});
        minerals.push_back({"钾长石", "花岗岩中的粉红色矿物", 1, 1.5, false, PINK, "造岩矿物", 2, "mine", true, "kg", 1000});
        minerals.push_back({"斜长石", "火成岩中最常见的矿物", 1, 1.2, false, GRAY, "造岩矿物", 2, "mine", true, "kg", 1000});
        minerals.push_back({"白云母", "片状无色透明矿物", 2, 5.0, false, SILVER, "造岩矿物", 3, "mine", true, "g", 1});
        minerals.push_back({"黑云母", "黑色片状矿物", 1, 3.0, false, BLACK, "造岩矿物", 2, "mine", true, "kg", 1000});
        minerals.push_back({"橄榄石", "黄绿色玻璃状矿物", 3, 800.0, false, GREEN, "造岩矿物", 4, "mine", true, "g", 1});
        minerals.push_back({"方解石", "遇酸起泡的矿物", 1, 2.0, false, WHITE, "造岩矿物", 1, "mine", true, "kg", 1000});
        minerals.push_back({"白云石", "弯曲马鞍形晶体", 2, 3.0, false, GRAY, "造岩矿物", 2, "mine", true, "kg", 1000});
        minerals.push_back({"石膏", "硬度低的硫酸盐矿物", 1, 1.0, false, WHITE, "造岩矿物", 1, "mine", true, "kg", 1000});
        minerals.push_back({"磁铁矿", "具有强磁性的铁矿石", 2, 500.0, false, BLACK, "金属矿石", 3, "mine", true, "kg", 1000});
        minerals.push_back({"钛铁矿", "钛的主要矿石", 3, 2500.0, false, BLACK, "金属矿石", 4, "mine", true, "kg", 1000});
        minerals.push_back({"磷灰石", "牙齿和骨骼的主要成分", 2, 800.0, false, GREEN, "工业矿物", 2, "mine", true, "kg", 1000});

        // 金属矿石
        minerals.push_back({"赤铁矿", "最重要的铁矿石", 2, 600.0, false, RED, "金属矿石", 3, "mine", true, "kg", 1000});
        minerals.push_back({"黄铜矿", "最主要的铜矿石", 2, 5200.0, false, YELLOW, "金属矿石", 3, "mine", true, "kg", 1000});
        minerals.push_back({"斑铜矿", "重要的铜矿石", 3, 6800.0, false, PURPLE, "金属矿石", 4, "mine", true, "kg", 1000});
        minerals.push_back({"孔雀石", "鲜艳的绿色次生铜矿", 3, 15500.0, false, GREEN, "宝石", 3, "mine", true, "g", 1});
        minerals.push_back({"铝土矿", "铝的主要矿石", 2, 800.0, false, BROWN, "金属矿石", 3, "mine", true, "kg", 1000});
        minerals.push_back({"方铅矿", "最重要的铅矿石", 2, 4200.0, false, GRAY, "金属矿石", 3, "mine", true, "kg", 1000});
        minerals.push_back({"闪锌矿", "主要的锌矿石", 2, 3800.0, false, BROWN, "金属矿石", 3, "mine", true, "kg", 1000});
        minerals.push_back({"软锰矿", "最重要的锰矿石", 2, 2100.0, false, BLACK, "金属矿石", 3, "mine", true, "kg", 1000});
        minerals.push_back({"黄铁矿", "俗称愚人金", 1, 500.0, false, YELLOW, "金属矿石", 2, "mine", true, "kg", 1000});
        minerals.push_back({"铬铁矿", "铬的唯一经济矿石", 4, 12500.0, false, BLACK, "金属矿石", 5, "mine", true, "kg", 1000});
        minerals.push_back({"黑钨矿", "重要的钨矿石", 4, 25800.0, false, BLACK, "金属矿石", 5, "mine", true, "kg", 1000});
        minerals.push_back({"锡石", "唯一的锡矿石", 3, 18200.0, false, BROWN, "金属矿石", 4, "mine", true, "kg", 1000});
        minerals.push_back({"辰砂", "汞的主要矿石", 4, 35500.0, false, RED, "金属矿石", 4, "mine", true, "g", 1});
        minerals.push_back({"绿柱石", "铍的主要矿石", 3, 8500.0, false, GREEN, "金属矿石", 4, "mine", true, "kg", 1000});

        // 宝石与玉石
        minerals.push_back({"红宝石", "红色宝石级刚玉", 5, 8500.0, false, RED, "宝石", 6, "mine", true, "ct", 0.2});
        minerals.push_back({"蓝宝石", "蓝色宝石级刚玉", 5, 5200.0, false, BLUE, "宝石", 6, "mine", true, "ct", 0.2});
        minerals.push_back({"祖母绿", "翠绿色绿柱石", 5, 6800.0, false, GREEN, "宝石", 6, "mine", true, "ct", 0.2});
        minerals.push_back({"海蓝宝石", "天蓝色绿柱石", 4, 1200.0, false, CYAN, "宝石", 5, "mine", true, "ct", 0.2});
        minerals.push_back({"金绿宝石", "亚历山大石变种", 5, 4500.0, false, GREEN, "宝石", 6, "mine", true, "ct", 0.2});
        minerals.push_back({"托帕石", "颜色多样的宝石", 3, 350.0, false, YELLOW, "宝石", 4, "mine", true, "ct", 0.2});
        minerals.push_back({"电气石", "颜色丰富的宝石", 3, 420.0, false, MAGENTA, "宝石", 4, "mine", true, "ct", 0.2});
        minerals.push_back({"橄榄石", "黄绿色宝石", 3, 280.0, false, GREEN, "宝石", 4, "mine", true, "ct", 0.2});
        minerals.push_back({"锆石", "高色散宝石", 3, 320.0, false, BLUE, "宝石", 4, "mine", true, "ct", 0.2});
        minerals.push_back({"石榴石", "红色绿色宝石", 2, 150.0, false, RED, "宝石", 3, "mine", true, "ct", 0.2});
        minerals.push_back({"尖晶石", "颜色丰富的宝石", 3, 380.0, false, RED, "宝石", 4, "mine", true, "ct", 0.2});
        minerals.push_back({"月光石", "具有月光效应", 3, 280.0, false, WHITE, "宝石", 4, "mine", true, "ct", 0.2});
        minerals.push_back({"翡翠", "硬玉集合体", 5, 3500.0, false, GREEN, "玉石", 6, "mine", true, "g", 1});
        minerals.push_back({"和田玉", "软玉集合体", 4, 850.0, false, WHITE, "玉石", 5, "mine", true, "g", 1});
        minerals.push_back({"玛瑙", "纹带构造石英", 2, 25.0, false, RED, "玉石", 3, "mine", true, "g", 1});
        minerals.push_back({"水晶", "无色透明石英", 2, 15.0, false, WHITE, "玉石", 2, "mine", true, "g", 1});
        minerals.push_back({"紫晶", "紫色水晶", 3, 45.0, false, PURPLE, "玉石", 3, "mine", true, "g", 1});
        minerals.push_back({"绿松石", "天蓝色玉石", 3, 120.0, false, CYAN, "玉石", 4, "mine", true, "g", 1});
        minerals.push_back({"青金石", "深蓝色玉石", 3, 95.0, false, BLUE, "玉石", 4, "mine", true, "g", 1});

        // 工业与非金属矿物
        minerals.push_back({"石盐", "食盐主要来源", 1, 5.0, false, WHITE, "工业矿物", 1, "mine", true, "kg", 1000});
        minerals.push_back({"萤石", "氟的主要来源", 2, 5000.0, false, PURPLE, "工业矿物", 3, "mine", true, "kg", 1000});
        minerals.push_back({"重晶石", "钻井泥浆加重剂", 2, 600.0, false, WHITE, "工业矿物", 3, "mine", true, "kg", 1000});
        minerals.push_back({"石墨", "润滑剂和电极", 2, 2500.0, false, BLACK, "工业矿物", 3, "mine", true, "kg", 1000});
        minerals.push_back({"金刚石", "最硬的物质", 5, 25000.0, false, WHITE, "宝石", 7, "mine", true, "ct", 0.2});
        minerals.push_back({"自然金", "重要的贵金属", 5, 380.0, false, GOLD, "金属矿石", 6, "mine", true, "g", 1});
        minerals.push_back({"自然银", "重要的贵金属", 4, 5.2, false, SILVER, "金属矿石", 5, "mine", true, "g", 1});
        minerals.push_back({"自然铜", "次要的铜矿石", 3, 4.8, false, RED, "金属矿石", 4, "mine", true, "g", 1});
        minerals.push_back({"自然硫", "硫酸和化肥原料", 2, 300.0, false, YELLOW, "工业矿物", 2, "mine", true, "kg", 1000});

        // 高级稀有矿物
        minerals.push_back({"铂金矿石", "极其稀有的白色金属", 5, 220.0, false, SILVER, "金属矿石", 7, "mine", true, "g", 1});
        minerals.push_back({"秘银矿石", "魔法金属", 5, 450.0, false, BLUE, "传说", 8, "mine", true, "g", 1});
        minerals.push_back({"精金矿石", "传说中的坚硬金属", 5, 680.0, false, RED, "传说", 9, "mine", true, "g", 1});

        // 镐子数据
        allPickaxes.clear();

        // 基础镐子
        allPickaxes.push_back(Pickaxe("木镐", 1, 30, 30, 0, 0, 300, 1, {{"木材", 5000}}));
        allPickaxes.push_back(Pickaxe("石镐", 2, 50, 50, 10, 5, 250, 1, {{"石头", 8000}, {"木材", 2000}}));
        allPickaxes.push_back(Pickaxe("铜镐", 2, 60, 60, 15, 8, 230, 1, {{"黄铜矿", 3000}, {"木材", 1500}}));

        // 中级镐子
        allPickaxes.push_back(Pickaxe("铁镐", 3, 80, 80, 20, 10, 200, 1, {{"赤铁矿", 5000}, {"石头", 3000}}));
        allPickaxes.push_back(Pickaxe("银镐", 4, 100, 100, 30, 15, 180, 1, {{"自然银", 800}, {"赤铁矿", 2000}}));
        allPickaxes.push_back(Pickaxe("金镐", 5, 120, 120, 40, 20, 150, 2, {{"自然金", 500}, {"自然银", 500}}));
        allPickaxes.push_back(Pickaxe("铬镐", 5, 130, 130, 45, 22, 140, 2, {{"铬铁矿", 2000}, {"自然金", 200}}));

        // 高级镐子
        allPickaxes.push_back(Pickaxe("水晶镐", 6, 150, 150, 50, 25, 130, 2, {{"水晶", 1000}, {"铬铁矿", 1500}}));
        allPickaxes.push_back(Pickaxe("宝石镐", 6, 160, 160, 55, 28, 120, 2, {{"红宝石", 50}, {"水晶", 800}}));
        allPickaxes.push_back(Pickaxe("钻石镐", 7, 200, 200, 60, 30, 100, 2, {{"金刚石", 30}, {"水晶", 1500}}));

        // 顶级镐子
        allPickaxes.push_back(Pickaxe("铂金镐", 7, 220, 220, 65, 35, 90, 3, {{"铂金矿石", 400}, {"金刚石", 20}}));
        allPickaxes.push_back(Pickaxe("秘银镐", 8, 250, 250, 70, 40, 80, 3, {{"秘银矿石", 300}, {"铂金矿石", 200}}));
        allPickaxes.push_back(Pickaxe("精金镐", 9, 300, 300, 80, 50, 70, 3, {{"精金矿石", 200}, {"秘银矿石", 400}}));
        allPickaxes.push_back(Pickaxe("神圣镐", 10, 400, 400, 100, 60, 50, 4, {{"精金矿石", 500}, {"金刚石", 50}, {"红宝石", 30}}));
    }

    // 显示进度条
    void ShowProgressBar(int current, int total, const string& operation) {
        int barWidth = 50;
        float progress = (float)current / total;
        int pos = barWidth * progress;

        cout << operation << " [";
        for (int i = 0; i < barWidth; ++i) {
            if (i < pos) cout << "=";
            else if (i == pos) cout << ">";
            else cout << " ";
        }
        cout << "] " << int(progress * 100.0) << " %\r";
        cout.flush();
    }

    // 保存字符串
    void SaveString(ofstream& file, const string& str) {
        int length = str.length();
        file.write((char*)&length, sizeof(length));
        file.write(str.c_str(), length);
    }

    // 加载字符串
    string LoadString(ifstream& file) {
        int length;
        file.read((char*)&length, sizeof(length));
        string str(length, ' ');
        file.read(&str[0], length);
        return str;
    }

    // 保存镐子
    void SavePickaxe(ofstream& file, const Pickaxe& pickaxe) {
        SaveString(file, pickaxe.name);
        file.write((char*)&pickaxe.level, sizeof(pickaxe.level));
        file.write((char*)&pickaxe.durability, sizeof(pickaxe.durability));
        file.write((char*)&pickaxe.maxDurability, sizeof(pickaxe.maxDurability));
        file.write((char*)&pickaxe.efficiency, sizeof(pickaxe.efficiency));
        file.write((char*)&pickaxe.luck, sizeof(pickaxe.luck));
        file.write((char*)&pickaxe.speed, sizeof(pickaxe.speed));
        file.write((char*)&pickaxe.multiMine, sizeof(pickaxe.multiMine));

        int materialCount = pickaxe.requiredMinerals.size();
        file.write((char*)&materialCount, sizeof(materialCount));
        for(const auto& material : pickaxe.requiredMinerals) {
            SaveString(file, material.first);
            file.write((char*)&material.second, sizeof(material.second));
        }
    }

    // 加载镐子
    Pickaxe LoadPickaxe(ifstream& file) {
        Pickaxe pickaxe;
        pickaxe.name = LoadString(file);
        file.read((char*)&pickaxe.level, sizeof(pickaxe.level));
        file.read((char*)&pickaxe.durability, sizeof(pickaxe.durability));
        file.read((char*)&pickaxe.maxDurability, sizeof(pickaxe.maxDurability));
        file.read((char*)&pickaxe.efficiency, sizeof(pickaxe.efficiency));
        file.read((char*)&pickaxe.luck, sizeof(pickaxe.luck));
        file.read((char*)&pickaxe.speed, sizeof(pickaxe.speed));
        file.read((char*)&pickaxe.multiMine, sizeof(pickaxe.multiMine));

        int materialCount;
        file.read((char*)&materialCount, sizeof(materialCount));
        pickaxe.requiredMinerals.clear();
        for(int i = 0; i < materialCount; i++) {
            string materialName = LoadString(file);
            double materialWeight;
            file.read((char*)&materialWeight, sizeof(materialWeight));
            pickaxe.requiredMinerals.push_back({materialName, materialWeight});
        }

        return pickaxe;
    }

    // 初始化新游戏
    void InitializeNewGame() {
        player.money = 500;
        player.level = 1;
        player.experience = 0;
        player.maxEnergy = 100;
        player.currentEnergy = 100;
        player.currentPickaxe = allPickaxes[0];
        player.debt = 0;
        player.totalDays = 1;
        player.processingSkill = 1;
        dayCount = 1;
        marketRefreshDays = 3;

        player.unlockedPickaxeNames.push_back("木镐");
        player.mineralsMined.clear();
        player.purchasedItems.clear();

        // 添加初始材料
        Mineral wood = GetMineralByName("木材");
        wood.unitWeight = 5000;
        player.inventory.push_back(wood);

        Mineral stone = GetMineralByName("石头");
        stone.unitWeight = 3000;
        player.inventory.push_back(stone);

        InitializeAchievements();
        InitializeMarket();
    }

    // 根据名称获取矿物
    Mineral GetMineralByName(const string& name) {
        for(const auto& mineral : minerals) {
            if(mineral.name == name) {
                return mineral;
            }
        }
        return minerals[0];
    }

    // 优化的保存系统
    void SaveGame() {
        system("cls");
        cout << CYAN << "===== 保存游戏中... =====" << RESET << endl;

        ofstream saveFile("mining_game_save.dat", ios::binary);
        if(saveFile.is_open()) {
            string version = "MINING_GAME_V8"; // 更新版本号
            int versionLength = version.length();
            saveFile.write((char*)&versionLength, sizeof(versionLength));
            saveFile.write(version.c_str(), versionLength);

            ShowProgressBar(1, 14, "保存游戏数据");
            Sleep(100);

            saveFile.write((char*)&player.money, sizeof(player.money));
            saveFile.write((char*)&player.level, sizeof(player.level));
            saveFile.write((char*)&player.experience, sizeof(player.experience));
            saveFile.write((char*)&player.maxEnergy, sizeof(player.maxEnergy));
            saveFile.write((char*)&player.currentEnergy, sizeof(player.currentEnergy));
            saveFile.write((char*)&player.debt, sizeof(player.debt));
            saveFile.write((char*)&player.totalDays, sizeof(player.totalDays));
            saveFile.write((char*)&player.processingSkill, sizeof(player.processingSkill));
            saveFile.write((char*)&dayCount, sizeof(dayCount));
            saveFile.write((char*)&marketRefreshDays, sizeof(marketRefreshDays));

            ShowProgressBar(2, 14, "保存玩家数据");
            Sleep(100);

            SavePickaxe(saveFile, player.currentPickaxe);

            ShowProgressBar(3, 14, "保存镐子数据");
            Sleep(100);

            int mineralCount = minerals.size();
            saveFile.write((char*)&mineralCount, sizeof(mineralCount));
            for(int i = 0; i < mineralCount; i++) {
                saveFile.write((char*)&minerals[i].discovered, sizeof(minerals[i].discovered));
            }

            ShowProgressBar(4, 14, "保存矿物状态");
            Sleep(100);

            map<string, double> inventoryWeights;
            for(const auto& mineral : player.inventory) {
                inventoryWeights[mineral.name] += mineral.unitWeight;
            }

            int uniqueItems = inventoryWeights.size();
            saveFile.write((char*)&uniqueItems, sizeof(uniqueItems));

            int itemIndex = 0;
            for(const auto& pair : inventoryWeights) {
                SaveString(saveFile, pair.first);
                saveFile.write((char*)&pair.second, sizeof(pair.second));

                itemIndex++;
                ShowProgressBar(4 + (itemIndex * 3 / uniqueItems), 14, "保存背包物品");
            }

            ShowProgressBar(7, 14, "保存加工物品");
            Sleep(100);

            int processedCount = player.processedInventory.size();
            saveFile.write((char*)&processedCount, sizeof(processedCount));

            for(int i = 0; i < processedCount; i++) {
                const auto& item = player.processedInventory[i];
                SaveString(saveFile, item.name);
                SaveString(saveFile, item.originalName);
                saveFile.write((char*)&item.quality, sizeof(item.quality));
                saveFile.write((char*)&item.value, sizeof(item.value));
                saveFile.write((char*)&item.weight, sizeof(item.weight));
                SaveString(saveFile, item.colorCode);
                SaveString(saveFile, item.description);
                SaveString(saveFile, item.unit);
            }

            ShowProgressBar(8, 14, "保存已解锁镐子");
            Sleep(100);

            int unlockedCount = player.unlockedPickaxeNames.size();
            saveFile.write((char*)&unlockedCount, sizeof(unlockedCount));

            for(const auto& name : player.unlockedPickaxeNames) {
                SaveString(saveFile, name);
            }

            ShowProgressBar(9, 14, "保存成就数据");
            Sleep(100);

            int achievementCount = player.achievements.size();
            saveFile.write((char*)&achievementCount, sizeof(achievementCount));

            for(const auto& achievement : player.achievements) {
                SaveString(saveFile, achievement.name);
                SaveString(saveFile, achievement.description);
                saveFile.write((char*)&achievement.unlocked, sizeof(achievement.unlocked));
                SaveString(saveFile, achievement.rewardType);
                saveFile.write((char*)&achievement.rewardValue, sizeof(achievement.rewardValue));
                SaveString(saveFile, achievement.requiredMineral);
                saveFile.write((char*)&achievement.requiredAmount, sizeof(achievement.requiredAmount));
                saveFile.write((char*)&achievement.requiredLevel, sizeof(achievement.requiredLevel));
                saveFile.write((char*)&achievement.requiredMoney, sizeof(achievement.requiredMoney));
            }

            ShowProgressBar(10, 14, "保存矿物挖掘记录");
            Sleep(100);

            int mineralsMinedCount = player.mineralsMined.size();
            saveFile.write((char*)&mineralsMinedCount, sizeof(mineralsMinedCount));

            for(const auto& pair : player.mineralsMined) {
                SaveString(saveFile, pair.first);
                saveFile.write((char*)&pair.second, sizeof(pair.second));
            }

            ShowProgressBar(11, 14, "保存市场数据");
            Sleep(100);

            int marketItemsCount = marketItems.size();
            saveFile.write((char*)&marketItemsCount, sizeof(marketItemsCount));

            for(const auto& item : marketItems) {
                SaveString(saveFile, item.mineralName);
                saveFile.write((char*)&item.priceMultiplier, sizeof(item.priceMultiplier));
                saveFile.write((char*)&item.stock, sizeof(item.stock));
                saveFile.write((char*)&item.isSpecial, sizeof(item.isSpecial));
                saveFile.write((char*)&item.availableDays, sizeof(item.availableDays));
            }

            ShowProgressBar(12, 14, "保存购买商品数据");
            Sleep(100);

            int purchasedItemsCount = player.purchasedItems.size();
            saveFile.write((char*)&purchasedItemsCount, sizeof(purchasedItemsCount));

            for(const auto& item : player.purchasedItems) {
                SaveString(saveFile, item.mineralName);
                saveFile.write((char*)&item.priceMultiplier, sizeof(item.priceMultiplier));
                saveFile.write((char*)&item.stock, sizeof(item.stock));
                saveFile.write((char*)&item.isSpecial, sizeof(item.isSpecial));
                saveFile.write((char*)&item.availableDays, sizeof(item.availableDays));
                saveFile.write((char*)&item.purchasePrice, sizeof(item.purchasePrice));
                saveFile.write((char*)&item.purchaseWeight, sizeof(item.purchaseWeight));
            }

            saveFile.close();

            ShowProgressBar(14, 14, "保存完成");
            cout << endl << GREEN << "游戏已保存!" << RESET << endl;
        } else {
            cout << RED << "保存失败!无法创建保存文件。" << RESET << endl;
        }
        Sleep(1000);
    }

    // 优化的加载系统
    void LoadGame() {
        system("cls");
        cout << CYAN << "===== 加载游戏中... =====" << RESET << endl;

        ifstream saveFile("mining_game_save.dat", ios::binary);
        if(saveFile.is_open()) {
            int versionLength;
            saveFile.read((char*)&versionLength, sizeof(versionLength));
            string version(versionLength, ' ');
            saveFile.read(&version[0], versionLength);

            if(version != "MINING_GAME_V8") {
                cout << RED << "保存文件版本不兼容!开始新游戏..." << RESET << endl;
                saveFile.close();
                InitializeNewGame();
                Sleep(1000);
                return;
            }

            ShowProgressBar(1, 14, "加载游戏数据");
            Sleep(100);

            saveFile.read((char*)&player.money, sizeof(player.money));
            saveFile.read((char*)&player.level, sizeof(player.level));
            saveFile.read((char*)&player.experience, sizeof(player.experience));
            saveFile.read((char*)&player.maxEnergy, sizeof(player.maxEnergy));
            saveFile.read((char*)&player.currentEnergy, sizeof(player.currentEnergy));
            saveFile.read((char*)&player.debt, sizeof(player.debt));
            saveFile.read((char*)&player.totalDays, sizeof(player.totalDays));
            saveFile.read((char*)&player.processingSkill, sizeof(player.processingSkill));
            saveFile.read((char*)&dayCount, sizeof(dayCount));
            saveFile.read((char*)&marketRefreshDays, sizeof(marketRefreshDays));

            ShowProgressBar(2, 14, "加载玩家数据");
            Sleep(100);

            player.currentPickaxe = LoadPickaxe(saveFile);

            ShowProgressBar(3, 14, "加载镐子数据");
            Sleep(100);

            int mineralCount;
            saveFile.read((char*)&mineralCount, sizeof(mineralCount));
            for(int i = 0; i < mineralCount && i < minerals.size(); i++) {
                saveFile.read((char*)&minerals[i].discovered, sizeof(minerals[i].discovered));
            }

            ShowProgressBar(4, 14, "加载矿物状态");
            Sleep(100);

            player.inventory.clear();
            int uniqueItems;
            saveFile.read((char*)&uniqueItems, sizeof(uniqueItems));

            for(int i = 0; i < uniqueItems; i++) {
                string itemName = LoadString(saveFile);
                double weight;
                saveFile.read((char*)&weight, sizeof(weight));

                Mineral mineral = GetMineralByName(itemName);
                mineral.unitWeight = weight;
                player.inventory.push_back(mineral);

                ShowProgressBar(4 + (i * 3 / uniqueItems), 14, "加载背包物品");
            }

            ShowProgressBar(7, 14, "加载加工物品");
            Sleep(100);

            player.processedInventory.clear();
            int processedCount;
            saveFile.read((char*)&processedCount, sizeof(processedCount));

            for(int i = 0; i < processedCount; i++) {
                ProcessedItem item;
                item.name = LoadString(saveFile);
                item.originalName = LoadString(saveFile);
                saveFile.read((char*)&item.quality, sizeof(item.quality));
                saveFile.read((char*)&item.value, sizeof(item.value));
                saveFile.read((char*)&item.weight, sizeof(item.weight));
                item.colorCode = LoadString(saveFile);
                item.description = LoadString(saveFile);
                item.unit = LoadString(saveFile);

                player.processedInventory.push_back(item);
            }

            ShowProgressBar(8, 14, "加载已解锁镐子");
            Sleep(100);

            player.unlockedPickaxeNames.clear();
            int unlockedCount;
            saveFile.read((char*)&unlockedCount, sizeof(unlockedCount));

            for(int i = 0; i < unlockedCount; i++) {
                string pickaxeName = LoadString(saveFile);
                player.unlockedPickaxeNames.push_back(pickaxeName);
            }

            ShowProgressBar(9, 14, "加载成就数据");
            Sleep(100);

            player.achievements.clear();
            int achievementCount;
            saveFile.read((char*)&achievementCount, sizeof(achievementCount));

            for(int i = 0; i < achievementCount; i++) {
                Achievement achievement("", "", "", 0);
                achievement.name = LoadString(saveFile);
                achievement.description = LoadString(saveFile);
                saveFile.read((char*)&achievement.unlocked, sizeof(achievement.unlocked));
                achievement.rewardType = LoadString(saveFile);
                saveFile.read((char*)&achievement.rewardValue, sizeof(achievement.rewardValue));
                achievement.requiredMineral = LoadString(saveFile);
                saveFile.read((char*)&achievement.requiredAmount, sizeof(achievement.requiredAmount));
                saveFile.read((char*)&achievement.requiredLevel, sizeof(achievement.requiredLevel));
                saveFile.read((char*)&achievement.requiredMoney, sizeof(achievement.requiredMoney));

                player.achievements.push_back(achievement);
            }

            ShowProgressBar(10, 14, "加载矿物挖掘记录");
            Sleep(100);

            player.mineralsMined.clear();
            int mineralsMinedCount;
            saveFile.read((char*)&mineralsMinedCount, sizeof(mineralsMinedCount));

            for(int i = 0; i < mineralsMinedCount; i++) {
                string mineralName = LoadString(saveFile);
                double amount;
                saveFile.read((char*)&amount, sizeof(amount));
                player.mineralsMined[mineralName] = amount;
            }

            ShowProgressBar(11, 14, "加载市场数据");
            Sleep(100);

            marketItems.clear();
            int marketItemsCount;
            saveFile.read((char*)&marketItemsCount, sizeof(marketItemsCount));

            for(int i = 0; i < marketItemsCount; i++) {
                MarketItem item("", 1.0);
                item.mineralName = LoadString(saveFile);
                saveFile.read((char*)&item.priceMultiplier, sizeof(item.priceMultiplier));
                saveFile.read((char*)&item.stock, sizeof(item.stock));
                saveFile.read((char*)&item.isSpecial, sizeof(item.isSpecial));
                saveFile.read((char*)&item.availableDays, sizeof(item.availableDays));

                marketItems.push_back(item);
            }

            ShowProgressBar(12, 14, "加载购买商品数据");
            Sleep(100);

            player.purchasedItems.clear();
            int purchasedItemsCount;
            saveFile.read((char*)&purchasedItemsCount, sizeof(purchasedItemsCount));

            for(int i = 0; i < purchasedItemsCount; i++) {
                MarketItem item("", 1.0);
                item.mineralName = LoadString(saveFile);
                saveFile.read((char*)&item.priceMultiplier, sizeof(item.priceMultiplier));
                saveFile.read((char*)&item.stock, sizeof(item.stock));
                saveFile.read((char*)&item.isSpecial, sizeof(item.isSpecial));
                saveFile.read((char*)&item.availableDays, sizeof(item.availableDays));
                saveFile.read((char*)&item.purchasePrice, sizeof(item.purchasePrice));
                saveFile.read((char*)&item.purchaseWeight, sizeof(item.purchaseWeight));

                player.purchasedItems.push_back(item);
            }

            saveFile.close();

            ShowProgressBar(14, 14, "加载完成");
            cout << endl << GREEN << "游戏加载成功!" << RESET << endl;
        } else {
            cout << YELLOW << "未找到保存文件,开始新游戏..." << RESET << endl;
            InitializeNewGame();
        }
        Sleep(1000);
    }

    void ShowMainMenu() {
        while(true) {
            system("cls");
            cout << CYAN << "===== 真实矿物挖掘 =====" << RESET << endl;
            cout << "第 " << dayCount << " 天 (总计: " << player.totalDays << " 天)" << endl;
            cout << "资金: " << GREEN << FormatMoney(player.money) << RESET;
            if(player.debt > 0) {
                cout << " | 负债: " << RED << FormatMoney(player.debt) << RESET;
            }
            cout << endl;
            cout << "等级: " << player.level << " | 经验: " << player.experience << "/" << (player.level * 100) << endl;
            cout << "能量: " << player.currentEnergy << "/" << player.maxEnergy << endl;
            cout << "加工技能: " << player.processingSkill << "级" << endl;
            cout << "当前镐: " << YELLOW << player.currentPickaxe.name << RESET;
            cout << " | 耐久: " << player.currentPickaxe.durability << "/" << player.currentPickaxe.maxDurability;
            if(player.currentPickaxe.multiMine > 1) {
                cout << " | 多重挖掘: x" << player.currentPickaxe.multiMine;
            }
            cout << endl;
            cout << "======================" << endl;
            cout << "1. 去采矿" << endl;
            cout << "2. 去砍树" << endl;
            cout << "3. 加工与切石" << endl;
            cout << "4. 查看矿物图鉴" << endl;
            cout << "5. 查看背包" << endl;
            cout << "6. 制作/修复镐子" << endl;
            cout << "7. 矿物市场" << endl;
            cout << "8. 成就系统" << endl;
            cout << "9. 休息一天" << endl;
            cout << "10. 偿还债务" << endl;
            cout << "11. 保存游戏" << endl;
            cout << "0. 退出游戏" << endl;
            cout << "选择: ";

            int choice;
            cin >> choice;

            switch(choice) {
                case 1: MineMinerals(); break;
                case 2: ChopWood(); break;
                case 3: ProcessingMenu(); break;
                case 4: ShowMineralCatalog(); break;
                case 5: ShowInventory(); break;
                case 6: CraftPickaxeMenu(); break;
                case 7: ShowMarket(); break;
                case 8: ShowAchievements(); break;
                case 9: Rest(); break;
                case 10: PayDebt(); break;
                case 11: SaveGame(); break;
                case 0:
                    SaveGame();
                    cout << "游戏已保存,再见!" << endl;
                    return;
                default:
                    cout << RED << "无效选择!" << RESET << endl;
                    Sleep(500);
            }
        }
    }

    // 计算每日生活费用
    double CalculateLivingCost() {
        return 100.0 + (player.level * 15.0);
    }

    // 计算挖掘获得的矿物重量
    double CalculateMineralWeight(const Mineral& mineral) {
        double baseWeight = 0;

        if (mineral.unit == "ct") {
            // 宝石类:0.1-5克拉
            baseWeight = 0.1 + (rand() % 50) * 0.1;
        } else if (mineral.unit == "g") {
            // 贵金属:1-100克
            baseWeight = 1 + (rand() % 100);
        } else {
            // 普通矿物:100-5000克
            baseWeight = 100 + (rand() % 4900);
        }

        double efficiencyBonus = 1.0 + (player.currentPickaxe.efficiency * 0.01);
        double rarityMultiplier = 1.0 / mineral.rarity;

        return baseWeight * efficiencyBonus * rarityMultiplier;
    }

    void MineMinerals() {
        if(player.currentEnergy <= 0) {
            cout << RED << "能量不足,需要休息!" << RESET << endl;
            Sleep(1000);
            return;
        }

        if(player.currentPickaxe.durability <= 0) {
            cout << RED << "镐子已损坏,需要修复或制作新镐子!" << RESET << endl;
            Sleep(1000);
            return;
        }

        system("cls");
        cout << YELLOW << "===== 采矿中... =====" << RESET << endl;

        int animationSpeed = player.currentPickaxe.speed / 2;
        for(int i = 0; i < 2; i++) {
            cout << "挖掘";
            for(int j = 0; j < 2; j++) {
                cout << ".";
                Sleep(animationSpeed);
            }
            cout << endl;
        }

        player.currentEnergy -= 10;
        player.currentPickaxe.durability -= 1;

        int successChance = 30 + player.currentPickaxe.efficiency;
        if(rand() % 100 > successChance) {
            cout << RED << "这次挖掘没有找到任何矿物..." << RESET << endl;
            Sleep(1000);
            return;
        }

        int mineralsFound = 0;
        double totalValue = 0;
        int totalExp = 0;

        for(int i = 0; i < player.currentPickaxe.multiMine; i++) {
            int mineralIndex = SelectMineral("mine");
            if(mineralIndex == -1) {
                cout << YELLOW << "这个深度的矿物需要更高级的镐子才能挖掘!" << RESET << endl;
                continue;
            }

            Mineral foundMineral = minerals[mineralIndex];
            minerals[mineralIndex].discovered = true;

            double weight = CalculateMineralWeight(foundMineral);
            foundMineral.unitWeight = weight;
            player.inventory.push_back(foundMineral);

            // 记录挖掘数量
            player.mineralsMined[foundMineral.name] += weight;

            double value = CalculateMineralValue(foundMineral, weight);
            totalValue += value;

            int expGained = foundMineral.rarity * 10;
            totalExp += expGained;

            mineralsFound++;

            cout << foundMineral.colorCode << "你找到了: " << foundMineral.name << "!" << RESET << endl;
            cout << "重量: " << FormatWeight(weight) << " | 价值: " << GREEN << FormatMoney(value) << RESET << endl;
        }

        if(mineralsFound == 0) {
            cout << YELLOW << "没有找到当前镐子可以挖掘的矿物..." << RESET << endl;
        } else {
            player.money += totalValue;
            player.experience += totalExp;

            cout << "总计价值: " << GREEN << FormatMoney(totalValue) << RESET << endl;
            cout << "获得经验: " << totalExp << endl;
        }

        cout << "镐子耐久: " << player.currentPickaxe.durability << "/" << player.currentPickaxe.maxDurability << endl;

        if(player.currentPickaxe.multiMine > 1 && mineralsFound > 0) {
            cout << "多重挖掘: " << mineralsFound << " 个矿物" << endl;
        }

        CheckLevelUp();
        CheckAchievements();

        cout << "\n按任意键继续..." << endl;
        cin.ignore();
        cin.get();
    }

    void ChopWood() {
        if(player.currentEnergy <= 0) {
            cout << RED << "能量不足,需要休息!" << RESET << endl;
            Sleep(1000);
            return;
        }

        system("cls");
        cout << GREEN << "===== 砍树中... =====" << RESET << endl;

        for(int i = 0; i < 2; i++) {
            cout << "砍树";
            for(int j = 0; j < 2; j++) {
                cout << ".";
                Sleep(200);
            }
            cout << endl;
        }

        player.currentEnergy -= 5;

        if(rand() % 100 > 20) {
            cout << RED << "这次砍树没有获得任何材料..." << RESET << endl;
            Sleep(1000);
            return;
        }

        for(int i = 0; i < minerals.size(); i++) {
            if(minerals[i].name == "木材") {
                Mineral wood = minerals[i];
                double weight = 1000 + (rand() % 4000);
                wood.unitWeight = weight;
                player.inventory.push_back(wood);

                // 记录挖掘数量
                player.mineralsMined["木材"] += weight;

                double value = CalculateMineralValue(wood, weight);
                cout << BROWN << "你获得了: 木材!" << RESET << endl;
                cout << "重量: " << FormatWeight(weight) << " | 价值: " << GREEN << FormatMoney(value) << RESET << endl;
                break;
            }
        }

        if(rand() % 100 < 30) {
            for(int i = 0; i < minerals.size(); i++) {
                if(minerals[i].name == "石头") {
                    Mineral stone = minerals[i];
                    double weight = 500 + (rand() % 2000);
                    stone.unitWeight = weight;
                    player.inventory.push_back(stone);

                    // 记录挖掘数量
                    player.mineralsMined["石头"] += weight;

                    cout << GRAY << "你获得了: 石头!" << RESET << endl;
                    break;
                }
            }
        }

        if(rand() % 100 < 15) {
            for(int i = 0; i < minerals.size(); i++) {
                if(minerals[i].name == "黏土") {
                    Mineral clay = minerals[i];
                    double weight = 200 + (rand() % 800);
                    clay.unitWeight = weight;
                    player.inventory.push_back(clay);

                    // 记录挖掘数量
                    player.mineralsMined["黏土"] += weight;

                    cout << BROWN << "你获得了: 黏土!" << RESET << endl;
                    break;
                }
            }
        }

        int expGained = 5;
        double moneyGained = 3.5;
        player.experience += expGained;
        player.money += moneyGained;

        cout << "获得经验: " << expGained << endl;
        cout << "获得资金: " << GREEN << FormatMoney(moneyGained) << RESET << endl;

        CheckLevelUp();
        CheckAchievements();

        cout << "\n按任意键继续..." << endl;
        cin.ignore();
        cin.get();
    }

    void ProcessingMenu() {
        while(true) {
            system("cls");
            cout << CYAN << "===== 加工与切石 =====" << RESET << endl;
            cout << "加工技能等级: " << player.processingSkill << endl;
            cout << "成功率: " << (50 + player.processingSkill * 5) << "%" << endl;
            cout << "=====================" << endl;
            cout << "1. 加工矿石/木材" << endl;
            cout << "2. 切石" << endl;
            cout << "3. 查看加工物品" << endl;
            cout << "4. 升级加工技能 (消耗 "<<500*player.processingSkill<<"元)" << endl;
            cout << "0. 返回" << endl;
            cout << "选择: ";

            int choice;
            cin >> choice;

            switch(choice) {
                case 1: ProcessMaterials(); break;
                case 2: CutStone(); break;
                case 3: ShowProcessedInventory(); break;
                case 4: UpgradeProcessingSkill(); break;
                case 0: return;
                default:
                    cout << RED << "无效选择!" << RESET << endl;
                    Sleep(500);
            }
        }
    }

    void ProcessMaterials() {
        if(player.currentEnergy < 5) {
            cout << RED << "能量不足,需要休息!" << RESET << endl;
            Sleep(1000);
            return;
        }

        vector<int> processableIndices;
        system("cls");
        cout << CYAN << "===== 选择要加工的物品 =====" << RESET << endl;

        for(int i = 0; i < player.inventory.size(); i++) {
            for(const auto& mineral : minerals) {
                if(mineral.name == player.inventory[i].name && mineral.processable) {
                    double value = CalculateMineralValue(mineral, player.inventory[i].unitWeight);

                    cout << i + 1 << ". " << mineral.colorCode << mineral.name << RESET;
                    cout << " - 重量: " << FormatWeight(player.inventory[i].unitWeight);
                    cout << " - 价值: " << GREEN << FormatMoney(value) << RESET << endl;
                    processableIndices.push_back(i);
                    break;
                }
            }
        }

        if(processableIndices.empty()) {
            cout << "没有可加工的物品!" << endl;
            Sleep(1000);
            return;
        }

        cout << "0. 返回" << endl;
        cout << "选择要加工的物品: ";

        int choice;
        cin >> choice;

        if(choice == 0) return;

        if(choice < 1 || choice > processableIndices.size()) {
            cout << RED << "无效选择!" << RESET << endl;
            Sleep(1000);
            return;
        }

        int itemIndex = processableIndices[choice - 1];
        Mineral selectedMineral = player.inventory[itemIndex];

        player.currentEnergy -= 5;

        system("cls");
        cout << CYAN << "===== 加工中... =====" << RESET << endl;
        for(int i = 0; i < 2; i++) {
            cout << "加工";
            for(int j = 0; j < 2; j++) {
                cout << ".";
                Sleep(200);
            }
            cout << endl;
        }

        int successRate = 50 + player.processingSkill * 5;
        bool success = (rand() % 100) < successRate;

        if(!success) {
            cout << RED << "加工失败!物品损坏了..." << RESET << endl;
            player.inventory.erase(player.inventory.begin() + itemIndex);
            Sleep(1000);
            return;
        }

        int quality = CalculateQuality();
        double originalValue = CalculateMineralValue(selectedMineral, selectedMineral.unitWeight);
        double newValue = originalValue * (0.8 + quality * 0.1); // 品质影响价值
        double newWeight = selectedMineral.unitWeight * 0.8; // 加工有重量损失

        ProcessedItem processedItem;
        processedItem.originalName = selectedMineral.name;
        processedItem.quality = quality;
        processedItem.weight = newWeight;
        processedItem.unit = selectedMineral.unit;
        processedItem.value = newValue;

        switch(quality) {
            case 1:
                processedItem.name = "劣质的 " + selectedMineral.name;
                processedItem.colorCode = GRAY;
                processedItem.description = "加工粗糙的" + selectedMineral.name;
                break;
            case 2:
                processedItem.name = "普通的 " + selectedMineral.name;
                processedItem.colorCode = WHITE;
                processedItem.description = "普通加工的" + selectedMineral.name;
                break;
            case 3:
                processedItem.name = "优质的 " + selectedMineral.name;
                processedItem.colorCode = GREEN;
                processedItem.description = "精心加工的" + selectedMineral.name;
                break;
            case 4:
                processedItem.name = "精美的 " + selectedMineral.name;
                processedItem.colorCode = BLUE;
                processedItem.description = "精美加工的" + selectedMineral.name;
                break;
            case 5:
                processedItem.name = "完美的 " + selectedMineral.name;
                processedItem.colorCode = GOLD;
                processedItem.description = "完美加工的" + selectedMineral.name;
                break;
        }

        player.inventory.erase(player.inventory.begin() + itemIndex);
        player.processedInventory.push_back(processedItem);

        cout << processedItem.colorCode << "加工成功!获得了: " << processedItem.name << RESET << endl;
        cout << "品质: " << GetQualityStars(quality) << endl;
        cout << "重量: " << FormatWeight(newWeight) << endl;
        cout << "价值: " << GREEN << FormatMoney(processedItem.value) << RESET << endl;

        player.experience += 5;
        CheckLevelUp();

        cout << "\n按任意键继续..." << endl;
        cin.ignore();
        cin.get();
    }

    void CutStone() {
        if(player.currentEnergy < 5) {
            cout << RED << "能量不足,需要休息!" << RESET << endl;
            Sleep(1000);
            return;
        }

        vector<int> stoneIndices;
        for(int i = 0; i < player.inventory.size(); i++) {
            if(player.inventory[i].name == "石头") {
                stoneIndices.push_back(i);
            }
        }

        if(stoneIndices.empty()) {
            cout << "没有石头可以切割!" << endl;
            Sleep(1000);
            return;
        }

        system("cls");
        cout << CYAN << "===== 选择要切割的石头 =====" << RESET << endl;
        cout << "你有 " << stoneIndices.size() << " 块石头" << endl;
        cout << "1. 切割一块石头" << endl;
        cout << "2. 切割所有石头" << endl;
        cout << "0. 返回" << endl;
        cout << "选择: ";

        int choice;
        cin >> choice;

        if(choice == 0) return;

        int stonesToCut = (choice == 2) ? stoneIndices.size() : 1;

        player.currentEnergy -= 5 * stonesToCut;

        system("cls");
        cout << CYAN << "===== 切割石头中... =====" << RESET << endl;
        for(int i = 0; i < 2; i++) {
            cout << "切割";
            for(int j = 0; j < 2; j++) {
                cout << ".";
                Sleep(200);
            }
            cout << endl;
        }

        int valuableFound = 0;
        int worthlessFound = 0;

        for(int i = 0; i < stonesToCut; i++) {
            if(stoneIndices.empty()) break;

            int stoneIndex = stoneIndices.back();
            stoneIndices.pop_back();

            player.inventory.erase(player.inventory.begin() + stoneIndex);

            if(rand() % 100 < (30 + player.processingSkill * 3)) {
                valuableFound++;

                vector<int> availableMinerals;
                for(int j = 0; j < minerals.size(); j++) {
                    if(minerals[j].type != "材料" && minerals[j].minPickaxeLevel <= (player.processingSkill + 2)) {
                        availableMinerals.push_back(j);
                    }
                }

                if(!availableMinerals.empty()) {
                    int mineralIndex = availableMinerals[rand() % availableMinerals.size()];
                    Mineral foundMineral = minerals[mineralIndex];
                    double weight = CalculateMineralWeight(foundMineral);
                    foundMineral.unitWeight = weight;

                    minerals[mineralIndex].discovered = true;
                    player.inventory.push_back(foundMineral);

                    // 记录挖掘数量
                    player.mineralsMined[foundMineral.name] += weight;

                    cout << foundMineral.colorCode << "发现: " << foundMineral.name << "!" << RESET << endl;
                    cout << "重量: " << FormatWeight(weight) << endl;
                }
            } else {
                worthlessFound++;
                Mineral worthless = {"碎石", "无价值的碎石", 1, 0, true, GRAY, "废料", 1, "none", false, "kg", 500};
                player.inventory.push_back(worthless);
                cout << GRAY << "切割出: 碎石 (无价值)" << RESET << endl;
            }
        }

        cout << "\n切割结果: " << endl;
        cout << "有价值的发现: " << GREEN << valuableFound << RESET << endl;
        cout << "无价值的碎石: " << GRAY << worthlessFound << RESET << endl;

        player.experience += valuableFound * 3;
        CheckLevelUp();
        CheckAchievements();

        cout << "\n按任意键继续..." << endl;
        cin.ignore();
        cin.get();
    }

    void ShowProcessedInventory() {
        system("cls");
        cout << CYAN << "===== 加工物品 =====" << RESET << endl;

        if(player.processedInventory.empty()) {
            cout << "没有加工过的物品" << endl;
        } else {
            map<string, pair<double, double>> itemStats;
            map<string, string> itemColors;

            for(const auto& item : player.processedInventory) {
                if(itemStats.find(item.name) == itemStats.end()) {
                    itemStats[item.name] = {item.weight, item.value};
                    itemColors[item.name] = item.colorCode;
                } else {
                    itemStats[item.name].first += item.weight;
                    itemStats[item.name].second += item.value;
                }
            }

            double totalWeight = 0;
            double totalValue = 0;

            for(const auto& pair : itemStats) {
                string itemName = pair.first;
                double weight = pair.second.first;
                double value = pair.second.second;
                string colorCode = itemColors[itemName];

                cout << colorCode << itemName << RESET;
                cout << " - 重量: " << FormatWeight(weight);
                cout << " - 总价值: " << GREEN << FormatMoney(value) << RESET << endl;

                totalWeight += weight;
                totalValue += value;
            }

            cout << "\n总计: " << player.processedInventory.size() << " 个加工物品" << endl;
            cout << "总重量: " << FormatWeight(totalWeight) << endl;
            cout << "总价值: " << GREEN << FormatMoney(totalValue) << RESET << endl;
        }

        cout << "\n1. 出售所有加工物品" << endl;
        cout << "2. 返回" << endl;
        cout << "选择: ";

        int choice;
        cin >> choice;

        if(choice == 1) {
            SellAllProcessedItems();
        }
    }

    void SellAllProcessedItems() {
        if(player.processedInventory.empty()) {
            cout << RED << "没有可出售的加工物品!" << RESET << endl;
            Sleep(1000);
            return;
        }

        double totalValue = 0;
        for(const auto& item : player.processedInventory) {
            totalValue += item.value;
        }

        player.money += totalValue;
        player.processedInventory.clear();

        cout << GREEN << "出售所有加工物品获得: " << FormatMoney(totalValue) << "!" << RESET << endl;
        Sleep(1000);
    }

    void UpgradeProcessingSkill() {
        if(player.money < 500*player.processingSkill) {
            cout << RED << "资金不足!升级需要 "<<500*player.processingSkill<<"元" << RESET << endl;
            Sleep(1000);
            return;
        }

        player.money -= 500*player.processingSkill;
        player.processingSkill++;

        cout << GREEN << "加工技能升级到 " << player.processingSkill << " 级!" << RESET << endl;
        cout << "成功率: " << (50 + player.processingSkill * 5) << "%" << endl;
        Sleep(1000);
    }

    int SelectMineral(string source) {
        vector<int> availableMinerals;
        vector<int> weights;

        for(int i = 0; i < minerals.size(); i++) {
            if(minerals[i].minPickaxeLevel <= player.currentPickaxe.level &&
               (minerals[i].source == source || minerals[i].source == "both")) {
                availableMinerals.push_back(i);
                int weight = 100 / minerals[i].rarity;
                weight = max(1, weight - player.currentPickaxe.luck);
                weights.push_back(weight);
            }
        }

        if(availableMinerals.empty()) {
            return -1;
        }

        int totalWeight = 0;
        for(int weight : weights) {
            totalWeight += weight;
        }

        int randomValue = rand() % totalWeight;
        int currentWeight = 0;

        for(int i = 0; i < weights.size(); i++) {
            currentWeight += weights[i];
            if(randomValue < currentWeight) {
                return availableMinerals[i];
            }
        }

        return availableMinerals[0];
    }

    int CalculateQuality() {
        vector<int> weights = {30, 25, 20, 15, 10};

        for(int i = 0; i < player.processingSkill; i++) {
            if(i < weights.size()) {
                weights[i] = max(5, weights[i] - 5);
                weights[weights.size() - 1 - i] += 5;
            }
        }

        int totalWeight = 0;
        for(int weight : weights) {
            totalWeight += weight;
        }

        int randomValue = rand() % totalWeight;
        int currentWeight = 0;

        for(int i = 0; i < weights.size(); i++) {
            currentWeight += weights[i];
            if(randomValue < currentWeight) {
                return i + 1;
            }
        }

        return 3;
    }

    string GetQualityStars(int quality) {
        string stars;
        for(int i = 0; i < quality; i++) {
            stars += "★";
        }
        for(int i = quality; i < 5; i++) {
            stars += "☆";
        }
        return stars;
    }

    void ShowMineralCatalog() {
        system("cls");
        cout << CYAN << "===== 矿物图鉴 =====" << RESET << endl;
        cout << "当前镐子等级: " << player.currentPickaxe.level << endl;
        cout << "可挖掘矿物: 等级 1-" << player.currentPickaxe.level << " 的矿物" << endl;

        vector<string> types = {"材料", "造岩矿物", "金属矿石", "宝石", "玉石", "工业矿物", "传说"};
        for(const auto& type : types) {
            cout << "\n" << MAGENTA << "=== " << type << " ===" << RESET << endl;

            for(const auto& mineral : minerals) {
                if(mineral.type == type) {
                    if(mineral.discovered) {
                        cout << mineral.colorCode << mineral.name << RESET;
                        cout << " - 稀有度: " << GetRarityStars(mineral.rarity);
                        cout << " - 单价: " << GREEN;

                        // 正确显示单位价值
                        double unitValue = CalculateUnitValue(mineral);
                        if (mineral.unit == "ct") {
                            cout << FormatMoney(unitValue) << "/克拉";
                        } else if (mineral.unit == "g") {
                            cout << FormatMoney(unitValue) << "/克";
                        } else {
                            cout << FormatMoney(unitValue) << "/千克";
                        }
                        cout << RESET;

                        if(mineral.type != "材料") {
                            cout << " - 需要镐子: " << mineral.minPickaxeLevel << "级";
                        }
                        cout << endl;
                        cout << "   " << mineral.description;
                        if(mineral.source == "mine") {
                            cout << " [通过挖掘获得]";
                        } else if(mineral.source == "chop") {
                            cout << " [通过砍树获得]";
                        } else if(mineral.source == "both") {
                            cout << " [挖掘和砍树均可获得]";
                        }
                        cout << endl;

                        if(mineral.type == "材料" || mineral.minPickaxeLevel <= player.currentPickaxe.level) {
                            cout << GREEN << "   [可获取]" << RESET << endl;
                        } else {
                            cout << RED << "   [需要 " << mineral.minPickaxeLevel << " 级镐子]" << RESET << endl;
                        }
                    } else {
                        cout << GRAY << "????" << RESET;
                        cout << " - 稀有度: " << GetRarityStars(mineral.rarity);
                        if(mineral.type != "材料") {
                            cout << " - 需要镐子: " << mineral.minPickaxeLevel << "级";
                        }
                        cout << endl;
                        cout << "   尚未发现的" << (mineral.type == "材料" ? "材料" : "矿物") << endl;
                    }
                    cout << endl;
                }
            }
        }

        int discoveredCount = 0;
        for(const auto& mineral : minerals) {
            if(mineral.discovered) discoveredCount++;
        }
        cout << "发现进度: " << discoveredCount << "/" << minerals.size() << endl;
        cout << "\n按任意键继续..." << endl;
        cin.ignore();
        cin.get();
    }

    string GetRarityStars(int rarity) {
        string stars;
        for(int i = 0; i < rarity; i++) {
            stars += "★";
        }
        for(int i = rarity; i < 5; i++) {
            stars += "☆";
        }
        return stars;
    }

    void ShowInventory() {
        system("cls");
        cout << YELLOW << "===== 背包 =====" << RESET << endl;

        if(player.inventory.empty() && player.processedInventory.empty()) {
            cout << "背包是空的" << endl;
        } else {
            if(!player.inventory.empty()) {
                cout << CYAN << "--- 矿物 ---" << RESET << endl;
                map<string, pair<double, double>> mineralStats;
                map<string, string> mineralColors;

                for(const auto& mineral : player.inventory) {
                    if(mineralStats.find(mineral.name) == mineralStats.end()) {
                        double value = CalculateMineralValue(mineral, mineral.unitWeight);
                        mineralStats[mineral.name] = {mineral.unitWeight, value};
                        mineralColors[mineral.name] = mineral.colorCode;
                    } else {
                        double value = CalculateMineralValue(mineral, mineral.unitWeight);
                        mineralStats[mineral.name].first += mineral.unitWeight;
                        mineralStats[mineral.name].second += value;
                    }
                }

                double totalWeight = 0;
                double totalValue = 0;

                for(const auto& pair : mineralStats) {
                    string mineralName = pair.first;
                    double weight = pair.second.first;
                    double value = pair.second.second;
                    string colorCode = mineralColors[mineralName];

                    cout << colorCode << mineralName << RESET << " - 重量: " << FormatWeight(weight);
                    cout << " - 总价值: " << GREEN << FormatMoney(value) << RESET << endl;

                    totalWeight += weight;
                    totalValue += value;
                }

                cout << "矿物总计: " << player.inventory.size() << " 个物品" << endl;
                cout << "总重量: " << FormatWeight(totalWeight) << endl;
                cout << "总价值: " << GREEN << FormatMoney(totalValue) << RESET << endl;
                cout << YELLOW << "注意: 矿物只能在市场出售" << RESET << endl;
                cout << endl;
            }

            if(!player.processedInventory.empty()) {
                cout << CYAN << "--- 加工物品 ---" << RESET << endl;
                map<string, pair<double, double>> itemStats;
                map<string, string> itemColors;

                for(const auto& item : player.processedInventory) {
                    if(itemStats.find(item.name) == itemStats.end()) {
                        itemStats[item.name] = {item.weight, item.value};
                        itemColors[item.name] = item.colorCode;
                    } else {
                        itemStats[item.name].first += item.weight;
                        itemStats[item.name].second += item.value;
                    }
                }

                double totalWeight = 0;
                double totalValue = 0;

                for(const auto& pair : itemStats) {
                    string itemName = pair.first;
                    double weight = pair.second.first;
                    double value = pair.second.second;
                    string colorCode = itemColors[itemName];

                    cout << colorCode << itemName << RESET;
                    cout << " - 重量: " << FormatWeight(weight);
                    cout << " - 总价值: " << GREEN << FormatMoney(value) << RESET << endl;

                    totalWeight += weight;
                    totalValue += value;
                }

                cout << "加工物品总计: " << player.processedInventory.size() << " 个物品" << endl;
                cout << "总重量: " << FormatWeight(totalWeight) << endl;
                cout << "总价值: " << GREEN << FormatMoney(totalValue) << RESET << endl;
            }
        }

        cout << "\n1. 出售所有加工物品" << endl;
        cout << "2. 返回" << endl;
        cout << "选择: ";

        int choice;
        cin >> choice;

        if(choice == 1) {
            SellAllProcessedItems();
        }
    }

    void CraftPickaxeMenu() {
        while(true) {
            system("cls");
            cout << CYAN << "===== 镐子工坊 =====" << RESET << endl;
            cout << "当前镐: " << YELLOW << player.currentPickaxe.name << RESET;
            cout << " | 耐久: " << player.currentPickaxe.durability << "/" << player.currentPickaxe.maxDurability << endl;
            cout << "=====================" << endl;

            for(int i = 0; i < allPickaxes.size(); i++) {
                const Pickaxe& pickaxe = allPickaxes[i];
                bool canCraft = CanCraftPickaxe(pickaxe);
                bool isUnlocked = IsPickaxeUnlocked(pickaxe);

                if(isUnlocked) {
                    cout << i + 1 << ". " << YELLOW << pickaxe.name << RESET;
                    cout << " (等级 " << pickaxe.level << ")" << endl;
                    cout << "   耐久: " << pickaxe.maxDurability << " | 效率: +" << pickaxe.efficiency << "%";
                    cout << " | 幸运: +" << pickaxe.luck;
                    cout << " | 速度: " << pickaxe.speed << "ms";
                    if(pickaxe.multiMine > 1) {
                        cout << " | 多重挖掘: x" << pickaxe.multiMine;
                    }
                    cout << endl;
                    cout << "   可挖掘: 等级 1-" << pickaxe.level << " 的矿物" << endl;
                    cout << "   需要: ";
                    for(const auto& req : pickaxe.requiredMinerals) {
                        cout << req.first << " " << FormatWeight(req.second) << " ";
                    }
                    cout << endl;

                    if(canCraft) {
                        cout << GREEN << "   [可制作]" << RESET << endl;
                    } else {
                        cout << RED << "   [材料不足]" << RESET << endl;
                    }
                } else {
                    cout << i + 1 << ". " << GRAY << "????" << RESET << " (需要等级 " << (i + 1) * 5 << ")" << endl;
                }
                cout << endl;
            }

            cout << allPickaxes.size() + 1 << ". 修复当前镐子 (消耗 50元)" << endl;
            cout << "0. 返回" << endl;
            cout << "选择: ";

            int choice;
            cin >> choice;

            if(choice == 0) break;

            if(choice == allPickaxes.size() + 1) {
                RepairPickaxe();
                continue;
            }

            int pickaxeIndex = choice - 1;
            if(pickaxeIndex >= 0 && pickaxeIndex < allPickaxes.size()) {
                CraftPickaxe(pickaxeIndex);
            } else {
                cout << RED << "无效选择!" << RESET << endl;
                Sleep(500);
            }
        }
    }

    bool CanCraftPickaxe(const Pickaxe& pickaxe) {
        map<string, double> availableWeights;
        for(const auto& mineral : player.inventory) {
            availableWeights[mineral.name] += mineral.unitWeight;
        }

        for(const auto& req : pickaxe.requiredMinerals) {
            if(availableWeights[req.first] < req.second) {
                return false;
            }
        }
        return true;
    }

    bool IsPickaxeUnlocked(const Pickaxe& pickaxe) {
        for(const auto& name : player.unlockedPickaxeNames) {
            if(name == pickaxe.name) {
                return true;
            }
        }
        return player.level >= pickaxe.level * 5;
    }

    void CraftPickaxe(int pickaxeIndex) {
        Pickaxe pickaxe = allPickaxes[pickaxeIndex];

        if(!IsPickaxeUnlocked(pickaxe)) {
            cout << RED << "等级不足,无法制作此镐子!" << RESET << endl;
            Sleep(1000);
            return;
        }

        if(!CanCraftPickaxe(pickaxe)) {
            cout << RED << "材料不足!" << RESET << endl;
            Sleep(1000);
            return;
        }

        map<string, double> toRemove;
        for(const auto& req : pickaxe.requiredMinerals) {
            toRemove[req.first] = req.second;
        }

        vector<Mineral> newInventory;
        for(const auto& mineral : player.inventory) {
            if(toRemove.find(mineral.name) != toRemove.end() && toRemove[mineral.name] > 0) {
                if(mineral.unitWeight <= toRemove[mineral.name]) {
                    toRemove[mineral.name] -= mineral.unitWeight;
                } else {
                    Mineral remaining = mineral;
                    remaining.unitWeight = mineral.unitWeight - toRemove[mineral.name];
                    toRemove[mineral.name] = 0;
                    newInventory.push_back(remaining);
                }
            } else {
                newInventory.push_back(mineral);
            }
        }

        player.inventory = newInventory;

        player.currentPickaxe = Pickaxe(pickaxe.name, pickaxe.level, pickaxe.maxDurability, pickaxe.maxDurability,
                                       pickaxe.efficiency, pickaxe.luck, pickaxe.speed, pickaxe.multiMine,
                                       pickaxe.requiredMinerals);

        bool alreadyUnlocked = false;
        for(const auto& name : player.unlockedPickaxeNames) {
            if(name == pickaxe.name) {
                alreadyUnlocked = true;
                break;
            }
        }
        if(!alreadyUnlocked) {
            player.unlockedPickaxeNames.push_back(pickaxe.name);
        }

        cout << GREEN << "成功制作 " << pickaxe.name << "!" << RESET << endl;
        cout << "新特性: ";
        if(pickaxe.speed < 300) cout << "挖掘速度更快 ";
        if(pickaxe.multiMine > 1) cout << "多重挖掘 x" << pickaxe.multiMine;
        cout << " | 可挖掘等级 1-" << pickaxe.level << " 的矿物" << endl;
        Sleep(1000);
    }

    void RepairPickaxe() {
        if(player.money < 50) {
            cout << RED << "资金不足!修复需要 50元" << RESET << endl;
            Sleep(1000);
            return;
        }

        player.money -= 50;
        player.currentPickaxe.durability = player.currentPickaxe.maxDurability;

        cout << GREEN << "镐子已修复!消耗 50元" << RESET << endl;
        Sleep(1000);
    }

    void Rest() {
        double livingCost = CalculateLivingCost();
        player.debt += livingCost;

        player.currentEnergy = player.maxEnergy;
        dayCount++;
        player.totalDays++;

        UpdateMarket();

        cout << GREEN << "休息了一天,能量恢复了!" << RESET << endl;
        cout << RED << "生活费用: " << FormatMoney(livingCost) << " (已加入负债)" << RESET << endl;
        cout << "总负债: " << FormatMoney(player.debt) << endl;
        Sleep(1000);
    }

    void PayDebt() {
        if(player.debt <= 0) {
            cout << "你没有负债!" << endl;
            Sleep(1000);
            return;
        }

        system("cls");
        cout << CYAN << "===== 偿还债务 =====" << RESET << endl;
        cout << "当前负债: " << RED << FormatMoney(player.debt) << RESET << endl;
        cout << "你的资金: " << GREEN << FormatMoney(player.money) << RESET << endl;
        cout << "1. 偿还全部债务" << endl;
        cout << "2. 偿还部分债务" << endl;
        cout << "3. 返回" << endl;
        cout << "选择: ";

        int choice;
        cin >> choice;

        if(choice == 1) {
            if(player.money >= player.debt) {
                player.money -= player.debt;
                cout << GREEN << "成功偿还全部债务!" << RESET << endl;
                player.debt = 0;
            } else {
                cout << RED << "资金不足,无法偿还全部债务!" << RESET << endl;
            }
        } else if(choice == 2) {
            cout << "输入偿还金额: ";
            double amount;
            cin >> amount;

            if(amount > 0 && amount <= player.money && amount <= player.debt) {
                player.money -= amount;
                player.debt -= amount;
                cout << GREEN << "成功偿还 " << FormatMoney(amount) << " 债务!" << RESET << endl;
            } else {
                cout << RED << "无效金额!" << RESET << endl;
            }
        }

        Sleep(1000);
    }

    void CheckLevelUp() {
        int requiredExp = player.level * 100;
        if(player.experience >= requiredExp) {
            player.level++;
            player.experience = 0;
            player.maxEnergy += 20;
            player.currentEnergy = player.maxEnergy;

            cout << MAGENTA << "\n★ 升级了!现在等级 " << player.level << " ★" << RESET << endl;
            cout << "最大能量增加至: " << player.maxEnergy << endl;

            for(const auto& pickaxe : allPickaxes) {
                if(player.level == pickaxe.level * 5) {
                    cout << YELLOW << "新镐子解锁: " << pickaxe.name << RESET << endl;
                    bool alreadyUnlocked = false;
                    for(const auto& name : player.unlockedPickaxeNames) {
                        if(name == pickaxe.name) {
                            alreadyUnlocked = true;
                            break;
                        }
                    }
                    if(!alreadyUnlocked) {
                        player.unlockedPickaxeNames.push_back(pickaxe.name);
                    }
                }
            }

            Sleep(1500);
        }
    }
};

int main() {
    srand(time(0));
    system("");
    MiningGame game;
    game.ShowMainMenu();
    return 0;
}
原文