Implementing a Simple AI for a Tetris Game Using Python
This article explains how to build a Tetris game with a basic AI using Python 3.6.4 and PyQt5, covering environment setup, the underlying algorithm that evaluates future board states, and the complete source code for the AI decision‑making and scoring functions.
The tutorial demonstrates how to create a Tetris game that incorporates a simple artificial‑intelligence algorithm using Python 3.6.4 and the PyQt5 library.
Development tools : Python 3.6.4, PyQt5, and standard Python modules.
Environment setup : Install Python, add it to the system PATH, and install the required modules via pip install pyqt5 .
Algorithm overview : The AI enumerates all possible placements for the current and next tetromino, simulates each resulting board, and selects the placement with the highest score based on several heuristics such as cleared lines, hole count, block count, column heights, height variance, and height differences.
AI source code :
# Simple AI algorithm
for d_now in current_direction_range:
x_now_min, x_now_max, y_now_min, y_now_max = self.inner_board.current_tetris.getRelativeBoundary(d_now)
for x_now in range(-x_now_min, self.inner_board.width - x_now_max):
board = self.getFinalBoardData(d_now, x_now)
for d_next in next_direction_range:
x_next_min, x_next_max, y_next_min, y_next_max = self.inner_board.next_tetris.getRelativeBoundary(d_next)
distances = self.getDropDistances(board, d_next, range(-x_next_min, self.inner_board.width - x_next_max))
for x_next in range(-x_next_min, self.inner_board.width - x_next_max):
score = self.calcScore(copy.deepcopy(board), d_next, x_next, distances)
if not action or action[2] < score:
action = [d_now, x_now, score]
return actionThe scoring function evaluates each simulated board using the following factors:
Number of lines that can be cleared
Number of holes (empty cells beneath blocks)
Number of individual blocks
Maximum column height
Standard deviation of column heights
First‑order forward difference of column heights and its standard deviation
Difference between the highest and lowest column
Hole statistics and scoring code :
# Hole statistics
hole_statistic_0 = [0] * width
hole_statistic_1 = [0] * width
# Block and hole counters
num_blocks = 0
num_holes = 0
# Highest point per column
roof_y = [0] * width
for y in range(height-1, -1, -1):
has_hole = False
has_block = False
for x in range(width):
if board[x + y * width] == tetrisShape().shape_empty:
has_hole = True
hole_statistic_0[x] += 1
else:
has_block = True
roof_y[x] = height - y
if hole_statistic_0[x] > 0:
hole_statistic_1[x] += hole_statistic_0[x]
hole_statistic_0[x] = 0
if hole_statistic_1[x] > 0:
num_blocks += 1
if not has_block:
break
if not has_hole and has_block:
removed_lines += 1
# Compute weighted hole count
num_holes = sum([i ** .7 for i in hole_statistic_1])
# Highest point after line removal
max_height = max(roof_y) - removed_lines
# Height differences
roof_dy = [roof_y[i] - roof_y[i+1] for i in range(len(roof_y)-1)]
# Standard deviations
if len(roof_y) <= 0:
roof_y_std = 0
else:
roof_y_std = math.sqrt(sum([y**2 for y in roof_y]) / len(roof_y) - (sum(roof_y) / len(roof_y)) ** 2)
if len(roof_dy) <= 0:
roof_dy_std = 0
else:
roof_dy_std = math.sqrt(sum([dy**2 for dy in roof_dy]) / len(roof_dy) - (sum(roof_dy) / len(roof_dy)) ** 2)
# Absolute sum of height differences
abs_dy = sum([abs(dy) for dy in roof_dy])
# Height range
max_dy = max(roof_y) - min(roof_y)
# Final score calculation
score = (removed_lines * 1.8 - num_holes * 1.0 - num_blocks * 0.5 - max_height ** 1.5 * 0.02 -
roof_y_std * 1e-5 - roof_dy_std * 0.01 - abs_dy * 0.2 - max_dy * 0.3)
return scoreThe article concludes with a visual demonstration of the AI‑controlled Tetris gameplay and a disclaimer about copyright.
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.