Adventures in Machine Learning

Revamp Your Game Night with Python: Building Connect Four Using NumPy and Pygame

Introduction to Connect Four Game

Have you ever played Connect Four before? Its a fun, strategic game thats perfect for two players.

The rules are simple: each player takes turns dropping colored discs into a vertical grid. The first person to connect four of their own colored discs in a horizontal, vertical, or diagonal row wins.

While it may seem easy at first, the game requires a certain level of strategic planning to outsmart your opponent. In this article, well delve deeper into the components required to code this exciting two-player game.

Well also explore the NumPy module, its definition, and purpose.

Required Modules for Coding

To code Connect Four, we will need several modules to help with programming and graphics. One of these modules is the NumPy module.

It is used to create arrays, perform mathematical operations, and work with matrices. We will also need Pygame which is responsible for graphics, sound, and user interface.

Lastly, the sys module to handle Python runtime environment parameters. The math module will be important too for complex mathematical calculations involved in the game.

NumPy Module

NumPy is a Numerical Python module that has been in use since the early 2000s. It is designed for performing complex mathematical operations in Python.

NumPy is an essential module for Connect Four because it is required to create an array to represent the gaming board. With NumPy, we can also implement mathematical operations at a much faster rate.

Installing NumPy

Before we proceed, we need to install NumPy. You can install NumPy via the Pip package installer by typing pip install numpy in your Python IDE console. Once installation is complete, you can then import NumPy into your program.

Creating the Gaming Board

The gaming board for Connect Four is a vertical grid consisting of six rows and seven columns. We can represent this board using a two-dimensional array in NumPy. We will create a function called create_board that returns a two-dimensional array with an initial value of zero representing the empty cells.

NumPy arrays are created using the zeros function, and by specifying the matrix dimension. Our create_board function will look like this:

import numpy as np

def create_board():

board = np.zeros((6, 7))

return board

The two-dimensional array will be represented in Python as follows:

board = create_board()


