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
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import csv
|
| 4 |
+
from io import StringIO
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
# --- Core Tic-Tac-Toe Logic Functions ---
|
| 8 |
+
def check_win(board):
|
| 9 |
+
"""
|
| 10 |
+
Checks if the current player (who just made the last move) has won.
|
| 11 |
+
board: 9-element list where 1=X, -1=O, 0=Empty
|
| 12 |
+
"""
|
| 13 |
+
winning_lines = [
|
| 14 |
+
(0, 1, 2), (3, 4, 5), (6, 7, 8), # Rows
|
| 15 |
+
(0, 3, 6), (1, 4, 7), (2, 5, 8), # Columns
|
| 16 |
+
(0, 4, 8), (2, 4, 6) # Diagonals
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
for line in winning_lines:
|
| 20 |
+
if abs(board[line[0]] + board[line[1]] + board[line[2]]) == 3:
|
| 21 |
+
return True
|
| 22 |
+
|
| 23 |
+
def get_board_str(board):
|
| 24 |
+
"""Converts the encoded board to a human-readable string."""
|
| 25 |
+
symbols = { 1: 'X', -1: 'O', 0: '_' }
|
| 26 |
+
return ','.join(symbols[p] for p in board)
|
| 27 |
+
|
| 28 |
+
# --- Symmetry Normalization (for symmetry_id) ---
|
| 29 |
+
def normalize_board(board):
|
| 30 |
+
"""
|
| 31 |
+
Finds the canonical (normalized) representation of a board state.
|
| 32 |
+
Used for generating a consistent 'symmetry_id'.
|
| 33 |
+
"""
|
| 34 |
+
transformations = [
|
| 35 |
+
(0, 1, 2, 3, 4, 5, 6, 7, 8), # Identity (0 Degree)
|
| 36 |
+
(6, 3, 0, 7, 4, 1, 8, 5, 2), # Roatation (90 Degree)
|
| 37 |
+
(8, 7, 6, 5, 4, 3, 2, 1, 0), # Rotation (180 Degree)
|
| 38 |
+
(2, 5, 8, 1, 4, 7, 0, 3, 6), # Rotation (270 Degree)
|
| 39 |
+
(6, 7, 8, 3, 4, 5, 0, 1, 2), # Vertical Reflection
|
| 40 |
+
(2, 1, 0, 5, 4, 3, 8, 7, 6), # Horizontal Reflection
|
| 41 |
+
(8, 5, 2, 7, 4, 1, 6, 3, 0), # Diagonal reflection (top-left to bottom-right)
|
| 42 |
+
(0, 3, 6, 1, 4, 7, 2, 5, 8) # Diagonal Reflection (top-right to bottom-left)
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
canonical_board = tuple(board)
|
| 46 |
+
|
| 47 |
+
# Iterate through all transformations to find the lexicographically smallest board tuple
|
| 48 |
+
for transform in transformations:
|
| 49 |
+
transformed_board = tuple(board[i] for i in transform)
|
| 50 |
+
if transformed_board < canonical_board:
|
| 51 |
+
canonical_board = transformed_board
|
| 52 |
+
|
| 53 |
+
return hash(canonical_board)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# Global counter for unique game sequences
|
| 57 |
+
GAME_COUNT = 0
|
| 58 |
+
# Define the field names (header) for the CSV file
|
| 59 |
+
FIELDNAMES = [
|
| 60 |
+
'game_id', 'step', 'player', 'board_state', 'next_move',
|
| 61 |
+
'result', 'board_state_str', 'symmetry_id'
|
| 62 |
+
]
|
| 63 |
+
# File name for the output
|
| 64 |
+
FILE_NAME = 'tic_tac_toe_dataset.csv'
|
| 65 |
+
|
| 66 |
+
def generate_sequences(board, current_player, history, csv_writer):
|
| 67 |
+
"""
|
| 68 |
+
Recursively explores the Tic-Tac-Toe game tree.
|
| 69 |
+
board: current board state (numpy array)
|
| 70 |
+
current_player: 1 (X) or -1 (O)
|
| 71 |
+
history: list of (board_state, next_move_index) tuples in the current game
|
| 72 |
+
csv_writer: The writer object to output rows directly to the file
|
| 73 |
+
"""
|
| 74 |
+
global GAME_COUNT
|
| 75 |
+
|
| 76 |
+
# Check for terminal state (Win or Draw)
|
| 77 |
+
is_win = check_win(board)
|
| 78 |
+
is_draw = not is_win and np.all(board != 0)
|
| 79 |
+
|
| 80 |
+
if is_win or is_draw:
|
| 81 |
+
# --- Game Ended: Finalize history ---
|
| 82 |
+
GAME_COUNT += 1
|
| 83 |
+
|
| 84 |
+
# Determine the final result
|
| 85 |
+
if is_win:
|
| 86 |
+
# The previous player (who is -current_player) won.
|
| 87 |
+
winner = 'X' if current_player == -1 else 'O'
|
| 88 |
+
result = f'{winner} Win'
|
| 89 |
+
else:
|
| 90 |
+
result = 'Draw'
|
| 91 |
+
|
| 92 |
+
# Write all moves in the history to the CSV file
|
| 93 |
+
for i, (prev_board, move_idx) in enumerate(history):
|
| 94 |
+
|
| 95 |
+
# The player whose turn it was to make this move
|
| 96 |
+
player_char = 'X' if (i + 1) % 2 != 0 else 'O'
|
| 97 |
+
|
| 98 |
+
row = {
|
| 99 |
+
'game_id': GAME_COUNT,
|
| 100 |
+
'step': i + 1,
|
| 101 |
+
'player': player_char,
|
| 102 |
+
'board_state': [int(x) for x in board.tolist()], # Convert numpy array back to list for CSV
|
| 103 |
+
'next_move': move_idx,
|
| 104 |
+
'result': result,
|
| 105 |
+
'board_state_str': get_board_str(prev_board),
|
| 106 |
+
'symmetry_id': normalize_board(prev_board)
|
| 107 |
+
}
|
| 108 |
+
csv_writer.writerow(row)
|
| 109 |
+
return
|
| 110 |
+
|
| 111 |
+
empty_spots = np.where(board == 0)[0]
|
| 112 |
+
|
| 113 |
+
for move_index in empty_spots:
|
| 114 |
+
# 1. Prepare data for the current move before it's made
|
| 115 |
+
current_move_data = (board.copy(), move_index)
|
| 116 |
+
|
| 117 |
+
# 2. Make the move
|
| 118 |
+
new_board = board.copy()
|
| 119 |
+
new_board[move_index] = current_player
|
| 120 |
+
|
| 121 |
+
# 3. Recurse with the new state
|
| 122 |
+
generate_sequences(
|
| 123 |
+
board=new_board,
|
| 124 |
+
current_player=-current_player, # Toggle player
|
| 125 |
+
history=history + [current_move_data],
|
| 126 |
+
csv_writer=csv_writer
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
# --- 4. Execution in Jupyter ---
|
| 130 |
+
|
| 131 |
+
# Clear and reset globals for safe re-running
|
| 132 |
+
GAME_COUNT = 0
|
| 133 |
+
CSV_BUFFER = StringIO()
|
| 134 |
+
csv_writer = csv.DictWriter(CSV_BUFFER, fieldnames=FIELDNAMES)
|
| 135 |
+
csv_writer.writeheader()
|
| 136 |
+
|
| 137 |
+
initial_board = np.zeros(9, dtype=int)
|
| 138 |
+
start_time = time.time()
|
| 139 |
+
|
| 140 |
+
print("🚀 Starting dataset generation (this may take a few seconds)...")
|
| 141 |
+
|
| 142 |
+
generate_sequences(
|
| 143 |
+
board=initial_board,
|
| 144 |
+
current_player=1, # X is 1
|
| 145 |
+
history=[],
|
| 146 |
+
csv_writer=csv_writer
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
end_time = time.time()
|
| 150 |
+
print(f"✅ Generation complete in {end_time - start_time:.2f} seconds.")
|
| 151 |
+
print(f"Total distinct game sequences found: **{GAME_COUNT}**")
|
| 152 |
+
|
| 153 |
+
# Get the CSV content from the buffer
|
| 154 |
+
CSV_BUFFER.seek(0)
|
| 155 |
+
df = pd.read_csv(CSV_BUFFER)
|
| 156 |
+
|
| 157 |
+
print(f"Total move entries (rows) generated: **{len(df)}**")
|
| 158 |
+
|
| 159 |
+
# Save the DataFrame to a CSV file for persistence
|
| 160 |
+
df.to_csv('tic_tac_toe_dataset.csv', index=False)
|
| 161 |
+
print("\n💾 Dataset saved to **tic_tac_toe_dataset.csv**")
|