mcpField
A
autonomous-agent-gaming

autonomous-agent-gaming

github.com/qodex-ai开发47269 次安装42 周前更新
代码仓库

关于 autonomous-agent-gaming

用于构建游戏 Agent 的技能,涵盖规则策略、搜索算法和强化学习,也介绍游戏环境、策略组合、性能优化与 Agent 基准测试。

主要功能

  1. 01构建规则型和搜索型 Agent
  2. 02使用 Q-learning 训练 Agent
  3. 03将 Agent 接入游戏环境
  4. 04组合开局、中局和残局策略
  5. 05通过缓存与并行优化搜索
  6. 06在锦标赛中评测 Agent

适用场景

  1. 01为回合制游戏制作 Agent 原型
  2. 02通过与游戏交互训练策略
  3. 03在锦标赛中比较 Agent
  4. 04分析博弈策略与均衡

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/qodex-ai/ai-agent-skills --skill autonomous-agent-gaming

安装后在 Claude Code 中输入/autonomous-agent-gaming确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

README.md
examples/
chess_engine.py
game_environment.py
mcts_agent.py
minimax_agent.py
qlearning_agent.py
rule_based_agent.py
strategy_modules.py
scripts/
agent_benchmark.py
game_theory_analyzer.py
performance_optimizer.py

详细介绍

自主游戏 Agent

构建复杂的游戏 Agent,通过 AI 和强化学习来学习策略、适应对手并精通复杂游戏。

概述

自主游戏 Agent 结合了:

  • 游戏环境接口:连接游戏规则和状态
  • 决策系统:选择最优行动
  • 学习机制:通过经验不断改进
  • 策略开发:长期规划与适应
应用场景
  • 国际象棋和棋盘游戏高手
  • 即时战略(RTS)游戏机器人
  • 电子游戏自主玩家
  • 博弈论研究
  • AI 测试和基准评估
  • 娱乐和挑战系统

快速入门

运行示例 Agent:

# Rule-based agent
python examples/rule_based_agent.py

# Minimax with alpha-beta pruning
python examples/minimax_agent.py

# Monte Carlo Tree Search
python examples/mcts_agent.py

# Q-Learning agent
python examples/qlearning_agent.py

# Chess engine
python examples/chess_engine.py

# Game theory analysis
python scripts/game_theory_analyzer.py

# Benchmark agents
python scripts/agent_benchmark.py

游戏 Agent 架构

1. 基于规则的 Agent

使用预定义规则和启发式方法。完整实现见 examples/rule_based_agent.py。

核心概念:

  • 难度级别控制策略深度
  • 评估综合考虑子力、位置和控制因素
  • 决策快速,适用于实时游戏
  • 易于自定义和理解

用法示例:

from examples.rule_based_agent import RuleBasedGameAgent

agent = RuleBasedGameAgent(difficulty="hard")
best_move = agent.decide_action(game_state)
2. 带 Alpha-Beta 剪枝的 Minimax

用于回合制游戏的最优决策。参见 examples/minimax_agent.py。

核心概念:

  • 在固定深度内进行穷举树搜索
  • Alpha-Beta 剪枝会排除不可能的分支
  • 保证在搜索深度内实现最优玩法
  • 评估函数决定走法质量

性能特点:

  • 时间复杂度:剪枝时为 O(b^(d/2)),不剪枝时为 O(b^d)
  • 空间复杂度:O(b*d)
  • 可调整深度,在速度和质量之间权衡

用法示例:

from examples.minimax_agent import MinimaxGameAgent

agent = MinimaxGameAgent(max_depth=6)
best_move = agent.get_best_move(game_state)
3. 蒙特卡洛树搜索(MCTS)

以概率方式探索游戏树。完整实现见 examples/mcts_agent.py。

核心概念:

  • 四阶段算法:选择、扩展、模拟、回传
  • UCT(应用于树的置信上限)可平衡探索与利用
  • 适用于分支因子较高的游戏
  • 随时可用的算法:迭代次数越多,决策越好

UCT 公式: UCT = (child_value / child_visits) + c * sqrt(ln(parent_visits) / child_visits)

用法示例:

