1979/src/inventory.py

src / inventory.py

src/inventory.py · 15.7 KB

"""物资系统 - 漫漫长夜式细分库存管理(东北苏联特化)"""

from dataclasses import dataclass, field
from typing import Optional


@dataclass
class Item:
    """物品定义"""
    id: str
    name: str
    category: str  # "survival"/"medical"/"ammo"/"tool"/"radio"/"special"/"craftable"/"book"/"tape"
    weight: float  # kg
    volume: float  # L
    stackable: bool = True
    max_stack: int = 99
    durability: float = 1.0  # 0-1,部分物品有
    state: str = "完好"  # "完好"/"腐烂"/"污染"/"受潮"/"破损"/"失效"
    # 额外属性(可选)
    warmth: float = 0.0  # 保暖值(衣物专用)
    heals: int = 0  # 治疗量(医疗用品)
    disinfect: bool = False  # 消毒
    numbs_pain_hours: int = 0  # 止痛时长
    cures_infection: bool = False  # 治愈感染
    radiation_reduce: int = 0  # 辐射降低
    addictive: bool = False  # 成瘾性
    prevents_scurvy: bool = False  # 预防坏血病
    treats_frostbite: bool = False  # 治疗冻伤
    prevents_radiation_damage: bool = False  # 防辐射伤害
    hull_repair: float = 0.0  # 车辆修理比例
    rarity: str = "common"  # 稀有度 "common"/"rare"/"ultra"


# ============================================================================
# ITEM CATALOG(物资目录,东北苏联特化)
# ============================================================================

# --- 生存物资 ---
water_clean = Item("water_clean_1L", "水(干净)", "survival", 1.0, 1.0)
water_dirty = Item("water_dirty_1L", "水(污染)", "survival", 1.0, 1.0, state="污染")
frozen_pear = Item("frozen_pear", "冻梨", "survival", 0.2, 0.2)
frozen_persimmon = Item("frozen_persimmon", "冻柿子", "survival", 0.2, 0.2)
suancai = Item("suancai_jar", "酸菜(缸)", "survival", 5.0, 8.0)
niantoubao = Item("niantoubao", "粘豆包", "survival", 0.3, 0.3)
dazazi = Item("dazazi_kg", "大碴子", "survival", 1.0, 1.5)
gaoliangmi = Item("gaoliangmi_kg", "高粱米", "survival", 1.0, 1.5)
fen_tiao = Item("fen_tiao_kg", "粉条", "survival", 0.5, 1.0)
xiancai = Item("xiancai", "咸菜疙瘩", "survival", 0.3, 0.3)
pork_frozen = Item("pork_frozen", "猪肉(冻)", "survival", 0.5, 0.5)
paozi_jerky = Item("paozi_jerky", "狍子肉(干)", "survival", 0.3, 0.3)
canned_meat = Item("canned_meat", "罐头(肉)", "survival", 0.4, 0.4)
canned_veg = Item("canned_veg", "罐头(蔬菜)", "survival", 0.4, 0.4)
flour = Item("flour_bag", "面粉(袋)", "survival", 2.0, 3.0)
compressed_biscuit = Item("compressed_biscuit", "压缩饼干", "survival", 0.2, 0.2)
diesel = Item("diesel_20L", "柴油(桶)", "survival", 10.0, 12.0)
gasoline = Item("gasoline_20L", "汽油(桶)", "survival", 7.0, 12.0)
coal = Item("coal_bag", "煤炭(袋)", "survival", 5.0, 8.0)
firewood = Item("firewood_bundle", "木柴(捆)", "survival", 5.0, 8.0)
matches = Item("matches_box", "火柴(盒)", "survival", 0.05, 0.05)
lighter = Item("lighter", "打火机", "survival", 0.1, 0.1)
vodka = Item("vodka_bottle", "伏特加(瓶)", "survival", 0.7, 0.7)
leiba = Item("leiba", "列巴(俄式面包)", "survival", 0.8, 1.2)
soviet_ration = Item("soviet_ration", "苏军口粮", "survival", 0.5, 0.5)

# --- 衣物/保暖 ---
blanket = Item("blanket", "毛毯", "survival", 1.5, 3.0, warmth=0.5)
cotton_coat_pla = Item("cotton_coat_pla", "解放军棉衣", "survival", 1.5, 2.5, warmth=0.3)
soviet_greatcoat = Item("soviet_greatcoat", "苏军军大衣", "survival", 2.5, 4.0, warmth=0.4)
ushanka = Item("ushanka", "苏式乌尚卡皮帽", "survival", 0.3, 0.3, warmth=0.15)
felt_boots = Item("felt_boots", "苏式毡靴", "survival", 0.8, 1.5, warmth=0.4)
gloves = Item("gloves_cotton", "棉手套", "survival", 0.2, 0.2, warmth=0.1)

