autonomous-agent-gaming
Build autonomous game-playing agents using AI and reinforcement learning. Covers game environments, agent decision-making, strategy development, and performance optimization. Use when creating game-playing bots, testing game AI, strategic decision-making systems, or game theory applications.
What this skill does
# Autonomous Agent Gaming
Build sophisticated game-playing agents that learn strategies, adapt to opponents, and master complex games through AI and reinforcement learning.
## Overview
Autonomous game agents combine:
- **Game Environment Interface**: Connect to game rules and state
- **Decision-Making Systems**: Choose optimal actions
- **Learning Mechanisms**: Improve through experience
- **Strategy Development**: Long-term planning and adaptation
### Applications
- Chess and board game masters
- Real-time strategy (RTS) game bots
- Video game autonomous players
- Game theory research
- AI testing and benchmarking
- Entertainment and challenge systems
## Quick Start
Run example agents with:
```bash
# 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
```
## Game Agent Architectures
### 1. Rule-Based Agents
Use predefined rules and heuristics. See full implementation in `examples/rule_based_agent.py`.
**Key Concepts:**
- Difficulty levels control strategy depth
- Evaluation combines material, position, and control factors
- Fast decision-making suitable for real-time games
- Easy to customize and understand
**Usage Example:**
```python
from examples.rule_based_agent import RuleBasedGameAgent
agent = RuleBasedGameAgent(difficulty="hard")
best_move = agent.decide_action(game_state)
```
### 2. Minimax with Alpha-Beta Pruning
Optimal decision-making for turn-based games. See `examples/minimax_agent.py`.
**Key Concepts:**
- Exhaustive tree search up to fixed depth
- Alpha-beta pruning eliminates impossible branches
- Guarantees optimal play within search depth
- Evaluation function determines move quality
**Performance Characteristics:**
- Time complexity: O(b^(d/2)) with pruning vs O(b^d) without
- Space complexity: O(b*d)
- Adjustable depth for speed/quality tradeoff
**Usage Example:**
```python
from examples.minimax_agent import MinimaxGameAgent
agent = MinimaxGameAgent(max_depth=6)
best_move = agent.get_best_move(game_state)
```
### 3. Monte Carlo Tree Search (MCTS)
Probabilistic game tree exploration. Full implementation in `examples/mcts_agent.py`.
**Key Concepts:**
- Four-phase algorithm: Selection, Expansion, Simulation, Backpropagation
- UCT (Upper Confidence bounds applied to Trees) balances exploration/exploitation
- Effective for games with high branching factors
- Anytime algorithm: more iterations = better decisions
**The UCT Formula:**
UCT = (child_value / child_visits) + c * sqrt(ln(parent_visits) / child_visits)
**Usage Example:**
```python
from examples.mcts_agent import MCTSAgent
agent = MCTSAgent(iterations=1000, exploration_constant=1.414)
best_move = agent.get_best_move(game_state)
```
### 4. Reinforcement Learning Agents
Learn through interaction with environment. See `examples/qlearning_agent.py`.
**Key Concepts:**
- Q-learning: model-free, off-policy learning
- Epsilon-greedy: balance exploration vs exploitation
- Update rule: Q(s,a) += α[r + γ*max_a'Q(s',a') - Q(s,a)]
- Q-table stores state-action value estimates
**Hyperparameters:**
- α (learning_rate): How quickly to adapt to new information
- γ (discount_factor): Importance of future rewards
- ε (epsilon): Exploration probability
**Usage Example:**
```python
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
```
## Game Environments
### Standard Interfaces
Create game environments compatible with agents. See `examples/game_environment.py` for base classes.
**Key Methods:**
- `reset()`: Initialize game state
- `step(action)`: Execute action, return (next_state, reward, done)
- `get_legal_actions(state)`: List valid moves
- `is_terminal(state)`: Check if game is over
- `render()`: Display game state
### OpenAI Gym Integration
Standard interface for game environments:
```python
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()
```
### Chess with python-chess
Full chess implementation in `examples/chess_engine.py`. Requires: `pip install python-chess`
**Features:**
- Full game rules and move validation
- Position evaluation based on material count
- Move history and undo functionality
- FEN notation support
**Quick Example:**
```python
from examples.chess_engine import ChessAgent
agent = ChessAgent()
result, moves = agent.play_game()
print(f"Game result: {result} in {moves} moves")
```
### Custom Game with Pygame
Extend `examples/game_environment.py` with pygame rendering:
```python
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()
```
## Strategy Development
All strategy implementations are in `examples/strategy_modules.py`.
### 1. Opening Theory
Pre-computed best moves for game openings. Load from PGN files or opening databases.
**OpeningBook Features:**
- Fast lookup using position hashing
- Load from PGN, opening databases, or create custom books
- Fallback to other strategies when out of book
**Usage:**
```python
from examples.strategy_modules import OpeningBook
book = OpeningBook()
if book.in_opening(game_state):
move = book.get_opening_move(game_state)
```
### 2. Endgame Tablebases
Pre-computed endgame solutions with optimal moves and distance-to-mate.
**Features:**
- Guaranteed optimal moves in endgame positions
- Distance-to-mate calculation
- Lookup by position hash
**Usage:**
```python
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. Multi-Stage Strategy
Combine different agents for different game phases using `AdaptiveGameAgent`.
**Strategy Selection:**
- **Opening (Material > 30)**: Use opening book or memorized lines
- **Middlegame (10-30)**: Use search-based engine (Minimax, MCTS)
- **Endgame (Material < 10)**: Use tablebase for optimal play
**Usage:**
```python
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. Composite Strategies
Combine multiple strategies with priority ordering using `CompositeStrategy`.
**Usage:**
```python
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)
```
## Performance Optimization
All optimization utilities are in `scripts/performance_optimizer.py`.
##Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.