One effective approach is to have each allied king work toward a common “meeting point,” which can be calculated as the center of mass (centroid) of all allied king positions. Then, on each turn, each king would try to move (safely) in the direction that reduces its distance to that centroid.
Below are the steps and some example code ideas to achieve that:
1. Calculate the Allied Kings’ Centroid
Assume you have a list of positions for all allied kings (each is a coordinate tuple, for example, (x, y)). You can compute the centroid as follows:
def calculate_centroid(king_positions):
total_x = sum(pos[0] for pos in king_positions)
total_y = sum(pos[1] for pos in king_positions)
count = len(king_positions)
return (total_x / count, total_y / count)
This centroid is the average of the x-coordinates and the y-coordinates. It serves as the “meeting point” for all allied kings.
2. Determine the Direction of Movement
For each king, you need to pick a move that brings it closer to the centroid. For a king on a 64x64 board, you can generate the available immediate moves (adjacent squares) and then select the one that minimizes the distance to the centroid. You also want to ensure that the move is safe (does not put the king in check).
import math
def distance(pos1, pos2):
return math.hypot(pos1[0] - pos2[0], pos1[1] - pos2[1])
def best_move_towards(king_pos, centroid, board, is_move_safe_func):
"""
king_pos: current position of the king (x,y)
centroid: target coordinate (x,y)
board: current board representation
is_move_safe_func: function to check if a given move is safe
"""
# All possible moves for a king (including diagonals)
possible_moves = []
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if dx == 0 and dy == 0:
continue # no move
new_x = king_pos[0] + dx
new_y = king_pos[1] + dy
# Check within board boundaries (0 to 63 on a 64x64 board)
if 0 <= new_x < 64 and 0 <= new_y < 64:
new_pos = (new_x, new_y)
if is_move_safe_func(king_pos, new_pos, board):
possible_moves.append(new_pos)
# If no safe move exists, the king stays in place
if not possible_moves:
return king_pos
# Choose the move that minimizes the distance to the centroid
best_move = min(possible_moves, key=lambda pos: distance(pos, centroid))
return best_move
Here, is_move_safe_func should be a function you define that verifies if a king can move from its current position to the proposed new position without exposing itself (or causing an illegal move, such as moving into check).