tic tac toe gpt with comments
unknown
python
2 years ago
3.0 kB
26
Indexable
class Cell:
def __init__(self):
# Initialize a cell with an empty value
self.value = ' '
def __str__(self):
# Convert the cell value to a string for display
return str(self.value)
class Player:
def __init__(self, symbol):
# Initialize a player with a given symbol ('X' or 'O')
self.symbol = symbol
def __str__(self):
# Convert the player's symbol to a string for display
return self.symbol
class TicTacToe:
def __init__(self):
# Initialize the Tic Tac Toe board with Cell objects
self.board = [[Cell() for _ in range(3)] for _ in range(3)]
# Initialize the current player as Player 'X'
self.current_player = Player('X')
def print_board(self):
# Print the Tic Tac Toe board
for row in self.board:
print("|".join(str(cell) for cell in row))
print("-----")
def make_move(self, row, col):
# Make a move on the board if the selected cell is empty
if self.board[row][col].value == ' ':
# Set the value of the cell to the current player's symbol
self.board[row][col].value = str(self.current_player)
# Switch to the other player for the next move
self.current_player = Player('O') if str(self.current_player) == 'X' else Player('X')
else:
# Display an error message if the cell is already taken
print("Invalid move. Cell already taken.")
def check_winner(self):
# Check rows for a winner
for row in self.board:
if all(cell.value == row[0].value and cell.value != ' ' for cell in row):
return str(row[0])
# Check columns for a winner
for col in range(3):
if all(self.board[row][col].value == self.board[0][col].value and self.board[row][col].value != ' ' for row in range(3)):
return str(self.board[0][col])
# Check diagonals for a winner
if all(self.board[i][i].value == self.board[0][0].value and self.board[i][i].value != ' ' for i in range(3)):
return str(self.board[0][0])
if all(self.board[i][2 - i].value == self.board[0][2].value and self.board[i][2 - i].value != ' ' for i in range(3)):
return str(self.board[0][2])
# Return None if there is no winner yet
return None
# Example usage
game = TicTacToe()
while True:
game.print_board()
row = int(input("Enter row (0, 1, or 2): "))
col = int(input("Enter column (0, 1, or 2): "))
game.make_move(row, col)
winner = game.check_winner()
if winner:
game.print_board()
print(f"Player {winner} wins!")
break
if all(cell.value != ' ' for row in game.board for cell in row):
game.print_board()
print("It's a tie!")
break
Editor is loading...
Leave a Comment