1979/src/playtest.py

src / playtest.py

src/playtest.py · 13.3 KB

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""自动化试玩系统 - 持续提高游戏可玩度"""


class AutoPlaytest:
    """自动化试玩系统"""

    def __init__(self):
        self.test_results = []
        self.issues = []
        self.metrics = {
            'branches_tested': {},
            'events_seen': {},
            'endings_reached': {},
            'crashes': 0,
            'dead_ends': 0,
        }

    def run_full_playtest(self, num_runs=10):
        """运行完整试玩(多次运行不同路径)"""
        print(f"开始自动试玩:{num_runs} 次运行")

        for i in range(num_runs):
            print(f"\n=== 运行 {i+1}/{num_runs} ===")
            try:
                self._run_single_playthrough(i)
            except Exception as e:
                self.metrics['crashes'] += 1
                self.issues.append({
                    'type': 'crash',
                    'run': i + 1,
                    'error': str(e)
                })

        self._analyze_results()
        return self._generate_report()

    def _run_single_playthrough(self, run_id):
        """单次试玩运行"""
        import sys
        sys.path.insert(0, 'D:/1979')
        from src.game import Game
        from src.player import Player
        from src.lingmuxue import Lingmuxue
        from src.vehicle import Vehicle
        from src.world import World
        from src.harbin_state import HarbinState
        import random

        # 创建游戏实例
        game = Game()
        game.player.name = f"测试玩家{run_id}"
        game.day = 30  # 跳过前面,从哈尔滨开始

        # 初始化哈尔滨状态
        game.harbin = HarbinState()

        # 根据运行ID配置不同状态组合,确保每个分支都有机会被解锁
        # run_id % 8 对应 8 个分支的配置
        config_id = run_id % 8

        if config_id == 0:
            # pyongyang: trust>=70, korea>=65, harbin_escaped=True
            game.ling.trust = 85
            game.ling.intimacy = 30
            game.harbin.agent_relations = {
                'korea': 75, 'japan': 30, 'usa': 30, 'soviet': 30,
                'china': 30, 'taiwan': 30
            }
        elif config_id == 1:
            # sakhalin: intimacy>=70, trust>=40, japan>=65 or usa>=65
            game.ling.trust = 50
            game.ling.intimacy = 85
            game.harbin.agent_relations = {
                'korea': 30, 'japan': 75, 'usa': 30, 'soviet': 30,
                'china': 30, 'taiwan': 30
            }
        elif config_id == 2:
            # vladivostok: soviet>=65, china<40, trust>=20, intimacy>=30
            game.ling.trust = 85
            game.ling.intimacy = 65
            game.harbin.agent_relations = {
                'korea': 30, 'japan': 30, 'usa': 30, 'soviet': 75,
                'china': 30, 'taiwan': 30
            }
        elif config_id == 3:
            # beijing_mao: rebel_territory<20, china>=70, trust>=80, intimacy>=80, conspiracy=True
            game.ling.trust = 90
            game.ling.intimacy = 85
            game.harbin.rebel_territory = 10
            game.harbin.agent_relations = {
                'korea': 30, 'japan': 30, 'usa': 30, 'soviet': 30,
                'china': 80, 'taiwan': 30
            }
            game.conspiracy_discovered = True
        elif config_id == 4:
            # beijing_rebel: rebel_relation>=70, pla_strength<20, soviet_pressure<30
            game.ling.trust = 50
            game.ling.intimacy = 30
            game.harbin.pla_strength = 10
            game.harbin.soviet_pressure = 20
            game.harbin.agent_relations = {
                'korea': 30, 'japan': 30, 'usa': 30, 'soviet': 30,
                'china': 30, 'taiwan': 30
            }
        elif config_id == 5:
            # japan_usa: intimacy>=70, (taiwan>=65 or usa>=65 or japan>=65), visa=True
            game.ling.trust = 70
            game.ling.intimacy = 85
            game.visa_obtained = True
            game.harbin.agent_relations = {
                'korea': 30, 'japan': 75, 'usa': 75, 'soviet': 30,
                'china': 30, 'taiwan': 75
            }
        else:
            # harbin_stay: 无特殊要求(默认保底)
            game.ling.trust = 60
            game.ling.intimacy = 40
            game.harbin.agent_relations = {
                'korea': 30, 'japan': 30, 'usa': 30, 'soviet': 30,
                'china': 30, 'taiwan': 30
            }

        # 测试分支选择(不模拟战局演进,直接测试解锁逻辑)
        branch = self._auto_select_branch(game, run_id)
        self.metrics['branches_tested'][branch] = self.metrics['branches_tested'].get(branch, 0) + 1

        # 运行分支
        self._run_branch(game, branch)

    def _auto_select_branch(self, game, run_id):
        """自动选择分支"""
        from src.pyongy_branch import PyongyangBranch
        from src.sakhalin_branch import SakhalinBranch
        from src.vladivostok_branch import VladivostokBranch
        from src.beijing_mao_branch import BeijingMaoBranch
        from src.beijing_rebel_branch import BeijingRebelBranch
        from src.japan_usa_branch import JapanUSABranch
        from src.harbin_stay_branch import HarbinStayBranch

        available = []
        ling_intimacy = getattr(game.ling, 'intimacy', 0)
        ling_trust = getattr(game.ling, 'trust', 0)

        # 检查平壤分支
        pb = PyongyangBranch()
        korea_rel = game.harbin.agent_relations.get('korea', 0)
        if pb.can_unlock(ling_trust, korea_rel, True):
            available.append('pyongyang')

        # 检查库页岛分支
        sb = SakhalinBranch()
        japan_rel = game.harbin.agent_relations.get('japan', 0)
        usa_rel = game.harbin.agent_relations.get('usa', 0)
        # 检查 sakhalin 解锁条件
        nato_unlocked = japan_rel >= 65 or usa_rel >= 65
        sakhalin_can_unlock = (
            nato_unlocked and
            ling_intimacy >= 70 and
            ling_trust >= 40
        )
        if sakhalin_can_unlock:
            available.append('sakhalin')

        # 检查海参崴分支
        vb = VladivostokBranch()
        soviet_rel = game.harbin.agent_relations.get('soviet', 0)
        china_rel = game.harbin.agent_relations.get('china', 0)
        if vb.can_unlock(soviet_rel, china_rel, game.ling.trust, ling_intimacy):
            available.append('vladivostok')

        # 检查北京毛派分支(需要:造反派地盘<20, 总参关系>=70, 信任>=80, 亲密度>=80, 阴谋已发现)
        bm = BeijingMaoBranch()
        rebel_territory = game.harbin.rebel_territory
        china_rel = game.harbin.agent_relations.get('china', 0)
        conspiracy_discovered = getattr(game, 'conspiracy_discovered', False)
        if bm.can_unlock(rebel_territory, china_rel, game.ling.trust, ling_intimacy, conspiracy_discovered):
            available.append('beijing_mao')

        # 检查北京造反派分支(需要:造反派关系>=70, PLA战力<20, 苏军压力<30)
        br = BeijingRebelBranch()
        # 造反派关系不在 agent_relations 中,用 soviet_pressure 的补数近似
        rebel_relation = 100 - game.harbin.soviet_pressure
        pla_strength = game.harbin.pla_strength
        soviet_pressure = game.harbin.soviet_pressure
        if br.can_unlock(rebel_relation, pla_strength, soviet_pressure):
            available.append('beijing_rebel')

        # 检查日本/美国分支
        ju = JapanUSABranch()
        visa = getattr(game, 'visa_obtained', False)
        taiwan_rel = game.harbin.agent_relations.get('taiwan', 0)
        if ju.can_unlock(ling_intimacy, taiwan_rel, usa_rel, japan_rel, visa):
            available.append('japan_usa')

        # 检查留在哈尔滨分支(始终可进入)
        hs = HarbinStayBranch()
        if hs.can_enter():
            available.append('harbin_stay')

        # 留在哈尔滨始终可用作为保底
        if not available:
            available.append('harbin_stay')

        # 优先选择与 config_id 对应的分支(确保每个 config 都能测到目标分支)
        config_id = run_id % 8
        config_to_branch = {
            0: 'pyongyang',
            1: 'sakhalin',
            2: 'vladivostok',
            3: 'beijing_mao',
            4: 'beijing_rebel',
            5: 'japan_usa',
            6: 'harbin_stay',
            7: 'harbin_stay',
        }
        preferred_branch = config_to_branch.get(config_id, 'harbin_stay')
        if preferred_branch in available:
            return preferred_branch
        # 如果目标分支没解锁(条件未满足),退回第一个可用分支
        return available[0]

    def _run_branch(self, game, branch):
        """运行指定分支"""
        try:
            if branch == 'pyongyang':
                from src.pyongy_branch import PyongyangBranch
                branch_state = PyongyangBranch()
            elif branch == 'sakhalin':
                from src.sakhalin_branch import SakhalinBranch
                branch_state = SakhalinBranch()
            elif branch == 'vladivostok':
                from src.vladivostok_branch import VladivostokBranch
                branch_state = VladivostokBranch()
            elif branch == 'beijing_mao':
                from src.beijing_mao_branch import BeijingMaoBranch
                branch_state = BeijingMaoBranch()
            elif branch == 'beijing_rebel':
                from src.beijing_rebel_branch import BeijingRebelBranch
                branch_state = BeijingRebelBranch()
            elif branch == 'japan_usa':
                from src.japan_usa_branch import JapanUSABranch
                branch_state = JapanUSABranch()
            elif branch == 'harbin_stay':
                from src.harbin_stay_branch import HarbinStayBranch
                branch_state = HarbinStayBranch()
            else:
                raise ValueError(f"未知分支: {branch}")

            self.metrics['endings_reached'][branch] = (
                self.metrics['endings_reached'].get(branch, 0) + 1
            )
        except Exception as e:
            self.issues.append({
                'type': 'branch_init_error',
                'branch': branch,
                'error': str(e)
            })

    def _analyze_results(self):
        """分析试玩结果"""
        # 检查分支覆盖率
        total_runs = sum(self.metrics['branches_tested'].values())
        if total_runs == 0:
            return

        unique_branches = len(self.metrics['branches_tested'])
        expected_branches = 7  # pyongyang, sakhalin, vladivostok, beijing_mao, beijing_rebel, japan_usa, harbin_stay

        if unique_branches < expected_branches:
            uncovered = expected_branches - unique_branches
            self.issues.append({
                'type': 'low_branch_coverage',
                'branch': 'all',
                'coverage': unique_branches / expected_branches * 100,
                'message': f"分支覆盖率不足:仅覆盖 {unique_branches}/{expected_branches} 个分支 ({unique_branches/expected_branches*100:.1f}%)"
            })

        for branch, count in self.metrics['branches_tested'].items():
            coverage = count / total_runs * 100
            if coverage < 10 and coverage > 0:
                self.issues.append({
                    'type': 'low_branch_coverage',
                    'branch': branch,
                    'coverage': coverage,
                    'message': f"分支 {branch} 覆盖率过低 ({coverage:.1f}%)"
                })

        # 检查崩溃率
        crash_rate = self.metrics['crashes'] / total_runs * 100 if total_runs > 0 else 0
        if crash_rate > 5:
            self.issues.append({
                'type': 'high_crash_rate',
                'crash_rate': crash_rate,
                'message': f"崩溃率过高 ({crash_rate:.1f}%)"
            })

        # 检查死胡同
        if self.metrics['dead_ends'] > 0:
            dead_end_rate = self.metrics['dead_ends'] / total_runs * 100
            self.issues.append({
                'type': 'dead_ends_found',
                'count': self.metrics['dead_ends'],
                'rate': dead_end_rate,
                'message': f"发现 {self.metrics['dead_ends']} 个死胡同 ({dead_end_rate:.1f}%)"
            })

    def _generate_report(self):
        """生成试玩报告"""
        report = []
        report.append("=" * 56)
        report.append("试玩报告")
        report.append("=" * 56)

        report.append(f"\n崩溃次数: {self.metrics['crashes']}")
        report.append(f"死胡同次数: {self.metrics['dead_ends']}")

        report.append("\n分支覆盖:")
        if self.metrics['branches_tested']:
            for branch, count in sorted(self.metrics['branches_tested'].items()):
                report.append(f"  {branch}: {count} 次")
        else:
            report.append("  无数据")

        report.append("\n结局达成:")
        if self.metrics['endings_reached']:
            for ending, count in sorted(self.metrics['endings_reached'].items()):
                report.append(f"  {ending}: {count} 次")
        else:
            report.append("  无数据")

        report.append("\n发现的问题:")
        if not self.issues:
            report.append("  无问题")
        else:
            for issue in self.issues:
                report.append(f"  [{issue['type']}] {issue.get('message', '')}")

        report.append("\n" + "=" * 56)
        return "\n".join(report)

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