Skip to content

tic tac toe python

Certainly! Here’s a simple implementation of Tic-Tac-Toe in Python. This implementation allows two players to take turns playing the game.

def print_board(board):
    for row in board:
        print(" | ".join(row))
        print("-" * 9)

def check_winner(board, player):
    for row in board:
        if all(cell == player for cell in row):
            return True

    for col in range(3):
        if all(board[row][col] == player for row in range(3)):
            return True

    if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
        return True

    return False

def is_full(board):
    return all(cell != " " for row in board for cell in row)

def main():
    board = [[" " for _ in range(3)] for _ in range(3)]
    current_player = "X"

    while True:
        row = int(input(f"Player {current_player}, enter row (0, 1, or 2): "))
        col = int(input(f"Player {current_player}, enter column (0, 1, or 2): "))

        if board[row][col] == " ":
            board[row][col] = current_player
            print("That cell is already occupied. Try again.")

        if check_winner(board, current_player):
            print(f"Player {current_player} wins!")
        elif is_full(board):
            print("It's a draw!")

        current_player = "O" if current_player == "X" else "X"

if __name__ == "__main__":

Copy and paste this code into a Python environment, and you can play Tic-Tac-Toe in the console. Players will take turns entering row and column numbers to place their marks (‘X’ or ‘O’) on the board until there is a winner or a draw.

Leave a Reply

Your email address will not be published. Required fields are marked *


Enjoy this blog? Please spread the word :)