# --- 医疗 ---
bandage = Item("bandage", "绷带", "medical", 0.1, 0.1, heals=10)
iodine = Item("iodine", "碘酒", "medical", 0.1, 0.1, disinfect=True)
painkiller = Item("painkiller", "止痛药", "medical", 0.05, 0.05, numbs_pain_hours=2)
antibiotic = Item("antibiotic", "抗生素", "medical", 0.1, 0.1, rarity="ultra", cures_infection=True)
iodine_tablet = Item("iodine_tablet", "碘片", "medical", 0.02, 0.02, rarity="ultra", radiation_reduce=50)
morphine = Item("morphine", "吗啡", "medical", 0.05, 0.05, rarity="ultra", heals=30, addictive=True)
vitamin_c = Item("vitamin_c", "维生素C", "medical", 0.05, 0.05, prevents_scurvy=True)
salve = Item("salve", "药膏", "medical", 0.1, 0.1, treats_frostbite=True)
mask = Item("mask", "口罩", "medical", 0.05, 0.05, prevents_radiation_damage=True)

# --- 工具 ---
wrench = Item("wrench", "扳手", "tool", 0.5, 0.3)
pliers = Item("pliers", "钳子", "tool", 0.4, 0.2)
axe = Item("hand_axe", "手斧", "tool", 0.8, 0.3)
knife = Item("hunting_knife", "猎刀", "tool", 0.3, 0.1)
ice_pick = Item("ice_pick", "冰镩", "tool", 1.0, 0.3)
snow_shovel = Item("snow_shovel", "雪铲", "tool", 1.5, 0.5)
needle_thread = Item("needle_thread", "缝纫针线", "tool", 0.1, 0.1)
wire = Item("wire_roll", "铁丝(卷)", "tool", 1.0, 0.5)
rope = Item("rope_10m", "麻绳(10米)", "tool", 0.5, 1.0)

# --- 车辆零件 ---
oil_filter = Item("oil_filter", "机油滤芯", "tool", 0.5, 0.5, hull_repair=0.05)
belt = Item("transmission_belt", "传动皮带", "tool", 0.8, 1.0, hull_repair=0.10)
piston = Item("piston_pin", "活塞销", "tool", 1.0, 0.5, hull_repair=0.15)
tire = Item("tire", "轮胎", "tool", 15.0, 20.0)

# --- 通讯 ---
radio_set = Item("radio_set", "短波电台", "radio", 5.0, 8.0)
radio_spares = Item("radio_spares", "电台备件", "radio", 1.0, 1.0)
battery_large = Item("battery_large", "电池(大)", "radio", 2.0, 1.0)
battery_small = Item("battery_small", "电池(小)", "radio", 0.2, 0.1)
flashlight = Item("flashlight", "手电筒", "radio", 0.3, 0.3)

# --- 特殊/剧情 ---
map_northeast = Item("map_northeast", "地图(东北)", "special", 0.2, 0.3)
officer_id = Item("officer_id", "军官证(你的)", "special", 0.05, 0.05)
diary = Item("diary", "日记本(凌暮雪的)", "special", 0.1, 0.1)
family_photo = Item("family_photo", "全家福(凌暮雪的)", "special", 0.05, 0.05)

# --- 书籍(学习模块) ---
barefoot_doctor = Item("barefoot_doctor_manual", "赤脚医生手册", "book", 0.3, 0.3)
minbing_manual = Item("minbing_manual", "民兵训练手册", "book", 0.3, 0.3)
car_manual = Item("car_manual", "机械维修手册(解放牌)", "book", 0.5, 0.5)
radio_textbook = Item("radio_textbook", "无线电教材", "book", 0.4, 0.4)
russian_dict = Item("russian_dict", "俄语词典", "book", 0.4, 0.4)
mao_quotations = Item("mao_quotations", "毛主席语录", "book", 0.1, 0.1)
shijian_zhenli = Item("shijian_zhenli", "实践是检验真理的唯一标准", "book", 0.1, 0.1)
shanghen_wenxue = Item("shanghen_wenxue", "伤痕文学(手抄本)", "book", 0.2, 0.2)
xiaohua = Item("xiaohua", "笑话大全(手抄本)", "book", 0.2, 0.2)
hongloumeng = Item("hongloumeng", "红楼梦(残本)", "book", 0.4, 0.5)
pushkin = Item("pushkin_ru", "普希金诗集(俄文)", "book", 0.4, 0.4)
stahl = Item("stahl_ru", "钢铁是怎样炼成的", "book", 0.5, 0.5)

