Build a Command-Line Tic Tac Toe Game in Python (With Download)



Published on: May 13, 2025
By: CODE GEAR

Want a fun way to practice Python? Build a Tic Tac Toe game you can play right in your terminal! This project is beginner-friendly and teaches important programming skills like loops, conditionals, and functions.


---

What You'll Learn

•Drawing a game board

Accepting user input

Switching turns between players

Checking for wins or draws

Adding replay functionality



---

⬇️ Download Full Code (tic_tac_toe.py)

You can also copy and paste the full code below.


---

Full Python Code (With Replay Option)

def draw_board(board):
    print("\n")
    for i in range(3):
        row = " | ".join(board[i])
        print(f" {row} ")
        if i < 2:
            print("---+---+---")
    print("\n")

def check_winner(board, mark):
    for i in range(3):
        if all(board[i][j] == mark for j in range(3)): return True
        if all(board[j][i] == mark for j in range(3)): return True
    if all(board[i][i] == mark for i in range(3)) or all(board[i][2 - i] == mark for i in range(3)):
        return True
    return False

def is_full(board):
    return all(cell in ['X', 'O'] for row in board for cell in row)

def get_move(player, board):
    while True:
        try:
            move = int(input(f"{player['name']} ({player['mark']}), choose a position (1-9): "))
            if move < 1 or move > 9:
                print("Please enter a number between 1 and 9.")
                continue
            row, col = divmod(move - 1, 3)
            if board[row][col] in ['X', 'O']:
                print("That spot is already taken. Try again.")
            else:
                return row, col
        except ValueError:
            print("Invalid input. Please enter a number.")

def play_game(player1, player2):
    board = [[str(3 * i + j + 1) for j in range(3)] for i in range(3)]
    players = [player1, player2]
    current = 0

    while True:
        draw_board(board)
        row, col = get_move(players[current], board)
        board[row][col] = players[current]['mark']

        if check_winner(board, players[current]['mark']):
            draw_board(board)
            print(f"Congratulations, {players[current]['name']}! You win!")
            break

        if is_full(board):
            draw_board(board)
            print("It's a draw!")
            break

        current = 1 - current

def main():
    print("=== Welcome to Tic Tac Toe ===")
    print("Two players will take turns marking X and O on the grid.")
    print("To win, get 3 marks in a row — horizontally, vertically, or diagonally.")
    print("-----------------------------------------------")

    player1 = {"name": input("Enter name for Player 1 (X): ").strip() or "Player 1", "mark": "X"}
    player2 = {"name": input("Enter name for Player 2 (O): ").strip() or "Player 2", "mark": "O"}

    print(f"\nLet the game begin: {player1['name']} vs {player2['name']}!\n")

    while True:
        play_game(player1, player2)
        again = input("Do you want to play again? (y/n): ").strip().lower()
        if again != 'y':
            print("Thanks for playing Tic Tac Toe!")
            break

if __name__ == "__main__":
    main()


---

How It Works (Step-by-Step)

1. Board Setup: A 3x3 board is created using numbers 1–9.


2. Drawing the Board: draw_board() shows the current state after each move.


3. Checking for Winner: check_winner() detects a win via rows, columns, or diagonals.


4. Taking Player Input: get_move() ensures valid input and handles position selection.


5. Game Loop: play_game() alternates turns, checks for win/draw, and ends the match.


6. Replay Option: After one match, players can choose to play again.




---

Try It Out

Save the file as tic_tac_toe.py and run it:

python tic_tac_toe.py

Output:

=== Welcome to Tic Tac Toe ===
Two players will take turns marking X and O on the grid.
To win, get 3 marks in a row — horizontally, vertically, or diagonally.
-----------------------------------------------
Enter name for Player 1 (X): Alice
Enter name for Player 2 (O): Bob

Let the game begin: Alice vs Bob!


মন্তব্যসমূহ

এই ব্লগটি থেকে জনপ্রিয় পোস্টগুলি

Build a Simple In-Memory Key-Value Database with Login and Admin Access (Python)