Do you know a game called Ultimate Tic-tac-toe? Implement it in Python.
- User
Do you know a game called Ultimate Tic-tac-toe? Implement it in Python.
- Assistant
Do you know a game called Ultimate Tic-tac-toe? Implement it in Python.
Yes, I’m familiar with Ultimate Tic-Tac-Toe! It’s a more strategic and complex version of the classic Tic-Tac-Toe game. Below is a Python implementation of Ultimate Tic-Tac-Toe that you can run in your local environment.
Ultimate Tic-Tac-Toe consists of a 3x3 grid of smaller Tic-Tac-Toe boards. Here's how it works:
Below is a Python script that implements Ultimate Tic-Tac-Toe. The game is played in the console, and players take turns entering their moves.
import sys
class SmallBoard:
def __init__(self):
# Initialize a 3x3 small board with empty cells
self.board = [[' ' for _ in range(3)] for _ in range(3)]
self.winner = None # 'X', 'O', or 'Tie'
def make_move(self, row, col, player):
if self.board[row][col] == ' ':
self.board[row][col] = player
self.check_winner()
return True
else:
return False
def check_winner(self):
lines = (
# Horizontal
self.board[0],
self.board[1],
self.board[2],
# Vertical
[self.board[0][0], self.board[1][0], self.board[2][0]],
[self.board[0][1], self.board[1][1], self.board[2][1]],
[self.board[0][2], self.board[1][2], self.board[2][2]],
# Diagonals
[self.board[0][0], self.board[1][1], self.board[2][2]],
[self.board[0][2], self.board[1][1], self.board[2][0]],
)
for line in lines:
if line[0] == line[1] == line[2] and line[0] != ' ':
self.winner = line[0]
return
# Check for Tie
if all(cell != ' ' for row in self.board for cell in row):
self.winner = 'Tie'
def is_full(self):
return all(cell != ' ' for row in self.board for cell in row)
def is_available(self):
return self.winner is None
def __str__(self):
return '\n'.join(['|'.join(row) for row in self.board])
class UltimateTicTacToe:
def __init__(self):
# Initialize a 3x3 grid of SmallBoards
self.boards = [[SmallBoard() for _ in range(3)] for _ in range(3)]
self.current_player = 'X'
self.last_move = None # (row, col) of the last move in the small board
self.overall_winner = None
def switch_player(self):
self.current_player = 'O' if self.current_player == 'X' else 'X'
def make_move(self, board_row, board_col, cell_row, cell_col):
small_board = self.boards[board_row][board_col]
if not small_board.is_available():
print("Selected small board is already won or tied. Choose another board.")
return False
if small_board.make_move(cell_row, cell_col, self.current_player):
self.last_move = (cell_row, cell_col)
self.check_overall_winner()
self.switch_player()
return True
else:
print("Cell is already occupied. Choose another cell.")
return False
def get_available_boards(self):
if self.last_move is None:
# Any board is available
return [(i, j) for i in range(3) for j in range(3) if self.boards[i][j].is_available()]
else:
target_board = self.last_move
if self.boards[target_board[0]][target_board[1]].is_available():
return [target_board]
else:
return [(i, j) for i in range(3) for j in range(3) if self.boards[i][j].is_available()]
def check_overall_winner(self):
# Check rows, columns, and diagonals for overall winner
def get_winner(i, j):
return self.boards[i][j].winner if self.boards[i][j].winner in ['X', 'O'] else None
lines = [
# Rows
[get_winner(0, 0), get_winner(0, 1), get_winner(0, 2)],
[get_winner(1, 0), get_winner(1, 1), get_winner(1, 2)],
[get_winner(2, 0), get_winner(2, 1), get_winner(2, 2)],
# Columns
[get_winner(0, 0), get_winner(1, 0), get_winner(2, 0)],
[get_winner(0, 1), get_winner(1, 1), get_winner(2, 1)],
[get_winner(0, 2), get_winner(1, 2), get_winner(2, 2)],
# Diagonals
[get_winner(0, 0), get_winner(1, 1), get_winner(2, 2)],
[get_winner(0, 2), get_winner(1, 1), get_winner(2, 0)],
]
for line in lines:
if line[0] == line[1] == line[2] and line[0] is not None:
self.overall_winner = line[0]
return
# Check for Tie
if all(board.winner is not None for row in self.boards for board in row):
self.overall_winner = 'Tie'
def render(self):
# Render the entire Ultimate Tic-Tac-Toe board
def render_row(row_boards, row_idx):
rows = ['' for _ in range(3)]
for board in row_boards:
for i in range(3):
rows[i] += ' ' + board.board[i][0] + '|' + board.board[i][1] + '|' + board.board[i][2] + ' '
if board != row_boards[-1]:
rows[i] += '||'
return '\n'.join(rows)
board_strings = []
for row in self.boards:
board_strings.append(render_row(row, self.boards.index(row)))
if row != self.boards[-1]:
board_strings.append('='*len(board_strings[0]))
print('\n'.join(board_strings))
def play(self):
while self.overall_winner is None:
self.render()
print(f"Player {self.current_player}'s turn.")
available_boards = self.get_available_boards()
if self.last_move is None:
print("You can play in any board.")
else:
if len(available_boards) ==1:
print(f"You must play in board at position {available_boards[0]}")
else:
print("You can choose any of the available boards.")
try:
# Input format: board_row board_col cell_row cell_col
move = input("Enter your move as 'board_row board_col cell_row cell_col': ")
board_r, board_c, cell_r, cell_c = map(int, move.strip().split())
if (board_r, board_c) not in available_boards:
print("Selected board is not available. Try again.")
continue
if not (0 <= board_r <=2 and 0<=board_c<=2 and 0<=cell_r<=2 and 0<=cell_c<=2):
print("Invalid input. Rows and columns must be between 0 and 2.")
continue
if self.make_move(board_r, board_c, cell_r, cell_c):
continue
except ValueError:
print("Invalid input format. Please enter four integers separated by spaces.")
continue
self.render()
if self.overall_winner == 'Tie':
print("The game ends in a tie!")
else:
print(f"Player {self.overall_winner} wins the game!")
if __name__ == "__main__":
game = UltimateTicTacToe()
game.play()
Save the Code: Copy the above code and save it in a file named ultimate_tic_tac_toe.py.
Run the Script:
ultimate_tic_tac_toe.py.python ultimate_tic_tac_toe.py
Board Mapping: The game uses 0-based indexing for both small boards and cells. The main board and each small board are indexed as follows:
Boards:
(0,0) | (0,1) | (0,2)
---------------------
(1,0) | (1,1) | (1,2)
---------------------
(2,0) | (2,1) | (2,2)
Cells within a small board:
(0,0) | (0,1) | (0,2)
---------------------
(1,0) | (1,1) | (1,2)
---------------------
(2,0) | (2,1) | (2,2)
Making a Move: When prompted, enter your move in the format:
board_row board_col cell_row cell_col
For example:
0 0 1 1
This means:
Turn Rules:
(a, b) of a small board, the next move must be in the small board at position (a, b) of the main board.SmallBoard Class: Represents each small Tic-Tac-Toe board. It handles making moves, checking for a winner or tie, and displaying the board.
UltimateTicTacToe Class: Represents the overall game. It manages the grid of small boards, enforces movement rules, checks for the overall winner, and handles player turns.
User Input Validation: Ensures that players enter valid moves and provides feedback for invalid inputs.
Rendering the Board: Displays the entire Ultimate Tic-Tac-Toe board in the console after each move, making it easy to visualize the game state.
Game Over Conditions: Detects when a player has won the game or when the game ends in a tie.
AI Opponent: Implement an AI to play against instead of two human players.
Graphical Interface: Use libraries like pygame or Tkinter to create a graphical version of the game.
Improved Board Rendering: Enhance the console output for better readability, such as adding colors or clearer separators.
Save and Load Game: Allow players to save the current game state and load it later.
This Python implementation provides a solid foundation for playing Ultimate Tic-Tac-Toe in the console. Feel free to enhance it further by adding new features or improving the user interface!
Not yet included in a published release.