# --- 磁带(音乐模块) ---
tape_shanzhashu = Item("tape_shanzhashu", "磁带(山楂树)", "tape", 0.1, 0.1)
tape_moscow = Item("tape_moscow", "磁带(莫斯科郊外的晚上)", "tape", 0.1, 0.1)
tape_katyusha = Item("tape_katyusha", "磁带(喀秋莎)", "tape", 0.1, 0.1)

# --- 可制作物品 ---
molotov = Item("molotov", "燃烧瓶", "craftable", 0.6, 0.6)
torch = Item("torch", "简易火把", "craftable", 0.3, 0.3)
trap = Item("trap", "陷阱", "craftable", 1.0, 1.0)


# 构建ID到Item的映射
ITEM_CATALOG: dict[str, Item] = {}
for _item in [
    water_clean, water_dirty, frozen_pear, frozen_persimmon, suancai,
    niantoubao, dazazi, gaoliangmi, fen_tiao, xiancai, pork_frozen,
    paozi_jerky, canned_meat, canned_veg, flour, compressed_biscuit,
    diesel, gasoline, coal, firewood, matches, lighter, vodka, leiba,
    soviet_ration, blanket, cotton_coat_pla, soviet_greatcoat, ushanka,
    felt_boots, gloves, bandage, iodine, painkiller, antibiotic,
    iodine_tablet, morphine, vitamin_c, salve, mask, wrench, pliers,
    axe, knife, ice_pick, snow_shovel, needle_thread, wire, rope,
    oil_filter, belt, piston, tire, radio_set, radio_spares, battery_large,
    battery_small, flashlight, map_northeast, officer_id, diary, family_photo,
    barefoot_doctor, minbing_manual, car_manual, radio_textbook, russian_dict,
    mao_quotations, shijian_zhenli, shanghen_wenxue, xiaohua, hongloumeng,
    pushkin, stahl, tape_shanzhashu, tape_moscow, tape_katyusha,
    molotov, torch, trap,
]:
    ITEM_CATALOG[_item.id] = _item


class Inventory:
    """车载库存管理系统"""

    def __init__(self, max_weight: float = 2000.0, max_volume: float = 100.0):
        """
        Args:
            max_weight: 最大载重(kg),默认2000kg(解放牌)
            max_volume: 最大容积(L),默认100L(80后斗+20驾驶)
        """
        self.max_weight = max_weight
        self.max_volume = max_volume
        self.items: dict[str, int] = {}  # {item_id: quantity}

    def add(self, item_id: str, qty: int) -> bool:
        """添加物品,失败返回False(超载或物品不存在)"""
        if item_id not in ITEM_CATALOG:
            return False
        if qty <= 0:
            return False

        item = ITEM_CATALOG[item_id]
        current_qty = self.items.get(item_id, 0)

        # 检查堆叠限制
        if item.stackable and current_qty + qty > item.max_stack:
            return False
        if not item.stackable and (current_qty > 0 or qty > 1):
            return False

        # 检查超重
        new_weight = self.current_weight + item.weight * qty
        if new_weight > self.max_weight:
            return False

        # 检查超体积
        new_volume = self.current_volume + item.volume * qty
        if new_volume > self.max_volume:
            return False

        self.items[item_id] = current_qty + qty
        return True

    def remove(self, item_id: str, qty: int) -> bool:
        """移除物品,失败返回False(数量不足或物品不存在)"""
        if item_id not in ITEM_CATALOG:
            return False
        if qty <= 0:
            return False

        current_qty = self.items.get(item_id, 0)
        if current_qty < qty:
            return False

        self.items[item_id] = current_qty - qty
        if self.items[item_id] == 0:
            del self.items[item_id]
        return True

    def has(self, item_id: str, qty: int = 1) -> bool:
        """检查是否有足够数量的物品"""
        if item_id not in ITEM_CATALOG:
            return False
        return self.items.get(item_id, 0) >= qty

    def get(self, item_id: str) -> Optional[Item]:
        """获取物品定义,如果库存中没有则返回None"""
        if item_id not in ITEM_CATALOG:
            return None
        if item_id not in self.items:
            return None
        return ITEM_CATALOG[item_id]

    def list(self) -> list[tuple[Item, int]]:
        """列出所有物品及其数量"""
        result = []
        for item_id, qty in self.items.items():
            if item_id in ITEM_CATALOG:
                result.append((ITEM_CATALOG[item_id], qty))
        return result

    @property
    def current_weight(self) -> float:
        """当前总重量"""
        total = 0.0
        for item_id, qty in self.items.items():
            if item_id in ITEM_CATALOG:
                total += ITEM_CATALOG[item_id].weight * qty
        return total

    @property
    def current_volume(self) -> float:
        """当前总体积"""
        total = 0.0
        for item_id, qty in self.items.items():
            if item_id in ITEM_CATALOG:
                total += ITEM_CATALOG[item_id].volume * qty
        return total

    def is_overweight(self) -> bool:
        """是否超重"""
        return self.current_weight > self.max_weight

    def is_over_volume(self) -> bool:
        """是否超体积"""
        return self.current_volume > self.max_volume

    def status_line(self) -> str:
        """状态行"""
        weight_pct = (self.current_weight / self.max_weight * 100) if self.max_weight > 0 else 0
        vol_pct = (self.current_volume / self.max_volume * 100) if self.max_volume > 0 else 0
        lines = [f"【库存】{len(self.items)}种物品 | 重量:{self.current_weight:.1f}/{self.max_weight:.0f}kg ({weight_pct:.0f}%) | 体积:{self.current_volume:.1f}/{self.max_volume:.0f}L ({vol_pct:.0f}%)"]
        if self.is_overweight():
            lines.append("  ⚠ 超重!")
        if self.is_over_volume():
            lines.append("  ⚠ 超体积!")
        return "\n".join(lines)


