Welcome, aspiring game developers and Python enthusiasts! Have you ever played Connect Four? It’s that classic two-player game where you drop colored discs into a grid, trying to get four of your discs in a row – horizontally, vertically, or diagonally – before your opponent does. It’s simple, fun, and a fantastic project for beginners to dive into game development using Python!
In this blog post, we’ll walk through creating a basic Connect Four game using Python. We’ll cover everything from setting up the game board to checking for wins. Don’t worry if you’re new to programming; we’ll explain every step and common technical terms along the way.
Why Build Connect Four with Python?
Python is an excellent language for beginners because its syntax (the way you write code) is very readable, almost like plain English. Building a game like Connect Four helps you learn fundamental programming concepts such as:
- Data Structures: How to store information, like our game board.
- Functions: How to organize your code into reusable blocks.
- Loops: How to repeat actions, like taking turns or checking for wins.
- Conditional Statements: How to make decisions in your code, like checking if a move is valid.
It’s a practical and fun way to see your code come to life!
Understanding Connect Four Basics
Before we start coding, let’s quickly review the game rules and typical setup:
- The Board: Usually a 6×7 grid (6 rows, 7 columns).
- Players: Two players, each with their own color (e.g., ‘X’ and ‘O’ or 1 and 2 in our code).
- Turns: Players take turns dropping one disc into a chosen column.
- Gravity: Discs fall to the lowest available space in that column.
- Winning: The first player to get four of their discs in a straight line (horizontal, vertical, or diagonal) wins!
- Draw: If the board fills up and no one has won, it’s a draw.
Now, let’s get our hands dirty with some Python code!
Setting Up Our Python Environment
You don’t need any special tools or libraries for this project, just a standard Python installation (version 3.x is recommended). You can write your code in any text editor and run it from your terminal or command prompt.
To run a Python script, save your code in a file named connect4.py (or any other name ending with .py), then open your terminal, navigate to the folder where you saved the file, and type:
python connect4.py
Step-by-Step Implementation
Representing the Game Board
How do we represent a 6×7 grid in Python? A good way is to use a 2D list.
- 2D List (Two-Dimensional List): Imagine a list where each item in that list is another list. This creates rows and columns, just like our game board!
- Rows and Columns: We’ll define
ROW_COUNTas 6 andCOLUMN_COUNTas 7.
Let’s create an empty board filled with zeros (representing empty slots).
import numpy as np # We'll use numpy later for easy board manipulation
ROW_COUNT = 6
COLUMN_COUNT = 7
def create_board():
# np.zeros creates an array (similar to a list) filled with zeros
# (ROW_COUNT, COLUMN_COUNT) specifies the size
board = np.zeros((ROW_COUNT, COLUMN_COUNT))
return board
board = create_board()
You might see np.zeros and numpy.
* NumPy: It’s a powerful Python library commonly used for working with arrays and mathematical operations. It makes creating and manipulating grids much easier than using Python’s built-in lists for this kind of task.
* import numpy as np: This line imports the NumPy library and gives it a shorter name, np, so we don’t have to type numpy. every time.
Displaying the Board
A raw 2D list isn’t very user-friendly to look at. Let’s create a function to print the board in a nice, visual way. We’ll flip it vertically because in Connect Four, pieces are dropped from the top and stack up from the bottom. When we create our numpy board, row 0 is the first row, but we want it to appear as the bottom row when printed.
def print_board(board):
# np.flipud flips the board "up-down"
# This makes row 0 appear at the bottom, which is more intuitive for Connect Four
print(np.flipud(board))
Dropping a Piece
This is where players interact with the game. They choose a column, and their piece needs to fall to the lowest available spot.
We’ll need a few helper functions:
is_valid_location(board, col): Checks if a chosen column is not full.get_next_open_row(board, col): Finds the first empty row in a given column.drop_piece(board, row, col, piece): Places the player’s piece on the board.
def is_valid_location(board, col):
# The top row (ROW_COUNT - 1) in that column must be empty (0)
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: # If the spot is empty (0)
return r # Return the row number
def drop_piece(board, row, col, piece):
board[row][col] = piece # Assign the player's piece number to that spot
Checking for a Win
This is often the trickiest part of game development! We need to check for four in a row in all possible directions: horizontal, vertical, and both types of diagonals.
- Loop: A programming construct that repeats a block of code multiple times. We’ll use
forloops to iterate through rows and columns. piece: This will be either player 1’s number or player 2’s number.
def winning_move(board, piece):
# 1. Check horizontal locations for win
# We iterate through each row
for c in range(COLUMN_COUNT - 3): # -3 because we need 4 spots, so we stop 3 spots from the end
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
# 2. Check vertical locations for win
# We iterate through each column
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT - 3): # -3 because we need 4 spots, so we stop 3 spots from the end
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
# 3. Check positively sloped diagonals (\)
# Start from bottom-left
for c in range(COLUMN_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
# 4. Check negatively sloped diagonals (/)
# Start from top-left, moving down and right
for c in range(COLUMN_COUNT - 3):
for r in range(3, ROW_COUNT): # Start checking from row 3 (index 3) up to the top
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
return False # If no winning pattern is found, return False
Putting It All Together: The Game Loop
Now, let’s combine all these pieces into our main game! We’ll need:
- A
game_overflag (a variable that isTrueorFalse) to control when the game ends. - A
turnvariable to keep track of whose turn it is. - A loop that continues as long as
game_overisFalse. - Input from players to choose a column.
- Calling our functions to drop pieces and check for wins.
game_over = False
turn = 0 # Player 0 (or 1 in game, but usually 0 and 1 in code) starts first
print_board(board)
while not game_over:
# Player 1 turn
if turn == 0:
try:
# Get column input from Player 1
# input() function gets text input from the user
# int() converts that text into a whole number
col = int(input("Player 1 Make your Selection (0-6):"))
except ValueError: # Handle cases where user doesn't enter a number
print("Invalid input. Please enter a number between 0 and 6.")
continue # Skip to the next iteration of the loop
# Check if the chosen column is valid
if 0 <= col <= COLUMN_COUNT - 1 and is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, 1) # Player 1 uses piece '1'
if winning_move(board, 1):
print("PLAYER 1 WINS!!! Congratulations!")
game_over = True
else:
print("Column is full or out of bounds. Try again!")
continue # Skip player turn, allow them to re-enter input
# Player 2 turn
else: # turn == 1
try:
col = int(input("Player 2 Make your Selection (0-6):"))
except ValueError:
print("Invalid input. Please enter a number between 0 and 6.")
continue
if 0 <= col <= COLUMN_COUNT - 1 and is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, 2) # Player 2 uses piece '2'
if winning_move(board, 2):
print("PLAYER 2 WINS!!! Congratulations!")
game_over = True
else:
print("Column is full or out of bounds. Try again!")
continue # Skip player turn, allow them to re-enter input
print_board(board) # Print the board after each move
# Check for a draw (board is full)
# np.all(board[ROW_COUNT-1] != 0) checks if all spots in the top row are taken
if not game_over and np.all(board[ROW_COUNT-1] != 0):
print("It's a DRAW! The board is full.")
game_over = True
turn += 1 # Increment turn
turn = turn % 2 # This makes turn alternate between 0 and 1 (0 -> 1 -> 0 -> 1...)
What’s Next? (Ideas for Improvement)
Congratulations! You’ve just built a fully playable Connect Four game in Python. This is a great foundation, and there are many ways you can expand and improve it:
- Graphical User Interface (GUI): Instead of text-based input and output, you could use libraries like
PygameorTkinterto create a visual board with clickable columns. - Artificial Intelligence (AI): Can you create a computer player that makes smart moves? This involves concepts like minimax algorithms.
- Better Input Validation: Make the game more robust against unexpected user inputs.
- Player Names: Allow players to enter their names instead of just “Player 1” and “Player 2.”
- More Colors/Symbols: Use different characters or even emoji to represent the pieces.
Keep experimenting, keep coding, and most importantly, have fun!
Leave a Reply
You must be logged in to post a comment.