Creating a Connect Four Game Using Python With Source Code

Introduction :

Connect Four is a classic two-player connection game where players take turns dropping colored discs into a grid, aiming to connect four of their own discs in a row—vertically, horizontally, or diagonally. In this tutorial, we’ll build a simple Connect Four game using Python and the turtle graphics module. This Connect Four game is designed for two players to play alternately, with one player using red discs and the other using yellow. The game board is a 7-column by 6-row grid where players drop their discs into columns, and the discs fall to the lowest available position within the selected column. The game continues until one player connects four discs in a row or the board fills up

Required Modules :

To run this project, you need the turtle and free games modules. If you don’t have free games installed, you can install it using

				
					pip install freegames
				
			

How to Run the Code :-

1. Install Dependencies :

○ Ensure Python is installed.
○ Install the freegames module using pip.

2. Run the Code:

○ Save the provided code in a file named connect_four.py.
Run the script using Python:

				
					 python connect_four.py
				
			

 3. Play the Game:

○ Agraphical window will open displaying the Connect Four grid.
○ Click on the columns to drop discs and play the game.

Code Explanation :

Let’s break down the code to understand how the Connect Four game is implemented:

1. Importing Modules

				
					 from turtle import *
 from freegames import line
				
			

 ● turtle: Used for graphical output.
linefromfreegames: Used to draw lines on the screen.

2. Initializing Variables

				
					turns = {'red': 'yellow', 'yellow': 'red'}
 state = {'player': 'yellow', 'rows': [0] * 8}

				
			

turns: Adictionary to manage player turns, alternating between ‘red’ and ‘yellow’.
● state: Adictionary to keep track of the current player and the number of discs in each column (rows)

3. Drawing the Grid

				
					 def grid():
 """Draw Connect Four grid."""
 bgcolor('light blue')
 for x in range(-150, 200, 50):
 line(x,-200, x, 200)
 for x in range(-175, 200, 50):
 for y in range(-175, 200, 50):
 up()
 goto(x, y)
 dot(40, 'white')
 update()
				
			

grid(): Sets up the Connect Four game board. It draws vertical and horizontal lines to create the grid and places white circles in each cell to represent empty spaces.

4. Handling Clicks

				
					 def tap(x, y):
 """Draw red or yellow circle in tapped row."""
 player = state['player']
 rows = state['rows']
 row = int((x + 200) // 50)
 count = rows[row]
 x = ((x + 200) // 50) * 50- 200 + 25
 y = count * 50- 200 + 25
up()
 goto(x, y)
 dot(40, player)
 update()
 rows[row] = count + 1
 state['player'] = turns[player]
				
			

tap(x, y): Handles mouse clicks. When a column is clicked, it calculates the position to place the disc (either red or yellow) and updates the game state. It then switches the current player

5. Setting Up the Game

				
					setup(420, 420, 370, 0)
 hideturtle()
 tracer(False)
 grid()
 onscreenclick(tap)
 done()
				
			

 ● setup(): Initializes the graphical window with a width and height of 420.
● hideturtle(): Hides the turtle cursor for a cleaner look.
● tracer(False): Disables automatic screen updates for better performance.
● grid(): Draws the game grid.
● onscreenclick(tap): Sets up the tap() function to handle mouse clicks.
● done(): Completes the setup and starts the game loop

Source Code :

				
					from turtle import *
from freegames import line

turns = {'red': 'yellow', 'yellow': 'red'}
state = {'player': 'yellow', 'rows': [0] * 8}

def grid():
    """Draw Connect Four grid."""
    bgcolor('light blue')
    for x in range(-150, 200, 50):
        line(x, -200, x, 200)
    for x in range(-175, 200, 50):
        for y in range(-175, 200, 50):
            up()
            goto(x, y)
            dot(40, 'white')
    update()

def tap(x, y):
    """Draw red or yellow circle in tapped row."""
    player = state['player']
    rows = state['rows']
    row = int((x + 200) // 50)
    count = rows[row]
    x = ((x + 200) // 50) * 50 - 200 + 25
    y = count * 50 - 200 + 25
    up()
    goto(x, y)
    dot(40, player)
    update()
    rows[row] = count + 1
    state['player'] = turns[player]

setup(420, 420, 370, 0)
hideturtle()
tracer(False)
grid()
onscreenclick(tap)
done()

				
			

Output :

Running the code will open a graphical window displaying the Connect Four game board. Players can click on columns to drop discs and play the game. The screen will update to reflect the current game state and the active player

Find More Projects

Drawing Ganesha Using Python Turtle Graphics[Drawing Ganapati Using Python] Introduction In this blog post, we will learn how to draw Lord Ganesha …

Contact Management System in Python with a Graphical User Interface (GUI) Introduction: The Contact Management System is a Python-based application designed to …

KBC Game using Python with Source Code Introduction : Welcome to this blog post on building a “Kaun Banega Crorepati” (KBC) game …

Basic Logging System in C++ With Source Code Introduction : It is one of the most important practices in software development. Logging …

Snake Game Using C++ With Source Code Introduction : The Snake Game is one of the most well-known arcade games, having its …

C++ Hotel Management System With Source Code Introduction : It is very important to manage the hotels effectively to avail better customer …

Get Huge Discounts
More Python Projects

Download From Telegram