Python Gomoku (Five‑in‑a‑Row) Game Using Pygame – Full Source Code and Walkthrough
This article presents a complete Python implementation of the classic Gomoku board game with Pygame, explaining the rules, showing a dynamic demo, providing the full source code for the checkerboard logic, AI opponent, rendering, and instructions for running the game on your own machine.
The article introduces a Python project that implements the traditional five‑in‑a‑row (Gomoku) game using the Pygame library. It starts with a brief preface and outlines the basic rules: black (p1) moves first, white (p2) follows, and the first player to connect five stones wins.
A dynamic GIF demonstrates the gameplay, followed by a detailed source‑code section. The code defines named tuples for chess pieces and points, sets up the board, and implements core methods such as can_drop , drop , _win , and _get_count_on_direction to manage moves and detect victories.
<code>from collections import namedtuple
Chessman = namedtuple('Chessman', 'Name Value Color')
Point = namedtuple('Point', 'X Y')
BLACK_CHESSMAN = Chessman('黑子', 1, (45, 45, 45))
WHITE_CHESSMAN = Chessman('白子', 2, (219, 219, 219))
offset = [(1, 0), (0, 1), (1, 1), (1, -1)]
class Checkerboard:
def __init__(self, line_points):
self._line_points = line_points
self._checkerboard = [[0] * line_points for _ in range(line_points)]
def _get_checkerboard(self):
return self._checkerboard
checkerboard = property(_get_checkerboard)
def can_drop(self, point):
return self._checkerboard[point.Y][point.X] == 0
def drop(self, chessman, point):
"""落子
:param chessman:
:param point:落子位置
:return:若该子落下之后即可获胜,则返回获胜方,否则返回 None"""
print(f'{chessman.Name} ({point.X}, {point.Y})')
self._checkerboard[point.Y][point.X] = chessman.Value
if self._win(point):
print(f'{chessman.Name}获胜')
return chessman
def _win(self, point):
cur_value = self._checkerboard[point.Y][point.X]
for os in offset:
if self._get_count_on_direction(point, cur_value, os[0], os[1]):
return True
def _get_count_on_direction(self, point, value, x_offset, y_offset):
count = 1
for step in range(1, 5):
x = point.X + step * x_offset
y = point.Y + step * y_offset
if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:
count += 1
else:
break
for step in range(1, 5):
x = point.X - step * x_offset
y = point.Y - step * y_offset
if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:
count += 1
else:
break
return count >= 5
</code>The script also includes the main game loop, handling user input, drawing the board and pieces, and integrating an AI opponent (referenced as AI ). Configuration constants define board dimensions, colors, stone radii, and screen size. Helper functions such as _draw_checkerboard , _draw_chessman , and _get_clickpoint manage rendering and click‑position translation.
Running the program is straightforward: after installing required modules (e.g., pip install pygame -i https://pypi.douban.com/simple ), execute the script; the if __name__ == '__main__': block calls main() . The article also provides a separate human‑vs‑human mode and a human‑vs‑AI mode, each with its own dynamic demonstration GIF.
Finally, the page includes a disclaimer about copyright and links to related Python tutorials, emphasizing that the content is curated from the web and belongs to the original authors.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.