[[0. 0.

0. 0.

0. 0.


[0. 0.

0. 0.

0. 0.


[0. 0.

0. 0.

0. 0.


[0. 0.

0. 0.

0. 0.


[0. 0.

0. 0.

0. 0.


[0. 0.

0. 0.

0. 0.


In the output, values 0.0 represent the empty cells.

Adding Discs to the Board

After creating the grid, we need to create a function to drop discs into the board. A player will select a column in which to drop a disc, and the program will place the disc in the next available open slot in that column.

The function will be called drop_piece. It takes three arguments; the board, the row, and a column index for the selected move.

import numpy as np

def drop_piece(board, row, col, piece):

board[row][col] = piece

The function is passed the current board state, the selected row, selected column, and the disc color of the current player. Using NumPy coordinates, we assign the disc color, either 1 or 2, to the selected cell on the board.

Checking for Winning Move

Every player seeks to connect four of their discs either horizontally, vertically or diagonally. To obtain a winning move, we need to examine the board state for any winning combinations.

We will implement this using NumPy horizontal, vertical, and diagonal and anti-diagonal slicing. First, we need to define a function to detect if a particular run of four discs is a winner.

A win occurs if the sequence of four discs is either of two colors.

import numpy as np

def winning_move(board, piece):

# Check horizontal locations for win

for c in range(4):

for r in range(6):

if board[r][c] == piece and board[r][c+1] == piece and board[r][c+2] == piece and board[r][c+3] == piece:

return True

# Check vertical locations for win

for c in range(7):

for r in range(3):

if board[r][c] == piece and board[r+1][c] == piece and board[r+2][c] == piece and board[r+3][c] == piece:

return True

# Check diagonal wins

for c in range(4):

for r in range(3):

if board[r][c] == piece and board[r+1][c+1] == piece and board[r+2][c+2] == piece and board[r+3][c+3] == piece:

return True

# Check anti-diagonal wins

for c in range(4):

for r in range(3, 6):

if board[r][c] == piece and board[r-1][c+1] == piece and board[r-2][c+2] == piece and board[r-3][c+3] == piece:

return True

The function takes the values of the current board state, the current piece, and returns True if a winning move has been made.


In this article, we have covered the fundamentals of creating the Connect Four game using the NumPy module. We started by introducing the game and its rules.

Next, we moved onto discussing the modules required for coding, like Pygame, Math module, and the sys module. Finally, we delved into the NumPy module and created the gaming board, dropping discs onto the board, and implementing win conditions using NumPy slicing.

By using these techniques, you can create and program your version of this classic two-player game!

3) Pygame Module

Pygame is a Python library that helps in creating multimedia applications, especially video games. Pygame is based on the Simple DirectMedia Layer (SDL) library, which provides low-level access to audio, keyboard, mouse, joystick, and graphics hardware.

Pygame is a powerful tool that provides an interface to manage multimedia aspects seamlessly. Using Pygame, developers can create custom games, educational software, and music software.

Installing Pygame

Before starting with implementation, we need to install Pygame. To install with pip, type pip install pygame in the command prompt.

With that done, we can then import Pygame into our code. Pygame only requires the Python interpreter and some basic modules installed on your system, such as NumPy and Pythons sys module.

Implementing Pygame In Connect Four Game

Pygame is used to manage the games graphics, such as creating the game screen, drawing the pieces, and detecting mouse input. The game screen is an essential aspect of the Connect Four game because it is where the players generate their moves.

We can achieve maximum results with Pygames functions to set up the game screen. Heres an example of how to create a game window using Pygame.

import pygame


# Set width and height of screen (width, height)

screen = pygame.display.set_mode((700, 700))

# Set screen caption

pygame.display.set_caption(“Connect Four”)

# Color of the background

background_color = (232, 232, 232)

# Set timing parameters

clock = pygame.time.Clock()

while True:

# Loop for the game

for event in pygame.event.get():

if event.type == pygame.QUIT:



Using this code, we are initializing pygame by calling the pygame.init() function. Next, we create a game window by calling the pygame.display.set_mode() function and specify the width and height of the game screen.

We also set the caption for the game window using the pygame.display.set_caption() function. The background color for the game window is set using the RGB color scheme.

Lastly, we add a game loop to handle any events generated by mouse input.

4) Python sys Module

The sys module is a part of Python Runtime Environment. It provides basic functions, objects, and system-specific parameters to work with.

It allows us to perform operations that interact with the system, like getting information about the Python interpreter, working with the operating system shell, managing and controlling interpreter execution, and so on.

Importing sys module

To work with the sys module, we need to import it using the

import sys statement. We can use it to get the system configuration variables, like the filename, Python version installed on the system, information about the interpreter environment, and so on.

Getting the Python Version Using sys Module

One of the essential features of the sys module is that it provides information about the current version of Python installed on the system. We can obtain the version number of Python using the sys.version attribute.

Here is an example of how to implement this in our Connect Four game.

import sys

print(f”Python version: {sys.version}”)

This will print the following output:

Python version: 3.9.6 (default, Jun 29 2021, 10:55:57)

In this code, sys.version retrieves the version number of Python installed on the computer. It is a string, and we can see that it is version 3.9.6 in the output.


In this article, we have examined the Pygame and sys modules in-depth and discussed their roles in creating multimedia applications and working with system-specific parameters, respectively. Pygame is a powerful and feature-rich library that can help developers create custom video games, music software, and other multimedia applications.

The sys module, on the other hand, is essential in working with runtime system environment variables. By making use of these modules and implementing them in your code, you can create a high-quality Connect Four game with advanced features and functionality.

5) Python math Module

The Python math module provides a set of mathematical functions, constants, and tools that help in performing mathematical operations in Python. The math module contains functionality for trigonometric functions, logarithmic functions, angle conversion functions, and more.

The module is built into Python, so there is no need for additional installation.

Installing math module

The math module is already installed with the Python language. Therefore, it’s pre-built into the Python system and needs no additional installation.

We can

import math to use it in our program.

Using the math Module in Connect Four Game

The math module can be easily integrated into the Connect Four game to implement a range of mathematical operations. One possible usage is to employ it to calculate the angle of the pieces when they drop onto the game board.

Another potential use case is to calculate the probability of a winning move. Here is an example of implementing the math module in calculating the probability of a winning move in the Connect Four game:

import math

total_moves = 42

winning_moves = 4

probability = winning_moves/total_moves

print(f”The probability of winning is {math.ceil(probability*100)}%”)

In this code, we first declare the variables total_moves and winning_moves as 42 and 4, respectively. These values illustrate that there are 42 moves possible in a game of Connect Four and only four ways to win.

We then calculate the probability of winning using the (winning_moves/total_moves) formula. Lastly, we print the output using the Python math module’s ceil function to round up the probability to the nearest integer.

6) Implementing Connect Four Game in Python

To implement the Connect Four game in Python, we start by initializing the board and creating the main game loop. We can use the following code:

import numpy as np



def create_board():

board = np.zeros((ROW_COUNT, COLUMN_COUNT))

return board

game_over = False

board = create_board()

while not game_over:

# Prompt for player 1 input

if turn == 0:

column = int(input(“Player 1 make your selection (0-6): “))

# Prompt for player 2 input


column = int(input(“Player 2 make your selection (0-6): “))

turn += 1

turn = turn % 2

The code creates the board with six rows and seven columns using the NumPy module. It then sets the game_over boolean value and initializes the board.

The board is then displayed inside the while loop, and the game continuously prompts each player to make their move. The turn variable helps in alternating the turns of the two players by making sure each player takes a turn.

Alterations and Updates to the Code

We can make the Connect Four game more exciting by making modifications to the code. One of such modifications is updating the drop_piece function to handle a future indication where the column is already full.

It can be written as follows:

def is_valid_location(board, col):

return board[ROW_COUNT-1][col] == 0

def get_next_open_row(board, col):

for r in range(ROW_COUNT):

if board[r][col] == 0:

return r

def drop_piece(board, row, col, piece):

if is_valid_location(board, col):

row = get_next_open_row(board, col)

board[row][col] = piece

These updates to the drop_piece function add functionality to the Connect Four game. By checking whether a move is valid, we avoid errors that could lead to code crashes.

Creating GUI using Pygame

Pygame makes it easy to implement and customize the graphics user interface of the Connect Four game. Heres an example of the implementation of the GUI:

import pygame




size = (width, height)

# Initialize Pygame


# Create Screen

screen = pygame.display.set_mode(size)

# Set game caption

pygame.display.set_caption(“Connect Four”)

# Colors

BLACK = (0, 0, 0)

BLUE = (94, 129, 162)

RED = (237, 90, 90)

YELLOW = (249, 223, 76)

# Draw Circles

def draw_board(board):

for c in range(COLUMN_COUNT):

for r in range(ROW_COUNT):


for c in range(COLUMN_COUNT):

for r in range(ROW_COUNT):

if board[r][c] == 1:, RED, (int(c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), int(SQUARESIZE/2-5))

elif board[r][c] == 2:, YELLOW, (int(c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), int(SQUARESIZE/2-5))


In this code, we first initialize Pygame, create a screen to display the Connect Four game board, and set the game caption. We also define the color for different players’ pieces, including BLACK, BLUE, RED, and YELLOW.

Lastly, we define a function called draw_board to generate the game board and control the display of the game.


In this article, we dove into the different ways in which we can expand the Connect Four game’s functionality and made it more interesting using the math module and the Pygame module. The math module provides us with several mathematical operations and tools to help us calculate probabilities and angles relevant to the game.

Additionally, Pygame makes it easy to produce polished graphics and create a graphical user interface that the players can interact with. By