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

    We respect your privacy. Unsubscribe at anytime.

    Python Project: Four in a Row Game (3 Core Programming Skills)

    Implement a four-in-a-row game in Python

    On a high level, you will learn about the following creating a four-in-a-row game in Python.

    1. Logic and control flow. A four-in-a-row game requires a lot of logical operations, such as checking for a win condition and determining the best move to make. By implementing these operations using functions and conditional statements, a Python programmer can learn how to write code that responds to different inputs and produces different outputs.
    2. Data structures. A four-in-a-row game involves storing and manipulating large amounts of data, such as the state of the game board and the positions of the game pieces. By using data structures such as lists and dictionaries, you will learn how to manage complex data sets and perform operations on them efficiently.
    3. User interaction. A four-in-a-row game requires a user interface that allows the player to interact with the game and make moves. This can be extended to make a GUI, here we will keep it in text mode.

    Are you ready?

    Project Description

    Four-in-a-row is a two-player strategy game where the objective is to connect four of your pieces vertically, horizontally, or diagonally on a grid of six rows and seven columns.

    Players take turns dropping their colored discs into one of the columns, with the disc occupying the lowest unoccupied space in that column.

    The first player to connect four of their discs in a row wins the game.

    How to implement that?

    Project Design

    We know that breaking a project down into smaller steps is a great way to make it easier to implement.

    A simple way is to consider how a game is structured. One way to break the four-in-a-row game in Python down could be as follows.

    1. The board data structure
    2. Display board
    3. Get player 0 move
    4. Check if the game is won or the board is full
    5. Display board
    6. Get player X move
    7. Check if the game is won or the board is full

    If you think about it, you only need to implement the first 4 steps, then you can implement the game.

    Step 1 The board data structure

    The most important decision is how you want to represent the board.

    This has an impact on the rest of the code in your project.

    The board has 6 rows and 7 columns.

    empty = '·'
    board = [[empty]*7 for _ in range(6)]
    

    Here we define a specific character empty we will use. This makes some code easier to read later.

    Step 2 Display board

    Here we use the Notebook clear_output. If you are not writing code in a Notebook, you cannot use it the import and you will have to leave it out.

    But here we use loops and functions to accomplish what we want.

    Obviously, if you want to make it more advanced you can do that.

    from IPython.display import clear_output
    def display_board(board):
        clear_output()
        print(' 0123456')
        print('+' + '-'*7 + '+')
        for row in board:
            print('|', end='')
            for col in row:
                print(col, end='')
            print('|')
        print('+' + '-'*7 + '+')
    

    Step 3 Get the player move

    Now if you implement this one with a marker, it can be used for both players.

    A simple way is to break this down into two functions.

    One that prompts the user until a valid move is given.

    Another one is to check if a move is valid.

    def valid_move(board, move):
        if len(move) != 1:
            return False
        
        if move not in '0123456':
            return False
        
        if board[0][int(move)] == empty:
            return True
        
        return False
    def get_player_move(board, marker):
        while True:
            print('Player:', marker)
            move = input('Input move:')
            if valid_move(board, move):
                return int(move)
            print('Invalid move')
    

    Step 4 Check if won or done

    This is by far the most complex to write.

    Let’s break it down into functions.

    To check if the game is done (but not won) is to check if the board is full. This can be done simply like the following.

    def is_full(board):
        for col in board[0]:
            if col == empty:
                return False
            
        return True
    

    Now check if the player has 4 in a row. This needs to be done horizontally, vertically, and diagonally.

    Again, break it down into more functions. One way could be as follows.

    def get_transpose(board):
        trans = []
        
        for i in range(len(board[0])):
            col = []
            for row in board:
                col.append(row[i])
                
            trans.append(col)
        return trans
    def four_in_row(board, marker):
        for row in board:
            row_str = ''.join(row)
            if marker*4 in row_str:
                return True
        return False
    def game_won(board, marker):
        # Check rows
        if four_in_row(board, marker):
            return True
        
        # Check columns
        trans = get_transpose(board)
        if four_in_row(trans, marker):
            return True
        
        # Check diagonal
        diag = []
        for idx, row in enumerate(board):
            diag.append([empty]*idx + row + [empty]*(6 - idx))
        diag_t = get_transpose(diag)
        if four_in_row(diag_t, marker):
            return True
          
        diag = []
        for idx, row in enumerate(board):
            diag.append([empty]*(6 - idx) + row + [empty]*idx)
        diag_t = get_transpose(diag)
        if four_in_row(diag_t, marker):
            return True
        return False 
    

    Combining it into a game

    Now we just need to combine it all into a game.

    empty = '·'
    board = [[empty]*7 for _ in range(6)]
    while True:
        display_board(board)
        move = get_player_move(board, 'O')
        board = place_marker(board, move, 'O')
        if game_won(board, 'O') or is_full(board):
            display_board(board)
            print('Done')
            break
            
        display_board(board)
        move = get_player_move(board, 'X')
        board = place_marker(board, move, 'X')
        if game_won(board, 'X') or is_full(board):
            display_board(board)
            print('Done')
            break
    

    Now isn’t that great?

    Want more Python projects?

    This is part of 19 Python Projects and you can build a tic tac toe game in Python and create a computer against human game.

    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