Game-playing agents demonstrate advanced AI capabilities through strategic decision-making, adversarial reasoning, and multi-agent coordination. These agents use LLMs to analyze game states, evaluate positions, and make strategic moves in real-time competitive scenarios.
Game-playing agents showcase key AI concepts like adversarial search, position evaluation, move validation, and strategic planning - all fundamental to building intelligent autonomous systems.
An advanced chess game system where two AI agents play against each other using Autogen with robust move validation and game state management.Multi-Agent Architecture:
Game Initialization ↓Player White Agent├─ Analyze current position├─ Evaluate possible moves├─ Select optimal move└─ Propose move in algebraic notation ↓Board Proxy Agent├─ Validate move legality├─ Check for rule violations├─ Update game state├─ Detect check/checkmate/stalemate└─ Approve or reject move ↓If Move Valid: ↓Player Black Agent├─ Analyze new position├─ Formulate response├─ Select counter-move└─ Propose move ↓Board Proxy Agent└─ Validate and update ↓Continue until game end...
Features:
Safety & Validation
Strategic Gameplay
Complete Ruleset
Robust Move Verification:
Checks all chess rules (castling, en passant, promotion)
Prevents illegal moves
Validates piece movement patterns
Ensures king safety
Real-time Monitoring:
Board state tracking after each move
Check and checkmate detection
Stalemate and draw conditions
Move history logging
Secure Progression:
Prevents rule violations
Handles edge cases
Enforces turn order
Game integrity maintenance
AI-Powered Analysis:
Deep position evaluation
Material count assessment
Piece activity analysis
King safety evaluation
Pawn structure assessment
Tactical Capabilities:
Fork and pin detection
Discovered attack recognition
Sacrifice evaluation
Combination searching
Dynamic Strategy:
Opening book knowledge
Middlegame planning
Endgame technique
Adaptive play style
Standard Chess Rules:
Piece movement (Pawn, Knight, Bishop, Rook, Queen, King)
Castling (kingside and queenside)
En passant captures
Pawn promotion
Check and checkmate
Stalemate detection
Fifty-move rule
Threefold repetition
Special Conditions:
Insufficient material draws
Agreed draws
Resignation handling
Setup and Run:
# Clone repositorygit clone https://github.com/Shubhamsaboo/awesome-llm-apps.gitcd advanced_ai_agents/autonomous_game_playing_agent_apps/ai_chess_agent# Install dependenciespip install -r requirements.txt# Set OpenAI API keyexport OPENAI_API_KEY='your-api-key-here'# Run the chess gamestreamlit run ai_chess_agent.py
import autogenimport chess# Configure LLMllm_config = { "config_list": [{ "model": "gpt-4o", "api_key": openai_api_key }]}# Create player agentsplayer_white = autogen.AssistantAgent( name="Player_White", system_message=""" You are a strategic chess player playing White. Analyze the position and make the best move. Use standard algebraic notation (e.g., e4, Nf3, O-O). """, llm_config=llm_config)player_black = autogen.AssistantAgent( name="Player_Black", system_message=""" You are a tactical chess player playing Black. Respond to White's moves with sound strategy. Use standard algebraic notation. """, llm_config=llm_config)# Create validation agentboard_proxy = autogen.AssistantAgent( name="Board_Proxy", system_message=""" You validate chess moves and maintain game state. Check move legality and update the board. Detect check, checkmate, and stalemate. """, llm_config=llm_config)# Initialize boardboard = chess.Board()# Game loopwhile not board.is_game_over(): # White's turn white_move = player_white.generate_move(board) if board_proxy.validate_move(white_move, board): board.push(white_move) # Black's turn if not board.is_game_over(): black_move = player_black.generate_move(board) if board_proxy.validate_move(black_move, board): board.push(black_move)
Strategic Insights: The agents learn chess strategy through their training data, including opening principles, tactical patterns, and endgame techniques. Watch how they apply concepts like center control, piece development, and king safety!
An interactive Tic-Tac-Toe game where AI agents powered by different language models compete against each other, built on Agno Agent Framework.Multi-Model Support:
OpenAI Models
GPT-4o
GPT-o3-mini
Advanced reasoning
Strategic planning
Google Models
Gemini Pro
Gemini Flash
Fast responses
Efficient processing
Other Models
Claude (Anthropic)
Llama 3 (Groq)
Diverse strategies
Comparative analysis
Agent Roles:
Master Agent (Referee)├─ Coordinates the game├─ Validates moves├─ Maintains game state├─ Determines outcome└─ Enforces rules ↓Player X Agent├─ Analyzes board state├─ Makes strategic X moves├─ Follows game rules└─ Responds to opponent ↓Player O Agent├─ Analyzes board state├─ Makes strategic O moves├─ Follows game rules└─ Responds to opponent
# Required for OpenAI models (gpt-4o, o3-mini)OPENAI_API_KEY=your_actual_openai_api_key_here# Optional - for additional modelsANTHROPIC_API_KEY=your_actual_anthropic_api_key_here # For ClaudeGOOGLE_API_KEY=your_actual_google_api_key_here # For GeminiGROQ_API_KEY=your_actual_groq_api_key_here # For Groq models
Replace placeholder values with actual API keys. The app shows helpful error messages if required keys are missing.
Run the Game:
streamlit run app.py
Open localhost:8501 to view the game interface.Game Implementation:
from agno import Agent# Create Master Agent (Referee)master_agent = Agent( name="Game_Master", model=model_x, instructions=""" You are the game master for Tic-Tac-Toe. Coordinate between players, validate moves, maintain game state, and determine winners. """)# Create Player Xplayer_x = Agent( name="Player_X", model=model_x, instructions=""" You play as X in Tic-Tac-Toe. Analyze the board and make strategic moves. Try to win by getting three X's in a row. Block opponent's winning moves. """)# Create Player Oplayer_o = Agent( name="Player_O", model=model_o, instructions=""" You play as O in Tic-Tac-Toe. Analyze the board and make strategic moves. Try to win by getting three O's in a row. Block opponent's winning moves. """)# Game loopboard = [[" " for _ in range(3)] for _ in range(3)]current_player = player_xwhile not is_game_over(board): # Current player makes move move = current_player.run( f"Current board state: {board}. Make your move." ) # Master validates and applies move if master_agent.validate_move(move, board): apply_move(move, board) current_player = player_o if current_player == player_x else player_x # Check for win/draw result = master_agent.check_game_over(board)
Strategic Patterns:
Offensive Strategy
Winning Moves:
Center control (position 5)
Corner positions (1, 3, 7, 9)
Fork creation
Two-way threats
Defensive Strategy
Blocking Moves:
Detect opponent’s two-in-a-row
Block winning moves
Force opponent to defend
Create counter-threats
Opening Play
First Moves:
Center (optimal)
Corners (strong)
Edges (suboptimal)
Response to opponent’s center
Endgame
Final Positions:
Forced wins
Forced draws
Mistake exploitation
Optimal play
Model Comparison:
Model Matchup
Strategy Type
Win Rate
Notes
GPT-4o vs GPT-4o
Balanced
50%
Optimal play both sides
GPT-4o vs o3-mini
Strategic vs Tactical
Varies
Different reasoning styles
Claude vs GPT-4o
Analytical
~45%
Methodical approach
Gemini vs Llama
Fast vs Robust
Varies
Speed vs consistency
Experiment with Models: Try different model combinations to see varied playing styles! GPT-4o tends to be aggressive, Claude is defensive, and o3-mini shows creative tactics.
# LLMs approximate minimax reasoningdef evaluate_move(board, player): """ LLM reasons about: 1. Immediate winning moves 2. Blocking opponent wins 3. Strategic position control 4. Long-term advantage """ prompt = f""" Board state: {board} You are playing as {player}. Analyze: 1. Can you win in one move? 2. Can opponent win if you don't block? 3. What move gives best position? Consider both your opportunities and opponent's threats. """ return llm.generate(prompt)
# Effective game agent promptssystem_message = """You are playing {game_name} as {player}.RULES:{game_rules}STRATEGY:1. Analyze the current position2. Identify immediate threats3. Look for winning opportunities4. Consider long-term advantage5. Make the best moveFORMAT:Provide your move in {notation_format}.Explain your reasoning briefly.CURRENT BOARD:{board_state}YOUR TURN: Make your move."""
import streamlit as st# Use session state for game persistenceif 'game_state' not in st.session_state: st.session_state.game_state = initialize_game() st.session_state.move_history = [] st.session_state.current_player = "X"# Update state after each movedef make_move(move): st.session_state.game_state.apply(move) st.session_state.move_history.append(move) st.session_state.current_player = switch_player()