class Crafting:
    """制作系统"""

    recipes = {
        "molotov": {"cloth": 1, "diesel_20L": 1, "glass_bottle": 1},
        "torch": {"cloth": 1, "diesel_20L": 1},
        "distilled_water": {"water_dirty_1L": 2, "fuel_0.5L": 1},
        "sew_blanket": {"broken_blanket": 1, "needle_thread": 1, "cloth": 1},
        "trap": {"wire_roll": 2, "rope_10m": 1},
    }

    @staticmethod
    def can_craft(recipe_id: str, inventory: Inventory) -> bool:
        """检查是否可以制作某个配方"""
        if recipe_id not in Crafting.recipes:
            return False
        recipe = Crafting.recipes[recipe_id]
        for ingredient, qty in recipe.items():
            if not inventory.has(ingredient, qty):
                return False
        return True

    @staticmethod
    def craft(recipe_id: str, inventory: Inventory, crafter_level: int = 1) -> bool:
        """
        制作物品
        Args:
            recipe_id: 配方ID
            inventory: 库存
            crafter_level: 制作人等级(影响成功率)
        Returns:
            是否制作成功
        """
        if not Crafting.can_craft(recipe_id, inventory):
            return False

        recipe = Crafting.recipes[recipe_id]

        # 消耗材料
        for ingredient, qty in recipe.items():
            inventory.remove(ingredient, qty)

        # 制作输出(简化:直接添加到库存)
        output_item = recipe_id  # 配方ID通常与输出物品ID一致
        if output_item in ITEM_CATALOG:
            inventory.add(output_item, 1)

        return True


def apply_state_changes(inventory: Inventory, weather: str, hours: int = 1):
    """
    应用状态变化(暴露在恶劣天气时)

    Args:
        inventory: 库存
        weather: 天气状况 ("blizzard"/"freeze_rain"/"dust_storm"/"normal")
        hours: 暴露小时数
    """
    items_to_remove = []
    items_to_modify = []

    for item_id, qty in inventory.items.items():
        if item_id not in ITEM_CATALOG:
            continue

        item = ITEM_CATALOG[item_id]

        # 罐头开封24小时后 → 腐烂
        if item_id.startswith("canned_") and hours >= 24:
            items_to_modify.append((item_id, "腐烂"))

        # 水暴露在尘暴 → 污染
        if item_id.startswith("water_clean") and weather == "dust_storm":
            items_to_remove.append(item_id)
            # 添加污染水(不直接在inventory里改ID,简化处理)

        # 弹药未密封在暴风雪/冻雨 → 受潮
        if item.category == "ammo" and weather in ("blizzard", "freeze_rain"):
            if item.durability < 1.0:  # 未完全密封
                items_to_modify.append((item_id, "受潮"))

        # 火柴未密封在暴风雪/冻雨 → 失效
        if item_id == "matches_box" and weather in ("blizzard", "freeze_rain"):
            if item.durability < 1.0:
                items_to_modify.append((item_id, "失效"))

        # 衣物/毛毯磨损 → 保暖-50%
        if item.warmth > 0 and item.durability < 0.5:
            items_to_modify.append((item_id, "破损"))

    for item_id, new_state in items_to_modify:
        if item_id in ITEM_CATALOG:
            ITEM_CATALOG[item_id].state = new_state

    # 污染水的替换逻辑需要更复杂的实现,这里简化

← 返回文件树 · 在 GitHub 上查看