Python for Beginners: Building a Connect 4 Game
Building a Connect 4 game is an excellent starting point for beginners who want to learn the basics of a programming language. So today, we’ll build one in Python.
I will walk you through the process of building this game, with code and explanations!
Connect 4 Rules
Before coding, it’s essential to understand the Connect 4 game’s rules and mechanics.
Connect 4 is a two-player strategy game played on a vertical board with 7 columns and 6 rows. The objective of the game is to connect four of your colored discs in a row, column, or diagonal before your opponent does the same. Each player takes turns dropping one of their colored discs into one of the columns, and the disc falls to the lowest unoccupied row of that column. The game ends when either a player connects four discs or the board is filled, resulting in a tie.
Getting Started
I won’t explain how to set up a Python environment, or how to set up dependencies. You’re supposed to already know it.
Before diving into the code,e I advise you to try to code this game yourself. The best way to learn a programming language is to practice.
The Game Board
The first step in building the Connect 4 game is to create the game board. We can represent the game board as a 2D list or array, where each element in the list represents a cell on the board. We can use the value “0” to represent an empty cell, “1” to represent a red disc, and “2” to represent a yellow disc. It’s not the perfect way to do this, it would have been better to use an Enum, but for now, don’t bother with enumerations.
# Create the game board
board = [[0 for j in range(7)] for i in range(6)]In this code snippet, we use a nested loop to create a 2D list with 6 rows and 7 columns, initialized with zeros. We use the “range” function to generate the indices for the rows and columns.
Now that we have created the game board, we can create a function to print it to the console.
def print_board(board):
for row in board:
print("|", end="")
for cell in row:
if cell == 0:
print(" ", end="|")
elif cell == 1:
print(" O ", end="|")
elif cell == 2:
print(" X ", end="|")
print("")
print("-----------------------------")In this code snippet, we define a function called “print_board” that takes the game board as an argument. We use two nested loops to iterate over the rows and columns of the game board. For each cell on the board, we print a vertical bar symbol (“|”) followed by a space and a disc representation (either “O” for red or “X” for yellow), depending on the value of the cell. We use the “end” parameter of the “print” function to avoid printing a new line character after each cell, which would result in a misaligned board. After each row, we print a horizontal line of dashes to separate the rows.
With the game board and print function in place, we can now test our code by calling the “print_board” function with the game board as an argument. This will display an empty Connect 4 board on the console.
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
-----------------------------Getting User Input
Now that we have created the game board and a function to print it, we can start implementing the game logic. The first step in the game logic is to get input from the players to place their discs on the board.
To get user input, we will use the built-in “input” function in Python, which reads a line of text from the console and returns it as a string. We will prompt the player to enter the column number where they want to drop their disc.
def get_player_input(player):
column = int(input("Player " + str(player) + ", enter a column number (1-7): "))
return columnWe define a function called “get_player_input” that takes the player number as an argument. We prompt the player to enter a column number by concatenating the player number with a string and using the “input” function. We convert the user input to an integer using the “int” function and return the column number.
It’s important to validate the user input to ensure that it is within the valid range of column numbers (1–7) and that the selected column is not already full. We can add some validation logic to the “get_player_input” function to handle these cases.
def get_player_input(player, board):
while True:
try:
column = int(input("Player " + str(player) + ", enter a column number (1-7): "))
if column < 1 or column > 7:
print("Invalid column number. Please enter a number between 1 and 7.")
continue
if board[0][column - 1] != 0:
print("Column is full. Please choose another column.")
continue
break
except ValueError:
print("Invalid input. Please enter a number between 1 and 7.")
return columnWe use a while loop to keep prompting the player until they enter a valid column number. We use the “try-except” block to catch any non-integer input from the player and handle it gracefully. We check if the column number is within the valid range of 1–7 and if the selected column is not already full. If either of these conditions is not met, we print an error message and continue the loop. If the input is valid, we break out of the loop and return the column number.
Updating the Board
After getting the user input, we need to update the game board with the player’s disc in the selected column. To do this, we will create a function called “update_board” that takes the column number, player number, and game board as arguments.
def update_board(column, player, board):
row = 5
while row >= 0:
if board[row][column - 1] == 0:
board[row][column - 1] = player
break
row -= 1We start by setting the initial row to the bottom of the selected column (row 5). We then use a while loop to iterate through the rows from bottom to top until we find an empty slot to place the player’s disc. If the slot is empty, we update the game board with the player’s disc and break out of the loop.
With the “update_board” function in place, we can now update the game board with the player’s disc by calling this function after getting the player’s input.
# Main game loop
player = 1
while True:
print_board(board)
column = get_player_input(player, board)
update_board(column, player, board)
player = 3 - player # Switch playerChecking for a Win
In Connect 4, a player wins the game if they have 4 of their discs in a row, either horizontally, vertically, or diagonally.
def check_win(player, board):
# Check horizontal
for row in range(6):
for col in range(4):
if board[row][col] == player and board[row][col+1] == player and board[row][col+2] == player and board[row][col+3] == player:
return True
# Check vertical
for row in range(3):
for col in range(7):
if board[row][col] == player and board[row+1][col] == player and board[row+2][col] == player and board[row+3][col] == player:
return True
# Check diagonal (down-right)
for row in range(3):
for col in range(4):
if board[row][col] == player and board[row+1][col+1] == player and board[row+2][col+2] == player and board[row+3][col+3] == player:
return True
# Check diagonal (down-left)
for row in range(3):
for col in range(3, 7):
if board[row][col] == player and board[row+1][col-1] == player and board[row+2][col-2] == player and board[row+3][col-3] == player:
return True
# No win found
return FalseWe use nested for loops to iterate through each row and column in the board and check for 4 consecutive discs belonging to the same player in all possible directions. If we find 4 consecutive discs belonging to the player in any direction, we return True, indicating that the player has won the game. If we have checked all possible directions and have not found a win, we return False.
We can now add logic to the main game loop to check for a win after each player’s turn.
# Main game loop
player = 1
while True:
print_board(board)
column = get_player_input(player, board)
update_board(column, player, board)
if check_win(player, board):
print("Player " + str(player) + " wins!")
break
player = 3 - player # Switch playerNow you can try to play, it should work!
Final Note
Here is the whole code:
# Create the game board
board = [[0 for j in range(7)] for i in range(6)]
def print_board(board):
for row in board:
print("|", end="")
for cell in row:
if cell == 0:
print(" ", end="|")
elif cell == 1:
print(" O ", end="|")
elif cell == 2:
print(" X ", end="|")
print("")
print("-----------------------------")
def get_player_input(player, board):
while True:
try:
column = int(input("Player " + str(player) + ", enter a column number (1-7): "))
if column < 1 or column > 7:
print("Invalid column number. Please enter a number between 1 and 7.")
continue
if board[0][column - 1] != 0:
print("Column is full. Please choose another column.")
continue
break
except ValueError:
print("Invalid input. Please enter a number between 1 and 7.")
return column
def update_board(column, player, board):
row = 5
while row >= 0:
if board[row][column - 1] == 0:
board[row][column - 1] = player
break
row -= 1
def check_win(player, board):
# Check horizontal
for row in range(6):
for col in range(4):
if board[row][col] == player and board[row][col+1] == player and board[row][col+2] == player and board[row][col+3] == player:
return True
# Check vertical
for row in range(3):
for col in range(7):
if board[row][col] == player and board[row+1][col] == player and board[row+2][col] == player and board[row+3][col] == player:
return True
# Check diagonal (down-right)
for row in range(3):
for col in range(4):
if board[row][col] == player and board[row+1][col+1] == player and board[row+2][col+2] == player and board[row+3][col+3] == player:
return True
# Check diagonal (down-left)
for row in range(3):
for col in range(3, 7):
if board[row][col] == player and board[row+1][col-1] == player and board[row+2][col-2] == player and board[row+3][col-3] == player:
return True
# No win found
return False
if __name__ == '__main__':
# Main game loop
player = 1
while True:
print_board(board)
column = get_player_input(player, board)
update_board(column, player, board)
if check_win(player, board):
print("Player " + str(player) + " wins!")
break
player = 3 - player # Switch playerAs you can see, in a few lines of code we can build a fun game, it’s the advantage of Python. It allows us to quickly develop things.
Now, I advise you to modify the code to implement new features of your choice. What about an AI, for example?
To explore more of my Python stories, click here!
If you liked the story, don’t forget to clap and maybe follow me if you want to explore more of my content :)
You can also subscribe to me via email to be notified every time I publish a new story, just click here!
If you’re not subscribed to medium yet and wish to support me or get access to all my stories, you can use my link:





