Skip to content

Commit

Permalink
refactor: move play_tic_tac_toe function to utils module
Browse files Browse the repository at this point in the history
  • Loading branch information
anuragts committed Feb 11, 2025
1 parent 4aee58c commit ce0d1fc
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 65 deletions.
65 changes: 0 additions & 65 deletions cookbook/examples/apps/tic_tac_toe/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
from agno.models.google import Gemini
from agno.models.ollama import Ollama
from agno.models.openai import OpenAIChat
from utils import TicTacToeBoard

project_root = str(Path(__file__).parent.parent.parent.parent)
if project_root not in sys.path:
Expand Down Expand Up @@ -194,67 +193,3 @@ def get_tic_tac_toe(
)

return master_agent


def play_tic_tac_toe(debug_mode: bool = True) -> None:
"""
Start and manage a game of Tic Tac Toe between two AI agents.
Args:
debug_mode (bool): Whether to show debug information during the game
"""
# Initialize the game
master_agent = get_tic_tac_toe(debug_mode=debug_mode)
game_board = TicTacToeBoard()

print("Starting a new game of Tic Tac Toe!")
print(game_board.get_board_state())

# Game loop
while True:
# Get current player
current_player = "X" if game_board.current_player == "X" else "O"
agent = master_agent.team[0] if current_player == "X" else master_agent.team[1]

# Get agent's move
print(f"\n{current_player}'s turn ({agent.name}):")
valid_moves = game_board.get_valid_moves()

response = agent.run(
f"""Current board state:\n{game_board.get_board_state()}\n
Available valid moves (row, col): {valid_moves}\n
Choose your next move from the valid moves list above.
Respond with ONLY two numbers for row and column, e.g. "1 2".""",
stream=False,
)

# Parse move from response content
try:
import re

numbers = re.findall(r"\d+", response.content if response else "")
row, col = map(int, numbers[:2])
success, message = game_board.make_move(row, col)
print(message)

if not success:
print("Invalid move! Try again.")
continue

except (ValueError, IndexError):
print("Invalid move format! Try again.")
continue

# Check for game end
winner = game_board.check_winner()
if winner:
print(f"\nGame Over! {winner} wins!")
break

if game_board.is_board_full():
print("\nGame Over! It's a draw!")
break


if __name__ == "__main__":
play_tic_tac_toe()
61 changes: 61 additions & 0 deletions cookbook/examples/apps/tic_tac_toe/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@
Utility functions for the Tic Tac Toe game.
"""

import re
from typing import List, Optional, Tuple

from agents import get_tic_tac_toe

# Define constants for players
X_PLAYER = "X"
O_PLAYER = "O"
Expand Down Expand Up @@ -122,3 +125,61 @@ def get_game_state(self) -> Tuple[bool, str]:
return True, "It's a draw!"

return False, "Game in progress"


def play_tic_tac_toe(debug_mode: bool = True) -> None:
"""
Start and manage a game of Tic Tac Toe between two AI agents.
Args:
debug_mode (bool): Whether to show debug information during the game
"""
# Initialize the game
master_agent = get_tic_tac_toe(debug_mode=debug_mode)
game_board = TicTacToeBoard()

print("Starting a new game of Tic Tac Toe!")
print(game_board.get_board_state())

# Game loop
while True:
# Get current player
current_player = "X" if game_board.current_player == "X" else "O"
agent = master_agent.team[0] if current_player == "X" else master_agent.team[1]

# Get agent's move
print(f"\n{current_player}'s turn ({agent.name}):")
valid_moves = game_board.get_valid_moves()

response = agent.run(
f"""Current board state:\n{game_board.get_board_state()}\n
Available valid moves (row, col): {valid_moves}\n
Choose your next move from the valid moves list above.
Respond with ONLY two numbers for row and column, e.g. "1 2".""",
stream=False,
)

# Parse move from response content
try:
numbers = re.findall(r"\d+", response.content if response else "")
row, col = map(int, numbers[:2])
success, message = game_board.make_move(row, col)
print(message)

if not success:
print("Invalid move! Try again.")
continue

except (ValueError, IndexError):
print("Invalid move format! Try again.")
continue

# Check for game end
winner = game_board.check_winner()
if winner:
print(f"\nGame Over! {winner} wins!")
break

if game_board.is_board_full():
print("\nGame Over! It's a draw!")
break

0 comments on commit ce0d1fc

Please sign in to comment.