Programming a Connect-4 game on Python
--
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 | | | | | | | |
-----------------------------
b | | | | | | | |
-----------------------------
a | | | | | | | |
-----------------------------
1 2 3 4 5 6 7
That means you can stack up 6 pieces on each column before filling it up, and the 2 players take turn placing pieces. The winner is whoever has a continuous stack of 4 pieces of their own denomination (I will use X’s and O’s in my program) in either a horizontal, vertical or diagonal fashion (e.g. next to each other in one of those directions).
Making a function that prints the board with pieces
First, we want to make a function that prints out a board like I did above, including the column numbers and row letters just for increased visibility. For this, let’s create the function as follows:
# print board
def printBoard(board):
rows =…