Python Create a Simple Tic-Tac-Toe Game Class

Document 对象参考手册Python3 Examples

Tic-Tac-Toe is a classic two-player game where players take turns placing their marks (usually "X" and "O") on a 3x3 grid. The goal of the game is to be the first to form a continuous line of three identical marks horizontally, vertically, or diagonally. Below, we will create a simple Tic-Tac-Toe game class that includes basic game logic and display functionality.

Example

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

    def print_board(self):
        for row in self.board:
            print('|'.join(row))
            print('-' * 5)

    def make_move(self, row, col):
        if self.board[row][col] == ' ':
            self.board[row][col] = self.current_player
            self.current_player = 'O' if self.current_player == 'X' else 'X'
        else:
            print("Invalid move! The cell is already occupied.")

    def check_winner(self):
        # Check rows
        for row in self.board:
            if row[0] == row[1] == row[2] != ' ':
                return row[0]

        # Check columns
        for col in range(3):
            if self.board[0][col] == self.board[1][col] == self.board[2][col] != ' ':
                return self.board[0][col]

        # Check diagonals
        if self.board[0][0] == self.board[1][1] == self.board[2][2] != ' ':
            return self.board[0][0]
        if self.board[0][2] == self.board[1][1] == self.board[2][0] != ' ':
            return self.board[0][2]

        # Check for a tie
        if all(cell != ' ' for row in self.board for cell in row):
            return 'Tie'

        return None

    def play_game(self):
        while True:
            self.print_board()
            print(f"Player {self.current_player}'s turn")
            row = int(input("Enter row (0, 1, 2): "))
            col = int(input("Enter column (0, 1, 2): "))

            self.make_move(row, col)
            winner = self.check_winner()
            if winner:
                self.print_board()
                if winner == 'Tie':
                    print("It's a tie!")
                else:
                    print(f"Player {winner} wins!")
                break

Code explanation:

  1. __init__The method initializes a 3x3 empty board and sets the current player to "X".
  2. print_boardThe method is used to print the current board state.
  3. make_moveThe method allows players to place a mark at the specified row and column, and switches the current player.
  4. check_winnerThe method checks whether a player has won or whether it is a tie. It checks all rows, columns, and diagonals for three identical marks, and returns the winning player or "Tie" to indicate a draw.
  5. play_gameThe method is the main loop of the game, allowing players to take turns entering rows and columns to make moves, until a player wins or the game ends in a tie.

Output result: Runplay_gameAfter the method, the game will start, and players can take turns entering rows and columns to make moves. The game continues until a player wins or it is a tie. For example:

 | | 
-----
 | | 
-----
 | | 
-----
Player X's turn
Enter row (0, 1, 2): 0
Enter column (0, 1, 2): 0
X| | 
-----
 | | 
-----
 | | 
-----
Player O's turn
Enter row (0, 1, 2): 1
Enter column (0, 1, 2): 1
X| | 
-----
 |O| 
-----
 | | 
-----
...

The game continues until a player wins or it is a tie.

Document 对象参考手册Python3 Examples

Other Extensions