Simple Connect 4 Project using Python and Kivy

Posted by


Connect 4 is a classic two-player game in which the players take turns dropping colored discs into a grid. The goal is to connect four of your own discs in a row vertically, horizontally, or diagonally.

In this tutorial, we will create a simple Connect 4 game using Python and the Kivy framework for building multi-touch applications. Kivy is a Python library for developing multitouch applications. It is cross-platform and supports Android, iOS, Linux, OS X, and Windows.

To follow this tutorial, you will need to have Python and Kivy installed on your computer. You can find instructions for installing Kivy on their official website: https://kivy.org/

Let’s get started by creating the game board for our Connect 4 game. We will start by creating a simple grid layout for the game board.

from kivy.app import App
from kivy.uix.gridlayout import GridLayout

class Connect4Grid(GridLayout):
    def __init__(self, **kwargs):
        super(Connect4Grid, self).__init__(**kwargs)
        self.cols = 7
        for i in range(42):
            self.add_widget(Button())

class Connect4App(App):
    def build(self):
        return Connect4Grid()

if __name__ == '__main__':
    Connect4App().run()

In the code above, we have created a Connect4Grid class that extends the GridLayout class from Kivy. We set the number of columns in the grid layout to 7, representing the 7 columns of the Connect 4 game board. We then loop through 42 times to add 42 Button widgets to the grid layout, representing the 42 slots on the game board.

Next, let’s add interactivity to our game by allowing players to drop discs into the columns of the game board. We will create a DropDisc method that will be called when a player taps on a column to drop a disc.

class Connect4Grid(GridLayout):
    def __init__(self, **kwargs):
        super(Connect4Grid, self).__init__(**kwargs)
        self.cols = 7
        for i in range(42):
            btn = Button()
            btn.bind(on_press=self.drop_disc)
            self.add_widget(btn)

    def drop_disc(self, instance):
        column = self.children.index(instance) % 7
        print(f'Dropped disc in column {column}')

In the updated code, we have added a drop_disc method that is called when a button in the grid layout is pressed. The method calculates the column index of the button that was pressed and prints a message indicating the column in which the disc was dropped.

Finally, let’s add logic to check for a winning condition in our game. We will implement a check_winner method that will check for four discs in a row vertically, horizontally, or diagonally.

class Connect4Grid(GridLayout):
    def __init__(self, **kwargs):
        super(Connect4Grid, self).__init__(**kwargs)
        self.cols = 7
        self.board = [[' ' for _ in range(7)] for _ in range(6)]
        for i in range(42):
            btn = Button()
            btn.bind(on_press=self.drop_disc)
            self.add_widget(btn)

    def drop_disc(self, instance):
        column = self.children.index(instance) % 7
        for i in range(6):
            if self.board[i][column] == ' ':
                self.board[i][column] = 'X'
                print(f'Dropped disc in column {column}')
                self.check_winner(i, column)
                break

    def check_winner(self, row, column):
        # Check for vertical, horizontal, and diagonal wins
        pass

In the updated code, we have added a 6×7 grid representing the game board, stored as a list of lists. When a player drops a disc, we update the board with the player’s symbol (‘X’) and call the check_winner method with the row and column index of the dropped disc.

You can now continue to implement the check_winner method to check for winning conditions in the game. You can implement this logic by checking for four matching discs in a row vertically, horizontally, or diagonally.

This tutorial covers the basic structure of a simple Connect 4 game using Python and the Kivy framework. You can further enhance the game by adding features such as a graphical user interface, animations, and multiplayer functionality.

I hope you found this tutorial helpful in creating your own Connect 4 game project. Happy coding!

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@codebored8625
3 months ago

Python Kivy
I make this on mobile using pydroid3 if your wondering, as if…

@sksahil4374
3 months ago

Nice work

@cubefox5736
3 months ago

Looks amazing best connect 4 Computer Version i have Seen 🥰