tic-tac-toe-legal-distinct-move / dataset-generator.py
prpigitcse's picture
Upload dataset-generator.py
c7899e1 verified
raw
history blame
5.4 kB
import numpy as np
import pandas as pd
import csv
from io import StringIO
import time
# --- Core Tic-Tac-Toe Logic Functions ---
def check_win(board):
"""
Checks if the current player (who just made the last move) has won.
board: 9-element list where 1=X, -1=O, 0=Empty
"""
winning_lines = [
(0, 1, 2), (3, 4, 5), (6, 7, 8), # Rows
(0, 3, 6), (1, 4, 7), (2, 5, 8), # Columns
(0, 4, 8), (2, 4, 6) # Diagonals
]
for line in winning_lines:
if abs(board[line[0]] + board[line[1]] + board[line[2]]) == 3:
return True
def get_board_str(board):
"""Converts the encoded board to a human-readable string."""
symbols = { 1: 'X', -1: 'O', 0: '_' }
return ','.join(symbols[p] for p in board)
# --- Symmetry Normalization (for symmetry_id) ---
def normalize_board(board):
"""
Finds the canonical (normalized) representation of a board state.
Used for generating a consistent 'symmetry_id'.
"""
transformations = [
(0, 1, 2, 3, 4, 5, 6, 7, 8), # Identity (0 Degree)
(6, 3, 0, 7, 4, 1, 8, 5, 2), # Roatation (90 Degree)
(8, 7, 6, 5, 4, 3, 2, 1, 0), # Rotation (180 Degree)
(2, 5, 8, 1, 4, 7, 0, 3, 6), # Rotation (270 Degree)
(6, 7, 8, 3, 4, 5, 0, 1, 2), # Vertical Reflection
(2, 1, 0, 5, 4, 3, 8, 7, 6), # Horizontal Reflection
(8, 5, 2, 7, 4, 1, 6, 3, 0), # Diagonal reflection (top-left to bottom-right)
(0, 3, 6, 1, 4, 7, 2, 5, 8) # Diagonal Reflection (top-right to bottom-left)
]
canonical_board = tuple(board)
# Iterate through all transformations to find the lexicographically smallest board tuple
for transform in transformations:
transformed_board = tuple(board[i] for i in transform)
if transformed_board < canonical_board:
canonical_board = transformed_board
return hash(canonical_board)
# Global counter for unique game sequences
GAME_COUNT = 0
# Define the field names (header) for the CSV file
FIELDNAMES = [
'game_id', 'step', 'player', 'board_state', 'next_move',
'result', 'board_state_str', 'symmetry_id'
]
# File name for the output
FILE_NAME = 'tic_tac_toe_dataset.csv'
def generate_sequences(board, current_player, history, csv_writer):
"""
Recursively explores the Tic-Tac-Toe game tree.
board: current board state (numpy array)
current_player: 1 (X) or -1 (O)
history: list of (board_state, next_move_index) tuples in the current game
csv_writer: The writer object to output rows directly to the file
"""
global GAME_COUNT
# Check for terminal state (Win or Draw)
is_win = check_win(board)
is_draw = not is_win and np.all(board != 0)
if is_win or is_draw:
# --- Game Ended: Finalize history ---
GAME_COUNT += 1
# Determine the final result
if is_win:
# The previous player (who is -current_player) won.
winner = 'X' if current_player == -1 else 'O'
result = f'{winner} Win'
else:
result = 'Draw'
# Write all moves in the history to the CSV file
for i, (prev_board, move_idx) in enumerate(history):
# The player whose turn it was to make this move
player_char = 'X' if (i + 1) % 2 != 0 else 'O'
row = {
'game_id': GAME_COUNT,
'step': i + 1,
'player': player_char,
'board_state': [int(x) for x in board.tolist()], # Convert numpy array back to list for CSV
'next_move': move_idx,
'result': result,
'board_state_str': get_board_str(prev_board),
'symmetry_id': normalize_board(prev_board)
}
csv_writer.writerow(row)
return
empty_spots = np.where(board == 0)[0]
for move_index in empty_spots:
# 1. Prepare data for the current move before it's made
current_move_data = (board.copy(), move_index)
# 2. Make the move
new_board = board.copy()
new_board[move_index] = current_player
# 3. Recurse with the new state
generate_sequences(
board=new_board,
current_player=-current_player, # Toggle player
history=history + [current_move_data],
csv_writer=csv_writer
)
# --- 4. Execution in Jupyter ---
# Clear and reset globals for safe re-running
GAME_COUNT = 0
CSV_BUFFER = StringIO()
csv_writer = csv.DictWriter(CSV_BUFFER, fieldnames=FIELDNAMES)
csv_writer.writeheader()
initial_board = np.zeros(9, dtype=int)
start_time = time.time()
print("🚀 Starting dataset generation (this may take a few seconds)...")
generate_sequences(
board=initial_board,
current_player=1, # X is 1
history=[],
csv_writer=csv_writer
)
end_time = time.time()
print(f"✅ Generation complete in {end_time - start_time:.2f} seconds.")
print(f"Total distinct game sequences found: **{GAME_COUNT}**")
# Get the CSV content from the buffer
CSV_BUFFER.seek(0)
df = pd.read_csv(CSV_BUFFER)
print(f"Total move entries (rows) generated: **{len(df)}**")
# Save the DataFrame to a CSV file for persistence
df.to_csv('tic_tac_toe_dataset.csv', index=False)
print("\n💾 Dataset saved to **tic_tac_toe_dataset.csv**")