To make the TETR.IO bot faster, we can target several areas of the code where optimization is possible. Here's a step-by-step breakdown with suggestions:
1. Optimize Screen Capturing
The screen capturing logic in refresh_screen_image() uses PIL.ImageGrab.grab, which can be slow for real-time applications.
Solution:
Replace ImageGrab.grab with a faster library like MSS, which is better suited for high-speed screen capture.
def get_next_pieces(self):
result = []
for x, y in self.next_piece_xy:
cropped = np.array(self.screen_image.crop((
x - self.pixel_area_half,
y - self.pixel_area_half,
x + self.pixel_area_half,
y + self.pixel_area_half
)))
# Reshape and vectorize color matching
reshaped = cropped.reshape(-1, cropped.shape[2])
diff = np.sum((reshaped[:, None] - colors) ** 2, axis=2)
closest_color_indices = np.argmin(diff, axis=1)
closest_color = colors[np.bincount(closest_color_indices).argmax()]
result.append(colors_name[colors.index(closest_color)])
return result
Why? This avoids the nested loops for pixel comparison and uses efficient NumPy operations, significantly speeding up processing.
3. Optimize Board Evaluation
The get_tetris_board method processes the entire Tetris board pixel-by-pixel to determine block states.
Solution:
Replace the pixel-by-pixel evaluation with block-based averaging. Instead of iterating through every pixel, calculate the average brightness of a block using NumPy slicing.
Optimized get_tetris_board:
python
def get_tetris_board(self):
board_image = np.array(self.screen_image.crop((
self.board_top_left[0],
self.board_top_left[1],
self.board_bottom_right[0],
self.board_bottom_right[1]
)).convert('L'))
block_width = board_image.shape[1] // NUM_COL
block_height = board_image.shape[0] // NUM_ROW
board = np.zeros((NUM_ROW, NUM_COL), dtype=np.int32)
for row in range(NUM_ROW):
for col in range(NUM_COL):
block = board_image[
row * block_height:(row + 1) * block_height,
col * block_width:(col + 1) * block_width
]
if np.mean(block) > 30: # Threshold for brightness
board[NUM_ROW - row - 1][col] = 1
return board
Why? This reduces the number of operations by processing entire blocks instead of individual pixels.
4. Improve Multiprocessing Efficiency
The bot already uses multiprocessing (mp_pool) for evaluating moves, but there are likely inefficiencies in how tasks are distributed.
Solution:
Use batch processing to minimize the overhead of task distribution.
Adjust the pruning_moves and pruning_breadth parameters based on your CPU core count to reduce excessive branching.
Optimized multiprocessing logic in find_best_move:
python
if mp_pool is not None:
batch_size = max(1, len(map_args) // (mp_pool._processes * 2))
batched_args = [map_args[i:i + batch_size] for i in range(0, len(map_args), batch_size)]
map_res = []
for batch in batched_args:
map_res.extend(mp_pool.map(_find_best_move, batch))
else:
map_res = map(_find_best_move, map_args)
Why? Batching reduces the overhead of task scheduling in multiprocessing.
5. Reduce Redundant Board Evaluations
The find_best_move function re-evaluates the board multiple times when exploring moves.
Solution:
Cache intermediate board states and their evaluations to avoid redundant computations.