1979/src/save_manager.py

src / save_manager.py

src/save_manager.py · 10.5 KB

# -*- coding: utf-8 -*-
"""SaveManager - 1979 游戏存档/读档系统

把 DemoGame 的核心状态序列化到 saves/*.json,支持多槽位 + 列表读取。
"""

import json
import os
from datetime import datetime
from typing import Dict, List, Optional


SAVE_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'saves')


def _ensure_save_dir() -> str:
    """确保 saves 目录存在"""
    os.makedirs(SAVE_DIR, exist_ok=True)
    return SAVE_DIR


# ============================================================================
# 各对象的序列化/反序列化
# ============================================================================

def _serialize_player(player) -> Dict:
    """序列化 Player"""
    return {
        'name': player.name,
        'hp': player.hp,
        '_max_hp_cap': player._max_hp_cap,
        'temperature': player.temperature,
        'hunger': player.hunger,
        'thirst': player.thirst,
        'radiation': player.radiation,
        'fatigue': player.fatigue,
        'morale': player.morale,
        '_hallucination_active': player._hallucination_active,
        '_hallucination_timer': player._hallucination_timer,
        'state': player.state,
        'radio_skill': player.radio_skill,
        'military_skill': player.military_skill,
        'speech_skill': player.speech_skill,
        'russian_skill': player.russian_skill,
        'politics_skill': player.politics_skill,
        'professional_level': getattr(player, 'professional_level', 1),
    }


def _deserialize_player(player, data: Dict) -> None:
    """把 data 灌回已构造的 Player 实例"""
    player.name = data.get('name', player.name)
    player.hp = data.get('hp', player.hp)
    player._max_hp_cap = data.get('_max_hp_cap', player._max_hp_cap)
    player.temperature = data.get('temperature', player.temperature)
    player.hunger = data.get('hunger', player.hunger)
    player.thirst = data.get('thirst', player.thirst)
    player.radiation = data.get('radiation', player.radiation)
    player.fatigue = data.get('fatigue', player.fatigue)
    player.morale = data.get('morale', player.morale)
    player._hallucination_active = data.get('_hallucination_active', False)
    player._hallucination_timer = data.get('_hallucination_timer', 0)
    player.state = data.get('state', 'normal')
    player.radio_skill = data.get('radio_skill', 70)
    player.military_skill = data.get('military_skill', 55)
    player.speech_skill = data.get('speech_skill', 35)
    player.russian_skill = data.get('russian_skill', 25)
    player.politics_skill = data.get('politics_skill', 45)
    player.professional_level = data.get('professional_level', 1)


def _serialize_ling(ling) -> Dict:
    """序列化 Lingmuxue(注意 alive 是只读 property,靠 hp 推断)"""
    return {
        'hp': ling.hp,
        '_max_hp_cap': ling._max_hp_cap,
        'temperature': ling.temperature,
        'hunger': ling.hunger,
        'thirst': ling.thirst,
        'radiation': ling.radiation,
        'fatigue': ling.fatigue,
        'morale': ling.morale,
        'trust': ling.trust,
        'intimacy': ling.intimacy,
        'left_silently': ling.left_silently,
        'memory': ling.memory,
        '_dialogue_count': ling._dialogue_count,
        '_hallucination_active': ling._hallucination_active,
        '_hallucination_timer': ling._hallucination_timer,
        'state': ling.state,
        'professional_level': getattr(ling, 'professional_level', 1),
    }


def _deserialize_ling(ling, data: Dict) -> None:
    ling.hp = data.get('hp', ling.hp)
    ling._max_hp_cap = data.get('_max_hp_cap', ling._max_hp_cap)
    ling.temperature = data.get('temperature', ling.temperature)
    ling.hunger = data.get('hunger', ling.hunger)
    ling.thirst = data.get('thirst', ling.thirst)
    ling.radiation = data.get('radiation', ling.radiation)
    ling.fatigue = data.get('fatigue', ling.fatigue)
    ling.morale = data.get('morale', ling.morale)
    ling.trust = data.get('trust', ling.trust)
    ling.intimacy = data.get('intimacy', ling.intimacy)
    ling.left_silently = data.get('left_silently', False)
    ling.memory = data.get('memory', [])
    ling._dialogue_count = data.get('_dialogue_count', 0)
    ling._hallucination_active = data.get('_hallucination_active', False)
    ling._hallucination_timer = data.get('_hallucination_timer', 0)
    ling.state = data.get('state', 'normal')
    ling.professional_level = data.get('professional_level', 1)


def _serialize_vehicle(vehicle) -> Dict:
    return {
        'name': vehicle.name,
        'fuel': vehicle.fuel,
        'hull': vehicle.hull,
        'max_fuel': vehicle.max_fuel,
        'max_hull': vehicle.max_hull,
    }


def _deserialize_vehicle(vehicle, data: Dict) -> None:
    vehicle.name = data.get('name', vehicle.name)
    vehicle.fuel = data.get('fuel', vehicle.fuel)
    vehicle.hull = data.get('hull', vehicle.hull)
    vehicle.max_fuel = data.get('max_fuel', vehicle.max_fuel)
    vehicle.max_hull = data.get('max_hull', vehicle.max_hull)


