Python Project - Four Connecting Game

Himani Bansal
Data Science Flood
Published in
6 min readNov 8, 2023

--

About Python Four Connecting Game Project:

In this Python project, we will build the Four Connect Game in Python. We will use numpy and pygame library to run the game smoothly. Connect Four is a two-player board game known for its simple rules and engaging gameplay. The objective is for players to strategically drop their coloured discs into a vertical grid, aiming to connect four of their own pieces in a row, either horizontally, vertically, or diagonally, before their opponent can do the same.

Rules for playing the Four Connecting game:

Connect Four is a classic two-player connection game in which the players take turns dropping coloured balls (usually red and yellow) from the top into a vertically suspended grid. The objective of the game is to be the first to form a horizontal, vertical, or diagonal line of four of one’s own discs.

Python Four Connecting Game Project
  • The game is typically played on a 6x7 grid, but variations can have different dimensions.
  • Two players take turns playing, with one using red discs and the other using yellow discs.
  • Players place one of their coloured discs into any of the seven columns.
  • The disc is dropped from the top of the selected column and occupies the lowest available slot.
  • Players cannot choose a column that is already full.
  • The goal is to be the first player to connect four of their own discs horizontally, vertically, or diagonally.
  • The four connected discs must be consecutive and aligned in any of these directions.
  • If a player successfully connects four discs in a row, they win the game.
  • The game ends immediately when a player achieves this, even if there are more possible moves.
  • If all slots on the board are filled, and no player has four connected discs, the game is declared a draw.
  • Winning the game requires both offensive and defensive strategies.
  • Players must aim to connect four of their discs while simultaneously blocking their opponent’s potential winning moves.

Prerequisites For Python Four Connecting Game Project:

  • First, we will install the required libraries and modules in our system using the pip installer.
  • It would be best if you had a strong understanding of Python, along with the NumPy, Pygame, Sys, and Math libraries, to develop this project.

Importing the libraries and modules:

import numpy as np
import pygame
import sys
import math

numpy- It is imported for numerical operations.

pygame- It is imported for creating the game interface.

sys- It is imported for system related functions.

math- It is imported for mathematical operations.

Defining Variables-

Defining variables for colors and storing the number of rows and columns in variables.

BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)

row_count = 6
colm_count = 7

Here, we’ve defined color variables as ‘BLUE’, ‘BLACK’, ‘RED’, and ‘YELLOW’. We’ve also used ‘row_count’ and ‘colm_count’ to define the number of rows and columns.

Code for Game Logic Function-

We will define various functions here for different purposes.


def create_board():
board = np.zeros((row_count, colm_count))
return board

def drop_piece(board, row, col, piece):
board[row][col] = piece

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 print_board(board):
print(np.flip(board, 0))

def winning_move(board, piece):
# Check horizontal locations for win
for c in range(colm_count - 3):
for r in range(row_count):
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(colm_count):
for r in range(row_count - 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 positively sloped diaganols
for c in range(colm_count - 3):
for r in range(row_count - 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 negatively sloped diaganols
for c in range(colm_count - 3):
for r in range(3, row_count):
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

‘def create_board()’ function initialises the game board as a NumPy array filled with zeros.

‘def drop_piece’ function drops a game piece (1 or 2) into a specified column.

‘def is_valid_location’ function checks if a column is a valid choice for a move.

‘def get_next_open_row’ function is used to return the next available row in a column.

‘def print_board’ function is used to print the game board (inverted) to the console.

‘def winning_move’ function is used to check if a player has won the game with their current move.

Code for Drawing the Board for the Game-

We will draw the game board using the ‘def draw_board’ function.

def draw_board(board):
for c in range(colm_count):
for r in range(row_count):
pygame.draw.rect(screen, BLUE, (c * sqsize, r * sqsize + sqsize, sqsize, sqsize))
pygame.draw.circle(screen, BLACK, (
int(c * sqsize + sqsize / 2), int(r * sqsize + sqsize + sqsize / 2)), RADIUS)

for c in range(colm_count):
for r in range(row_count):
if board[r][c] == 1:
pygame.draw.circle(screen, RED, (
int(c * sqsize + sqsize / 2), height - int(r * sqsize + sqsize / 2)), RADIUS)
elif board[r][c] == 2:
pygame.draw.circle(screen, YELLOW, (
int(c * sqsize + sqsize / 2), height - int(r * sqsize + sqsize / 2)), RADIUS)
pygame.display.update()

board = create_board()
print_board(board)
game_over = False
turn = 0

‘def draw_board’ function draws the game board and pieces on the screen using Pygame. It’s called at various points to update the display.

Code for Game Interface-

We will initialize the pygame here.

pygame.init()

# define our screen size
sqsize = 100

# define width and height of board
width = colm_count * sqsize
height = (row_count + 1) * sqsize

size = (width, height)

RADIUS = int(sqsize / 2 - 5)

screen = pygame.display.set_mode(size)
# Calling function draw_board again
draw_board(board)
pygame.display.update()

myfont = pygame.font.SysFont("monospace", 75)

Here we have initialized the pygame window using the ‘pygame.init()’ method and set the width and height of the window.

Code for Main Game Loop-

Here is the main loop of the game.

while not game_over:

for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()

if event.type == pygame.MOUSEMOTION:
pygame.draw.rect(screen, BLACK, (0, 0, width, sqsize))
posx = event.pos[0]
if turn == 0:
pygame.draw.circle(screen, RED, (posx, int(sqsize / 2)), RADIUS)
else:
pygame.draw.circle(screen, YELLOW, (posx, int(sqsize / 2)), RADIUS)
pygame.display.update()

if event.type == pygame.MOUSEBUTTONDOWN:
pygame.draw.rect(screen, BLACK, (0, 0, width, sqsize))

# Ask for Player 1 Input
if turn == 0:
posx = event.pos[0]
col = int(math.floor(posx / sqsize))

if is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, 1)

if winning_move(board, 1):
label = myfont.render("Player 1 wins!!", 1, RED)
screen.blit(label, (40, 10))
game_over = True

# Ask for Player 2 Input
else:
posx = event.pos[0]
col = int(math.floor(posx / sqsize))

if is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, 2)

if winning_move(board, 2):
label = myfont.render("Player 2 wins!!", 1, YELLOW)
screen.blit(label, (40, 10))
game_over = True

print_board(board)
draw_board(board)

turn += 1
turn = turn % 2

if game_over:
pygame.time.wait(3000)

We have used a ‘while’ loop (while not game_over) that handles player input and game logic.

We have used ‘if/else’ statements for further game processing.

After that, events like quitting the game or mouse movement are processed. The current player’s piece is displayed as they move their mouse over the columns.

On a mouse click, the game checks if the move is valid, updates the board, and checks for a win.

The game alternates between Player 1 (red) and Player 2 (yellow).

When a player wins, a message is displayed, and the game waits for a few seconds before exiting.

Python Four Connecting Game Output:

Python Four Connecting Game Output

Conclusion:

We have successfully created the Four Connect Game in Python using the numpy and pygame libraries. You can customize and modify the game to meet your specific preferences and requirements, making it a fun and engaging project to work on. Enjoy playing and experimenting with it!

--

--

Doing my Best to Explain Data Science (Data Scientist, technology freak & Blogger)