create tik tak toe in python

Here is a simple implementation of tik tak toe game in python:

main.py
# Function to print Tic Tac Toe
def printBoard(board):
    print("\n")
    for i in range(3):
        for j in range(3):
            print(board[i][j], end=" ")
        print("\n")

# Function to check if any player has won
def checkWinner(board):
    # check rows
    for i in range(3):
        if (board[i][0] == board[i][1] and board[i][1] == board[i][2]):
            if (board[i][0] == 'X'):
                return 'X'
            elif (board[i][0] == 'O'):
                return 'O'
            
    # check columns
    for j in range(3):
        if (board[0][j] == board[1][j] and board[1][j] == board[2][j]):
            if (board[0][j] == 'X'):
                return 'X'
            elif (board[0][j] == 'O'):
                return 'O'
    
    # check diagonals
    if (board[0][0] == board[1][1] and board[1][1] == board[2][2]):
        if (board[0][0] == 'X'):
            return 'X'
        elif (board[0][0] == 'O'):
            return 'O'
    
    if (board[0][2] == board[1][1] and board[1][1] == board[2][0]):
        if (board[0][2] == 'X'):
            return 'X'
        elif (board[0][2] == 'O'):
            return 'O'

    # if nobody wins return None
    return None

# Function to play Tic Tac Toe
def playTicTacToe():
    # initialize board
    board = [['-' for j in range(3)] for i in range(3)]
    
    # initialize player and turn
    player = 'X'
    turn = 1
    printBoard(board)

    # loop until the game is over
    while(turn<=9):
        print()
        print(f"Player {player} turn: ")
        
        # get the user input
        try:
            row = int(input("Enter row number(0-2): "))
            col = int(input("Enter column number(0-2): "))
        except:
            print("Invalid input")
            continue
        
        # check if cell is not already occupied
        if(board[row][col] != '-'):
            print("Cell is already occupied")
            continue
        
        # mark the cell with player's symbol
        board[row][col] = player
        printBoard(board)
        # check if the current player wins
        if(checkWinner(board) == player):
            print(f"Player {player} wins the game")
            return
        
        # switch players for next turn
        if(player == 'X'):
            player = 'O'
        else:
            player = 'X'
        
        turn += 1
      
    print("Game is a tie")

playTicTacToe()
2412 chars
90 lines

In this implementation, we have used a 2D list to represent the Tic Tac Toe board. We have used two functions, one to print the board and the other to check if any player has won. The main function playTicTacToe() contains the game logic and takes input from the user to mark a position on the board. It also checks if the game is over and declares the winner.

related categories

gistlibby LogSnag