def _serialize_world(world) -> Dict:
    return {
        'distance_to_harbin': world.distance_to_harbin,
        'traveled': world.traveled,
        'day': world.day,
        '_phase_idx': world._phase_idx,
        'season': world.season,
        'weather': world.weather,
        'temperature': world.temperature,
        'fuel_on_route': world.fuel_on_route,
        '_weather_rolled_today': world._weather_rolled_today,
        'air_superiority_lost': getattr(world, 'air_superiority_lost', False),
        'father_clue_found': getattr(world, 'father_clue_found', False),
    }


def _deserialize_world(world, data: Dict) -> None:
    world.distance_to_harbin = data.get('distance_to_harbin', world.distance_to_harbin)
    world.traveled = data.get('traveled', world.traveled)
    world.day = data.get('day', world.day)
    world._phase_idx = data.get('_phase_idx', 0)
    world.season = data.get('season', world.season)
    world.weather = data.get('weather', world.weather)
    world.temperature = data.get('temperature', world.temperature)
    world.fuel_on_route = data.get('fuel_on_route', world.fuel_on_route)
    world._weather_rolled_today = data.get('_weather_rolled_today', True)
    world.air_superiority_lost = data.get('air_superiority_lost', False)
    world.father_clue_found = data.get('father_clue_found', False)


def _serialize_inventory(inv) -> Dict:
    return {
        'items': dict(inv.items),
        'max_weight': inv.max_weight,
        'max_volume': inv.max_volume,
    }


def _deserialize_inventory(inv, data: Dict) -> None:
    inv.items = dict(data.get('items', {}))
    inv.max_weight = data.get('max_weight', inv.max_weight)
    inv.max_volume = data.get('max_volume', inv.max_volume)


# ============================================================================
# SaveManager 主类
# ============================================================================

class SaveManager:
    """存档管理器"""

    def __init__(self, save_dir: str = None):
        self.save_dir = save_dir or _ensure_save_dir()

    def save(self, game, slot: str = 'auto') -> str:
        """保存游戏状态到指定槽位

        Args:
            game: DemoGame 实例
            slot: 槽位名(如 'auto'/'slot1')

        Returns:
            存档文件路径
        """
        data = {
            'meta': {
                'slot': slot,
                'saved_at': datetime.now().isoformat(),
                'day': getattr(game, 'day', 1),
                'node_index': getattr(game, 'current_node_index', 0),
            },
            'player': _serialize_player(game.player),
            'ling': _serialize_ling(game.ling),
            'vehicle': _serialize_vehicle(game.vehicle),
            'world': _serialize_world(game.world),
            'inventory': _serialize_inventory(game.inventory),
            'game_state': {
                'day': game.day,
                'current_node_index': game.current_node_index,
                'ammo_count': game.ammo_count,
                'player_has_gun': game.player_has_gun,
            },
        }

        path = os.path.join(self.save_dir, f'{slot}.json')
        with open(path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        return path

    def load(self, game, slot: str = 'auto') -> bool:
        """从指定槽位读取游戏状态灌回 game 实例

        Args:
            game: DemoGame 实例
            slot: 槽位名

        Returns:
            是否加载成功
        """
        path = os.path.join(self.save_dir, f'{slot}.json')
        if not os.path.exists(path):
            print(f"[存档] 槽位 {slot} 不存在")
            return False

        with open(path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        _deserialize_player(game.player, data['player'])
        _deserialize_ling(game.ling, data['ling'])
        _deserialize_vehicle(game.vehicle, data['vehicle'])
        _deserialize_world(game.world, data['world'])
        _deserialize_inventory(game.inventory, data['inventory'])

        gs = data.get('game_state', {})
        game.day = gs.get('day', game.day)
        game.current_node_index = gs.get('current_node_index', game.current_node_index)
        game.ammo_count = gs.get('ammo_count', game.ammo_count)
        game.player_has_gun = gs.get('player_has_gun', game.player_has_gun)

        meta = data.get('meta', {})
        print(f"[存档] 已读取 {slot}(保存于 {meta.get('saved_at', '未知')})")
        return True

    def list_slots(self) -> List[Dict]:
        """列出所有存档槽位"""
        slots = []
        if not os.path.exists(self.save_dir):
            return slots

        for fname in sorted(os.listdir(self.save_dir)):
            if not fname.endswith('.json'):
                continue
            path = os.path.join(self.save_dir, fname)
            try:
                with open(path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                meta = data.get('meta', {})
                slots.append({
                    'slot': meta.get('slot', fname[:-5]),
                    'saved_at': meta.get('saved_at', '?'),
                    'day': meta.get('day', '?'),
                    'node_index': meta.get('node_index', '?'),
                    'path': path,
                })
            except (json.JSONDecodeError, KeyError):
                continue
        return slots

    def delete_slot(self, slot: str) -> bool:
        """删除存档槽位"""
        path = os.path.join(self.save_dir, f'{slot}.json')
        if os.path.exists(path):
            os.remove(path)
            return True
        return False

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