Learn how you can become a Python programmer in just 12 weeks.

    We respect your privacy. Unsubscribe at anytime.

    Python Project: Tic Tac Toe Game Play Against Computer

    Why create an interactive game as a Python developer

    Implementing an interactive game, like Tic Tac Toe in Python, as a programmer can be an exciting and rewarding experience with several benefits.

    reasons to create an interactive game as a python developer

    Here are some of the most important reasons why implementing an interactive game, like the Tic Tac Toe game in Python, is valuable for a programmer:

    1. Creative Expression. Developing an interactive game provides programmers with a unique opportunity to express their creativity and imagination. Games often involve designing characters, creating worlds, and developing game mechanics, all of which require a high degree of creativity.
    2. Problem-Solving. Developing a game involves solving a wide range of problems, from designing the game’s architecture to implementing the game mechanics. This process can help programmers develop their problem-solving skills and learn how to approach complex challenges.
    3. Learning. Developing an interactive game can be a great way to learn new programming languages, libraries, and tools. Game development often requires working with a wide range of technologies, from game engines to graphics libraries, which can broaden a programmer’s skill set.
    4. Collaboration. Game development often requires working in a team, which can help programmers develop collaboration and communication skills. Building a game requires designers, artists, and developers to work together to achieve a shared goal, which can help programmers understand the importance of teamwork and collaboration.
    5. Engagement. Games are interactive by nature, which makes them an engaging and immersive experience. Implementing an interactive game can help programmers understand how to build user interfaces that are easy to use and engaging, which is valuable in many other applications beyond games.
    6. Marketable Skills. Game development is a highly valued skill in the tech industry, and building a game can help programmers develop a portfolio that demonstrates their expertise in programming, problem-solving, and collaboration.
    Watch tutorial!

    Overall, implementing an interactive game is a valuable experience for a programmer that can help them develop a wide range of skills, from creativity and problem-solving to collaboration and communication. Plus, the satisfaction of building a game that others enjoy playing can be an incredibly rewarding experience.

    Project Description

    Tic Tac Toe is a two-player game where each player takes turns placing X’s or O’s on a 3×3 grid.

    The objective is to get three of your symbols in a row, either horizontally, vertically, or diagonally, while preventing your opponent from doing the same.

    The game ends in a draw if the grid is full and neither player has won.

    It is a simple and popular game often used to teach basic game theory and programming concepts.

    The goal of this project is to implement a game, where the player is O and the computer is X. In this simple version, you implement the player O always start.

    Design of Project

    As we have learned, it is important to make a design of your project before you start to code. This is also true for implementing the Tic Tac Toe game in Python.

    • It clarifies the project requirements, making it easier to understand the nature of what you need to implement.
    • It gives structure to the project, making it easier to know what to code and how to connect the pieces.
    • It saves time, as you have planned the full implementation, and is, therefore, less likely to get surprises.
    • It facilitates collaboration, as you can branch out and implement pieces independently.

    Not to forget, it makes your code easy to test in individual parts.

    One way to break down a game is by following the logical flow of the game.

    It is important to understand that this flow could be considered as follows.

    Tic tac toe game in Python

    This can be done as follows for a tic tac toe game.

    1. Setup board
    2. Display board
    3. Input from the user (including validation)
    4. Update board (place the marker for the player)
    5. Check if the player wins or the game is done then output it and end.
    6. Input from computer
    7. Update board (place the marker for the computer)
    8. Check if the computer wins or the game is done then output it and end.
    9. Repeat from 1.

    Now we are ready to implement the tic tac toe game in Python using functions.

    Step 0 Setup board

    While this can seem like a simple part of the project, it often has the biggest impact on the rest of the code.

    How you represent the board will influence how other parts of the code will be implemented.

    What we will use here is the simple keypad of numbers.

    Why using the keypad as representation.

    You see, using the keypad as a way to represent the board is a great way to represent it. Later, you will also see how it can simplify other parts of the code.

    Alternatively, you could have a list of lists. But try to think about how you would implement other parts of the code later. It would make it more complex.

    Hence, we keep the board as follows.

    board = ['#', '-', '-', '-', '-', '-', '-', '-', '-', '-']

    Notice, we do not use the first entry (index 0) and keep a hash symbol there. This actually doesn’t matter, because it will simplify the code as we proceed.

    The only entries we use are 1 to 9.

    Step 1 Display the board

    Already when we need to display the board, we see the power of just having it represented as a keypad.

    from IPython.display import clear_output
    def display_board(board):
        print(board[7], board[8], board[9])
        print(board[4], board[5], board[6])
        print(board[1], board[2], board[3])

    This makes it clear and concise what the board looks like and is easy to understand as a programmer.

    Notice this code is made for Notebooks, if you do not use Notebooks, you cannot use the import and clear_output().

    If you want to make a more fancy display, you are welcome.

    Step 2 Input from the user

    User interaction is often a bit complex. The user may interact in the wrong way.

    Therefore you often need validation of the input.

    A great way to do that is by using while loops.

    def valid_move(board, input_str):
        Return true if move valid (1-9 and available).
        if len(input_str) != 1:
            return False
        if input_str not in '123456789':
            return False
        move = int(input_str)
        if board[move] != '-':
            return False
        return True
    def player_input(board):
        Input player move. Prompts the user until valid move
        meaning (1-9) and position available.
        Returns the valid move.
        while True:
            input_str = input('Input move (1-9): ')
            if valid_move(board, input_str):
                return int(input_str)
            print('Invalid move')

    You see, the user is prompted until a valid move has been made.

    This is a great way to implement it, as it makes it easy for somebody reading the code as well.

    Always think about the future person reading the code. How can you design and make the implementation easy?

    Step 3 Update the board

    This is straightforward, but there is one thing to remember.

    We have already validated that the player makes a valid move, therefore it is straightforward to implement this part.

    def place_marker(board, marker, move):
        Places the marker at position on board and returns it.
        board[move] = marker
        return board

    You may think creating a function for this is a bit too much, but it will simplify and make your final code more readable and easier to understand. The function name tells the reader of the code what the intention is, also, the doc string tells about that.

    If you just put the code somewhere, the reader can see what happens, but not know what the intention was, making it difficult to understand.

    Step 4 Check if the game is done

    We need to check two things.

    1. Are there any moves left (is the board filled)
    2. Did the player win?

    This can be implemented in two functions as follows.

    def is_done(board):
        Returns True if the board is filled and game is done.
        for pos in board[1:]:
            if pos == '-':
                return False
        return True
    def player_won(board, marker):
        Return True if player with marker has won.
        if board[7] == board[8] == board[9] == marker:  # top row
            return True
        if board[4] == board[5] == board[6] == marker:  # middle row
            return True
        if board[1] == board[2] == board[3] == marker:  # low row
            return True
        if board[7] == board[4] == board[1] == marker:  # left column
            return True
        if board[8] == board[5] == board[2] == marker:  # middle column
            return True
        if board[9] == board[6] == board[3] == marker:  # right column
            return True
        if board[7] == board[5] == board[3] == marker:  # diagonal
            return True
        if board[9] == board[5] == board[1] == marker:  # diagonal
            return True
        return False

    First notice, that is_done could be implemented more elegantly, but it does the job.

    Secondly, player_won now uses the power of implementing the board as a keypad. It makes it easy to test.

    Step 5 Computer move

    Now we need a move from the computer.

    We will make a simple random move.

    But how do we do that?

    Simply, just make a random choice and see if it is valid.

    You can get randomness by using Python’s standard library.

    from random import randrange
    def get_random_postion():
        Returns a random integer from 1-9 (both inclusive)
        return randrange(1, 10)
    def get_computer_move(board):
        Returns a random move by the computer which is valid.
        while True:
            random_move = get_random_postion()
            if board[random_move] == '-':
                return random_move

    See, this is easy to implement and understand.

    And actually, now we implemented all we need.

    Putting it all together

    Now we can implement our tic tac toe game.

    def play_game():
        Plays a game of Tic Toc Toe with the computer.
        # 0: setup board
        board = ['#', '-', '-', '-', '-', '-', '-', '-', '-', '-']
        while True:
            pos = player_input(board)
            place_marker(board, 'O', pos)
            if is_done(board) or player_won(board, 'O'):
                print('Game done!')
            c_pos = get_computer_move(board)
            place_marker(board, 'X', c_pos)
            if is_done(board) or player_won(board, 'X'):
                print('Game done!')

    You can make a more advanced version where it is random whether the user starts or not.

    Want more Python projects?

    This is part of 19 Python Projects and you can learn about data processing with this IMDB data project.

    Python for Finance: Unlock Financial Freedom and Build Your Dream Life

    Discover the key to financial freedom and secure your dream life with Python for Finance!

    Say goodbye to financial anxiety and embrace a future filled with confidence and success. If you’re tired of struggling to pay bills and longing for a life of leisure, it’s time to take action.

    Imagine breaking free from that dead-end job and opening doors to endless opportunities. With Python for Finance, you can acquire the invaluable skill of financial analysis that will revolutionize your life.

    Make informed investment decisions, unlock the secrets of business financial performance, and maximize your money like never before. Gain the knowledge sought after by companies worldwide and become an indispensable asset in today’s competitive market.

    Don’t let your dreams slip away. Master Python for Finance and pave your way to a profitable and fulfilling career. Start building the future you deserve today!

    Python for Finance a 21 hours course that teaches investing with Python.

    Learn pandas, NumPy, Matplotlib for Financial Analysis & learn how to Automate Value Investing.

    “Excellent course for anyone trying to learn coding and investing.” – Lorenzo B.

    Leave a Comment