Table of Contents

, , , , , , , , ,

About the Club

Python Club Topics - Exercise: Guess my number game

Exercise: Tic Tac Toe

  1. Output: Create the game of Tic Tac Toe for 2 players
  2. What you learn from the example:
    1. Use loops, conditionals, and functions
    2. Get input from user
    3. Use lists

Solution

[1] code:python show
def print_board(board):
    for row in board:
        print(“ | ”.join(row))
        print(“-” * 9)

def check_win(board, player):
    for i in range(3):
        if all([board[i][j] == player for j in range(3)]) or \
           all([board[j][i] == player for j 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 tic_tac_toe():
    board = [[“ ” for _ in range(3)] for _ in range(3)]
    current_player = “X”
    moves = 0

    while moves < 9:
        print_board(board)
        row = int(input(f“Player {current_player}, enter row (0-2): ”))
        col = int(input(f“Player {current_player}, enter column (0-2): ”))

        if row < 0 or row > 2 or col < 0 or col > 2 or board[row][col] != “ ”:
            print(“Invalid move. Try again.”)
            continue

        board[row][col] = current_player
        moves += 1

        if check_win(board, current_player):
            print_board(board)
            print(f“Player {current_player} wins!”)
            break

        current_player = “O” if current_player == “X” else “X”
    else:
        print_board(board)
        print(“It's a tie!”)

if __name__ == “__main__”:
    tic_tac_toe()