Develop a Game in Python – Tic Tac Toe

spyrokp@gmail.com Avatar
\"Develop

Tic Tac Toe is a classic, two-player game that is often played on paper or a game board. The game is simple to learn and quick to play, making it a popular choice for kids and adults alike.

The game is played on a 3×3 grid, where each player takes turns placing either an \”X\” or an \”O\” on the board. The goal is to get three of your symbols in a row, either horizontally, vertically, or diagonally. If all nine spaces are filled and no player has won, the game is a tie.

Tic Tac Toe is a game of strategy and anticipation, as each player tries to outmaneuver their opponent to get three in a row while blocking their opponent\’s attempts to do the same. It\’s a fun way to pass the time and exercise your brainpower!

First, we\’ll set up our game board as a list of lists. Each inner list will represent a row on the board, and each element in the inner list will represent a space on the board. We\’ll initialize each space to be empty, represented by a dash \”-\”:

board = [    [\”-\”, \”-\”, \”-\”],

    [\”-\”, \”-\”, \”-\”],

    [\”-\”, \”-\”, \”-\”]

]

Next, we\’ll define a function to print the current state of the board:

def print_board(board):

    for row in board:

        print(\” \”.join(row))

This function iterates over each row in the board and joins the elements together with a space character, then prints the resulting string to the console.

Now, let\’s define a function to get the user\’s input for their move:

def get_move(player):

    print(f\”It\’s {player}\’s turn.\”)

    row = int(input(\”Enter row (1-3): \”)) – 1

    col = int(input(\”Enter column (1-3): \”)) – 1

    return row, col

This function takes the player\’s symbol (\”X\” or \”O\”) as an argument and prompts them to enter the row and column they want to place their symbol in. We subtract 1 from the user\’s input to convert it to 0-based indexing (since our board list uses 0-based indexing).

Next, let\’s define a function to make a move on the board:

def make_move(board, row, col, player):

    board[row][col] = player

Now, let\’s define a function to check if the game is over:

def game_over(board):

    for row in board:

        if row.count(row[0]) == len(row) and row[0] != \”-\”:

            return True

    for col in range(len(board)):

        check = []

        for row in board:

            check.append(row[col])

        if check.count(check[0]) == len(check) and check[0] != \”-\”:

            return True

    diag1 = []

    diag2 = []

    for i in range(len(board)):

        diag1.append(board[i][i])

        diag2.append(board[i][len(board)-i-1])

    if diag1.count(diag1[0]) == len(diag1) and diag1[0] != \”-\”:

Also Read:

Best Python projects for beginners