Four in a Row is a Connect Four-style game: drop counters into a 7-column, 6-row grid and try to line up four. It is the best project for learning 2D lists (a list of rows), because you need to drop counters to the lowest free row and look for lines in four directions.
You are X. The computer (O) wins when it can, blocks you when it must, and otherwise prefers the middle columns.
Play Four in a Row
Press โถ Play to start the game. When it asks you something, type your answer and press Enter.
View and edit the code (70 lines)
How to play
- Type a column number from 1 to 7 to drop your counter.
- Counters fall to the lowest empty space in that column.
- Four in a row across, down or diagonally wins.
The complete Four in a Row code
Here is the whole program (70 lines). It only uses Python's standard library, so it runs anywhere Python 3 is installed.
import random
ROWS, COLS = 6, 7
grid = [["." for _ in range(COLS)] for _ in range(ROWS)] # row 0 is the top
def show():
print()
for row in grid:
print(" " + " ".join(row))
print(" " + " ".join(str(c + 1) for c in range(COLS)))
def drop(col, mark):
for r in range(ROWS - 1, -1, -1): # start at the bottom row
if grid[r][col] == ".":
grid[r][col] = mark
return r
return None # the column is full
def wins(mark):
for r in range(ROWS):
for c in range(COLS):
for dr, dc in [(0, 1), (1, 0), (1, 1), (1, -1)]:
cells = [(r + dr * i, c + dc * i) for i in range(4)]
if all(0 <= y < ROWS and 0 <= x < COLS and grid[y][x] == mark for y, x in cells):
return True
return False
def open_cols():
return [c for c in range(COLS) if grid[0][c] == "."]
def computer():
for mark in ["O", "X"]: # win, else block
for c in open_cols():
r = drop(c, mark)
found = wins(mark)
grid[r][c] = "."
if found:
return c
middle = [c for c in [3, 2, 4, 1, 5, 0, 6] if c in open_cols()]
return random.choice(middle[:3])
print("FOUR IN A ROW - you are X")
show()
while True:
text = input("Your column (1-7): ").strip()
if not text.isdigit() or not 1 <= int(text) <= COLS or int(text) - 1 not in open_cols():
print("Pick an open column from 1 to 7.")
continue
drop(int(text) - 1, "X")
if wins("X"):
show()
print("Four in a row! You win!")
break
if not open_cols():
show()
print("The grid is full. It's a draw.")
break
col = computer()
drop(col, "O")
print(f"The computer drops into column {col + 1}.")
show()
if wins("O"):
print("The computer got four in a row.")
breakHow the Four in a Row game works, step by step
01Make a grid with a list of lists
A list comprehension builds 6 rows of 7 dots. grid[r][c] is row r, column c. Building each row separately matters: [["."] * 7] * 6 would make six copies of the same row.
grid = [["." for _ in range(COLS)] for _ in range(ROWS)]02Drop with gravity
Counters fall, so we scan the column from the bottom row upwards and fill the first empty space. range(ROWS - 1, -1, -1) counts 5, 4, 3, 2, 1, 0.
for r in range(ROWS - 1, -1, -1):
if grid[r][col] == ".":
grid[r][col] = mark
return r03Look for four in any direction
From every cell, step 4 times in each of four directions: right (0, 1), down (1, 0) and the two diagonals. If all four cells are on the grid and hold the same mark, that's a win.
for dr, dc in [(0, 1), (1, 0), (1, 1), (1, -1)]:
cells = [(r + dr * i, c + dc * i) for i in range(4)]04Try moves, then undo them
The computer drops a counter, checks for a win, then puts the dot back. Testing moves this way is how most game AIs think, just with deeper searches.
r = drop(c, mark)
found = wins(mark)
grid[r][c] = "."What you'll learn
- 2D lists and
grid[row][col] - Counting backwards with
range() - Direction vectors to scan lines
all()with a generator- Try-and-undo AI moves
Python concepts in this game:
Four in a Row coding challenges
Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).
Drop a counter
Write drop(grid, col, mark): put mark in the lowest "." of column col and return that row number, or return None if the column is full. Row 0 is the top.
Hint
Loop for r in range(len(grid) - 1, -1, -1): and stop at the first ".".
Show a solution
def drop(grid, col, mark):
for r in range(len(grid) - 1, -1, -1):
if grid[r][col] == ".":
grid[r][col] = mark
return r
return None
g = [[".", "."], [".", "."], ["X", "."]]
print(drop(g, 0, "O"), g)Four across
Write four_across(row, mark): row is a list of strings. Return True if it contains four marks next to each other.
Hint
Check every slice of four: row[c:c + 4] == [mark] * 4 for c in range(len(row) - 3).
Show a solution
def four_across(row, mark):
for c in range(len(row) - 3):
if row[c:c + 4] == [mark] * 4:
return True
return False
print(four_across(list(".XXXX.."), "X"))Which columns are open?
Write open_cols(grid) that returns the column indexes whose top cell (row 0) is ".".
Hint
Only the top row matters: if grid[0][c] is a dot, column c has space.
Show a solution
def open_cols(grid):
return [c for c in range(len(grid[0])) if grid[0][c] == "."]
print(open_cols([["X", ".", "O"], ["X", "O", "O"]]))Make it your own
Once your challenges pass, try one of these upgrades:
- Let two players share the keyboard.
- Make the computer look two moves ahead.
- Colour the counters with ANSI escape codes in a terminal.
- Draw the grid with turtle or pygame.
Frequently asked questions
How do you make Connect Four in Python?
Use a 6x7 list of lists, drop each counter into the lowest free row of the chosen column, and after every move check all four directions for four matching counters.
How do you check diagonals in a grid?
Use direction steps: (1, 1) moves down-right and (1, -1) moves down-left. From each cell, collect four cells along the direction and test if they all match.
Why does my grid change in every row at once?
Writing [['.'] * 7] * 6 makes six references to one list. Build each row separately with a list comprehension instead.