Programming a Connect-4 game on Python

Oscar Nieves
12 min readAug 10, 2021

Done from scratch using less than 200 lines of code.

The other day I was working with some Python and functions, and it occurred to me that it would be a fun task to program a Connect-4 game from scratch using a few functions and a data structure known as a stack. Programming board games is a fun activity for two reasons: (1) it teaches you how to think out of the box when it comes to coding and algorithms, and (2) it is an interactive process in which the end result is quite satisfactory.

In this tutorial, I will teach you how to do this step by step, and perhaps that way you can get some inspiration for programming other board games yourself. If you would like to access the original code I made, I recommend visiting my GitHub repository: https://github.com/oscarnieves100/Python-Programs/blob/main/Connect_Four.py. Other than that, let’s get started.

The rules of the game

First let’s discuss the main rules of the game. The board of Connect-4 consists of 7 columns (or stacks) and 6 rows for each as shown below:

  -----------------------------
f | | | | | | | |
-----------------------------
e | | | | | | | |
-----------------------------
d | | | | | | | |
-----------------------------
c | | | | | | |…

--

--

Oscar Nieves

I write stories about applied math, physics and engineering.