from examples.mcts_agent import MCTSAgent

agent = MCTSAgent(iterations=1000, exploration_constant=1.414)
best_move = agent.get_best_move(game_state)
4. 强化学习 Agent

通过与环境交互进行学习。参见 examples/qlearning_agent.py。

核心概念:

  • Q-learning:无模型、离策略学习
  • ε-greedy:平衡探索与利用
  • 更新规则:Q(s,a) += α[r + γ*max_a'Q(s',a') - Q(s,a)]
  • Q 表存储状态-行动价值估计

超参数:

  • α(learning_rate):适应新信息的速度
  • γ(discount_factor):未来奖励的重要性
  • ε(epsilon):探索概率

用法示例:

from examples.qlearning_agent import QLearningAgent

agent = QLearningAgent(learning_rate=0.1, discount_factor=0.99, epsilon=0.1)
action = agent.get_action(state)
agent.update_q_value(state, action, reward, next_state)
agent.decay_epsilon()  # Reduce exploration over time

游戏环境

标准接口

创建与 Agent 兼容的游戏环境。基类见 examples/game_environment.py。

核心方法:

  • reset():初始化游戏状态
  • step(action):执行行动,返回 (next_state, reward, done)
  • get_legal_actions(state):列出有效走法
  • is_terminal(state):检查游戏是否结束
  • render():显示游戏状态
OpenAI Gym 集成

游戏环境的标准接口:

import gym

# Create environment
env = gym.make('CartPole-v1')

# Initialize
state = env.reset()

# Run episode
done = False
while not done:
    action = agent.get_action(state)
    next_state, reward, done, info = env.step(action)
    agent.update(state, action, reward, next_state)
    state = next_state

env.close()
使用 python-chess 实现国际象棋

完整的国际象棋实现见 examples/chess_engine.py。需要安装:pip install python-chess

功能:

  • 完整的游戏规则和走法验证
  • 基于子力数量的局面评估
  • 走法历史记录和撤销功能
  • 支持 FEN 记谱法

快速示例:

from examples.chess_engine import ChessAgent

agent = ChessAgent()
result, moves = agent.play_game()
print(f"Game result: {result} in {moves} moves")
使用 Pygame 创建自定义游戏

通过 pygame 渲染扩展 examples/game_environment.py:

from examples.game_environment import PygameGameEnvironment

class MyGame(PygameGameEnvironment):
    def get_initial_state(self):
        # Return initial game state
        pass

    def apply_action(self, state, action):
        # Execute action, return new state
        pass

    def calculate_reward(self, state, action, next_state):
        # Return reward value
        pass

    def is_terminal(self, state):
        # Check if game is over
        pass

    def draw_state(self, state):
        # Render using pygame
        pass

game = MyGame()
game.render()

策略开发

所有策略实现均位于 examples/strategy_modules.py。

1. 开局理论

为棋局开局预先计算的最佳走法。可从 PGN 文件或开局数据库加载。

OpeningBook 功能:

  • 使用局面哈希快速查找
  • 从 PGN、开局数据库加载,或创建自定义棋谱
  • 超出棋谱范围时回退到其他策略

用法:

from examples.strategy_modules import OpeningBook

book = OpeningBook()
if book.in_opening(game_state):
    move = book.get_opening_move(game_state)
2. 残局库

预先计算的残局解法,包含最优走法和到将死的距离。

功能:

  • 保证残局局面下的最优走法
  • 计算到将死的距离
  • 按局面哈希查找

用法:

from examples.strategy_modules import EndgameTablebase

tablebase = EndgameTablebase()
if tablebase.in_tablebase(game_state):
    move = tablebase.get_best_endgame_move(game_state)
    dtm = tablebase.get_endgame_distance(game_state)
3. 多阶段策略

使用 AdaptiveGameAgent 为不同棋局阶段组合不同的 Agent。

策略选择:

  • 开局(子力 > 30):使用开局库或记忆棋谱
  • 中局(10-30):使用基于搜索的引擎(Minimax、MCTS)
  • 残局(子力 < 10):使用残局库实现最优对弈

用法:

from examples.strategy_modules import AdaptiveGameAgent
from examples.minimax_agent import MinimaxGameAgent

agent = AdaptiveGameAgent(
    opening_book=book,
    middlegame_engine=MinimaxGameAgent(max_depth=6),
    endgame_tablebase=tablebase
)

move = agent.decide_action(game_state)
phase_info = agent.get_phase_info(game_state)
4. 组合策略

使用 CompositeStrategy 按优先级组合多种策略。

用法:

from examples.strategy_modules import CompositeStrategy

composite = CompositeStrategy([
    opening_strategy,
    endgame_strategy,
    default_search_strategy
])

move = composite.get_move(game_state)
active = composite.get_active_strategy(game_state)

性能优化

所有优化工具均位于 scripts/performance_optimizer.py。

1. 置换表

缓存已评估的局面,避免重复计算。与 Alpha-Beta 剪枝配合时尤其有效。

工作原理:

  • 存储评估结果(分数 + 深度 + 界限类型)
  • 对局面进行哈希以便快速查找
  • 只有新评估的深度更大时才会覆盖
  • 支持并行搜索,且线程安全

界限类型:

  • exact:精确评估
  • lower:评估值至少为此值
  • upper:评估值至多为此值

用法:

from scripts.performance_optimizer import TranspositionTable

tt = TranspositionTable(max_size=1000000)

# Store evaluation
tt.store(position_hash, depth=6, score=150, flag='exact')

# Lookup
score = tt.lookup(position_hash, depth=6)
hit_rate = tt.hit_rate()
2. 杀手启发式

跟踪在相似深度上造成截断的走法,以改进走法排序。

概念:

  • 杀手走法是导致 Beta 截断的非吃子走法
  • 它们很可能也是同一深度其他节点的好走法
  • 提高 Alpha-Beta 剪枝效率

用法:

from scripts.performance_optimizer import KillerHeuristic

killers = KillerHeuristic(max_depth=20)

# When a cutoff occurs
killers.record_killer(move, depth=5)

# When ordering moves
killer_list = killers.get_killers(depth=5)
is_killer = killers.is_killer(move, depth=5)
3. 并行搜索

通过多个线程并行搜索博弈树。

用法:

from scripts.performance_optimizer import ParallelSearchCoordinator

coordinator = ParallelSearchCoordinator(num_threads=4)

# Parallel move evaluation
scores = coordinator.parallel_evaluate_moves(moves, evaluate_func)

# Parallel minimax
best_move, score = coordinator.parallel_minimax(root_moves, minimax_func)

coordinator.shutdown()
4. 搜索统计

使用 SearchStatistics 跟踪和分析搜索性能。

指标:

  • 已评估 / 已剪枝的节点数
  • 分支因子
  • 剪枝效率
  • 缓存命中率

用法:

from scripts.performance_optimizer import SearchStatistics

stats = SearchStatistics()

# During search
stats.record_node()
stats.record_cutoff()
stats.record_cache_hit()

# Analysis
print(stats.summary())
print(f"Pruning efficiency: {stats.pruning_efficiency():.1f}%")

博弈论应用

完整实现见 scripts/game_theory_analyzer.py。

1. 纳什均衡计算

为双人博弈寻找最优混合策略解。

纯策略纳什均衡: 如果一个单元格对双方玩家而言都是最佳响应,那么它就是纳什均衡。

混合策略纳什均衡: 玩家在不同动作间随机选择。对于 2x2 博弈,可使用无差异条件。

用法:

from scripts.game_theory_analyzer import GameTheoryAnalyzer, PayoffMatrix
import numpy as np

# Create payoff matrix
p1_payoffs = np.array([[3, 0], [5, 1]])
p2_payoffs = np.array([[3, 5], [0, 1]])

matrix = PayoffMatrix(
    player1_payoffs=p1_payoffs,
    player2_payoffs=p2_payoffs,
    row_labels=['Strategy A', 'Strategy B'],
    column_labels=['Strategy X', 'Strategy Y']
)

analyzer = GameTheoryAnalyzer()

# Find pure Nash equilibria
equilibria = analyzer.find_pure_strategy_nash_equilibria(matrix)

# Find mixed Nash equilibrium (2x2 only)
p1_mixed, p2_mixed = analyzer.calculate_mixed_strategy_2x2(matrix)

# Expected payoff
payoff = analyzer.calculate_expected_payoff(p1_mixed, p2_mixed, matrix, player=1)

# Zero-sum analysis
if matrix.is_zero_sum():
    minimax = analyzer.minimax_value(matrix)
    maximin = analyzer.maximin_value(matrix)
2. 合作博弈分析

分析玩家可以协调行动的联盟博弈。

Shapley 值:

  • 根据边际贡献公平分配总收益
  • 每位玩家获得其在所有联盟排列中的预期边际贡献

核心:

  • 不存在任何联盟希望偏离的一组收益分配
  • 满足联盟理性的稳定结果

用法:

from scripts.game_theory_analyzer import CooperativeGameAnalyzer

coop = CooperativeGameAnalyzer()

# Define payoff function for coalitions
def payoff_func(coalition):
    # Return total value of coalition
    return sum(player_values[p] for p in coalition)

players = ['Alice', 'Bob', 'Charlie']

# Calculate Shapley values
shapley = coop.calculate_shapley_value(payoff_func, players)
print(f"Alice's fair share: {shapley['Alice']}")

# Find core allocation
core = coop.calculate_core(payoff_func, players)
is_stable = coop.is_core_allocation(core, payoff_func, players)

最佳实践

Agent 开发
  • ✓ 从基于规则的基线开始
  • ✓ 始终如一地衡量性能指标
  • ✓ 针对多个对手进行测试
  • ✓ 使用版本控制管理 Agent 版本
  • ✓ 记录策略变更
游戏环境
  • ✓ 验证游戏规则的实现
  • ✓ 测试边界情况
  • ✓ 提供便捷的重置 / 重播功能
  • ✓ 记录游戏状态以供分析
  • ✓ 支持确定性种子
优化
  • ✓ 优化前先进行性能分析
  • ✓ 使用置换表
  • ✓ 实施妥善的时间管理
  • ✓ 监控内存使用情况
  • ✓ 与基线进行性能对比

测试与基准测试

完整的基准测试工具包见 scripts/agent_benchmark.py。

锦标赛评估

在 Agent 之间进行循环赛或淘汰赛。

用法:

from scripts.agent_benchmark import GameAgentBenchmark

benchmark = GameAgentBenchmark()

# Run tournament
results = benchmark.run_tournament(agents, num_games=100)

# Compare two agents
comparison = benchmark.head_to_head_comparison(agent1, agent2, num_games=50)
print(f"Win rate: {comparison['agent1_win_rate']:.1%}")
评分系统

使用标准评分系统计算 Agent 的实力。

Elo 评分:

  • 基于实力差距
  • 普通对局的 K 系数为 32
  • 用于国际象棋和许多其他游戏

Glicko-2 评分:

  • 考虑评分的不确定性(偏差)
  • 更适用于不规律的对局安排

用法:

# Elo ratings
elo_ratings = benchmark.evaluate_elo_rating(agents, num_games=100)

# Glicko-2 ratings
glicko_ratings = benchmark.glicko2_rating(agents, num_games=100)

# Strength relative to baseline
strength = benchmark.rate_agent_strength(agent, baseline_agents, num_games=20)
性能分析

在测试局面上评估 Agent 的质量。

用法:

# Get performance profile
profile = benchmark.performance_profile(agent, test_positions, time_limit=1.0)
print(f"Accuracy: {profile['accuracy']:.1%}")
print(f"Avg move quality: {profile['avg_move_quality']:.2f}")

实现清单

  • 选择游戏环境(Gym、Chess、自定义)
  • 设计 Agent 架构(基于规则、Minimax、MCTS、RL)
  • 实现游戏状态表示
  • 创建评估函数
  • 实现 Agent 决策
  • 设置训练/学习循环
  • 创建基准测试系统
  • 与多个对手进行测试
  • 优化性能(搜索深度、评估速度)
  • 记录策略和结果
  • 部署并监控性能

资源

框架
研究

评论

支持 Markdown