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

Get Discount on Top Educational Courses

Brand NameDiscount InformationCoupon Codes Link
Educative.io20% discount on Educative courses and plans
W3Schools20% discount on W3Schools courses
KodeKloud10% discount on KodeKloud courses and plans
GeeksforGeeks30% discount on GeeksforGeeks courses
Target Test Prep20% discount on Target Test Prep
Coding Ninjas₹5000 discount on Coding Ninjas courses
Skillshare40% discount on Skillshare
DataCamp50% discount on DataCamp
365 Data Science57% discount on 365 Data Science Plans
Get SmarterFlat 20% discount on Get Smarter courses
SmartKeedaFlat 40% discount on SmartKeeda courses
StackSocial20% discount on StackSocial courses

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

how to create a video background with html CSS JavaScript Introduction Hello friends, you all are welcome to today’s new blog post. …

Auto Text Effect Animation Using Html CSS & JavaScript Introduction Hello friends, welcome to today’s new blog post. Today we have created …

Windows 12 Notepad Using Python Introduction: In this article, we will create a Windows 12 Notepad using Python. If you are a …

Animated Search Bar using Html CSS And JavaScript Introduction Hello friends, all of you developers are welcome to today’s beautiful blog post. …

Best Quiz Game Using HTML CSS And JavaScript Introduction Hello coders, welcome to another new blog. Today in this article we’ll learn …

Tower Blocks Game Using HTML CSS And JavaScript Introduction Hello coders, welcome to another new blog. Today in this blog we’ll learn …

Get Huge Discounts
More Python Projects