tic tac toe gpt

 avatar
unknown
python
a year ago
2.2 kB
7
Indexable
class Cell:
    def __init__(self):
        self.value = ' '

    def __str__(self):
        return str(self.value)


class Player:
    def __init__(self, symbol):
        self.symbol = symbol

    def __str__(self):
        return self.symbol


class TicTacToe:
    def __init__(self):
        self.board = [[Cell() for _ in range(3)] for _ in range(3)]
        self.current_player = Player('X')

    def print_board(self):
        for row in self.board:
            print("|".join(str(cell) for cell in row))
            print("-----")

    def make_move(self, row, col):
        if self.board[row][col].value == ' ':
            self.board[row][col].value = str(self.current_player)
            self.current_player = Player('O') if str(self.current_player) == 'X' else Player('X')
        else:
            print("Invalid move. Cell already taken.")

    def check_winner(self):
        # Check rows
        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 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
        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

# 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