AI Game Agent Training Program for Map Exploration and Item Collection
Creating an AI model to learn from player behavior and optimize gameplay for map exploration and item collection is a fascinating project. I'll outline a comprehensive approach to build this system, focusing on monitoring the mini-map, directing clicks, and handling item collection through computer vision and machine learning techniques.
System Architecture Overview
The training program will consist of several interconnected components:
- Screen Capture Module: Captures real-time game screen data, with special focus on the mini-map region
- State Representation: Processes raw screen data into meaningful state observations
- Action Generation: Converts AI decisions into in-game clicks with appropriate positioning
- Training Pipeline: Implements learning algorithms to improve performance
- Evaluation System: Measures agent performance across 3-minute loops
Screen Capture and Input Processing
Mini-map Analysis
The core of your system requires precise monitoring of the mini-map:
def capture_minimap(screen):
# Extract mini-map from top-right corner of screen
# Assuming fixed position - adjust coordinates as needed
minimap_region = screen[top:bottom, left:right]
return minimap_region
def detect_undiscovered_areas(minimap):
# Convert to HSV color space for better color detection
hsv = cv2.cvtColor(minimap, cv2.COLOR_BGR2HSV)
# Define color range for undiscovered areas
# These ranges will need calibration for your specific game
lower_bound = np.array([h_min, s_min, v_min])
upper_bound = np.array([h_max, s_max, v_max])
# Create mask for undiscovered areas
mask = cv2.inRange(hsv, lower_bound, upper_bound)
# Find contours of undiscovered regions
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Return centroids of contours
centers = []
for contour in contours:
M = cv2.moments(contour)
if M["m00"] != 0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
centers.append((cX, cY))
return centers
Item Detection
For identifying dropped items:
def detect_items(screen, color_ranges):
"""
Detect items based on provided color ranges
color_ranges: List of color range tuples (lower_bound, upper_bound)
"""
items = []
for lower_bound, upper_bound in color_ranges:
hsv = cv2.cvtColor(screen, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, lower_bound, upper_bound)
# Reduce noise
mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)
# Find contours
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Process each contour
for contour in contours:
if cv2.contourArea(contour) > MIN_ITEM_AREA: # Filter out noise
M = cv2.moments(contour)
if M["m00"] != 0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
items.append((cX, cY, "item"))
return items
State Representation
The state representation is crucial for effective learning. We'll need to create a state that encompasses:
def create_state_representation(minimap, player_position, undiscovered_areas, items):
"""
Create a suitable state representation for the learning algorithm
"""
# Calculate relative positions of undiscovered areas from player
undiscovered_vectors = []
minimap_center = (minimap.shape[1]//2, minimap.shape//2)
for area in undiscovered_areas:
# Vector from player to undiscovered area
dx = area - minimap_center
dy = area[1] - minimap_center[1]
# Convert to polar coordinates (distance, angle)
distance = np.sqrt(dx**2 + dy**2)
angle = np.arctan2(dy, dx)
undiscovered_vectors.append((distance, angle))
# Similarly process items
item_vectors = []
for item in items:
dx = item - player_position
dy = item[1] - player_position[1]
distance = np.sqrt(dx**2 + dy**2)
angle = np.arctan2(dy, dx)
item_vectors.append((distance, angle, item[2]))
# Create the state vector
# Sort by distance to prioritize closer targets
undiscovered_vectors.sort(key=lambda x: x)
item_vectors.sort(key=lambda x: x)
# Take N closest undiscovered areas and items
state = {
'undiscovered': undiscovered_vectors[:N_UNDISCOVERED],
'items': item_vectors[:N_ITEMS]
}
return state
Action Generation
For translating AI decisions into clicks:
def generate_click(direction_angle, distance_multiplier, player_position):
"""
Generate a click based on direction, angle and a distance multiplier
"""
# Convert from polar to cartesian coordinates
dx = math.cos(direction_angle) * distance_multiplier
dy = math.sin(direction_angle) * distance_multiplier
# Calculate click position relative to player
click_x = player_position + dx
click_y = player_position[1] + dy
return (int(click_x), int(click_y))
def execute_click(position):
"""
Execute a click at the specified position
"""
pyautogui.click(position, position[1])
Learning Approach
Given your requirements, I recommend a hybrid approach combining imitation learning (IL) and reinforcement learning (RL):
Imitation Learning Phase
First, learn from human demonstrations:
def collect_demonstration_data(num_episodes=10):
"""
Record human demonstrations for initial training
"""
demonstrations = []
for episode in range(num_episodes):
print(f"Starting demonstration episode {episode+1}/{num_episodes}")
states = []
actions = []
# Start game loop
game_start_time = time.time()
while time.time() - game_start_time < 180: # 3-minute loops
# Capture screen
screen = capture_screen()
minimap = capture_minimap(screen)
# Process state
undiscovered_areas = detect_undiscovered_areas(minimap)
items = detect_items(screen, COLOR_RANGES)
# Get player position
player_position = detect_player_position(screen)
# Create state representation
state = create_state_representation(minimap, player_position,
undiscovered_areas, items)
# Record mouse position and clicks (human action)
mouse_x, mouse_y = pyautogui.position()
if pyautogui.mouseDown():
action = (mouse_x, mouse_y, True) # Click
else:
action = (mouse_x, mouse_y, False) # Mouse movement
states.append(state)
actions.append(action)
time.sleep(0.1) # Adjust sampling rate as needed
demonstrations.append((states, actions))
return demonstrations
Reinforcement Learning Phase
Following imitation learning, implement RL to further improve performance:
def define_reward_function(previous_state, current_state, action):
"""
Calculate reward based on game progress
"""
reward = 0
# Reward for discovering new areas
previous_undiscovered = len(previous_state['undiscovered'])
current_undiscovered = len(current_state['undiscovered'])
if current_undiscovered < previous_undiscovered:
reward += DISCOVERY_REWARD * (previous_undiscovered - current_undiscovered)
# Reward for collecting items
previous_items = len(previous_state['items'])
current_items = len(current_state['items'])
if current_items < previous_items:
reward += ITEM_COLLECTION_REWARD * (previous_items - current_items)
# Penalty for time passing without progress
reward -= TIME_PENALTY
return reward
Policy Network Architecture
A deep neural network will map game states to actions:
def create_policy_network():
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(STATE_DIM,)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(ACTION_DIM) # Output: (angle, distance_multiplier)
])
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
loss='mse'
)
return model
Training Loop
The training process will alternate between collecting experiences and updating the policy:
def train_agent(initial_model, episodes=1000):
model = initial_model
for episode in range(episodes):
print(f"Starting episode {episode+1}/{episodes}")
# Reset game environment
reset_game()
states = []
actions = []
rewards = []
# Start game loop
game_start_time = time.time()
previous_state = None
while time.time() - game_start_time < 180: # 3-minute loops
# Capture and process screen
screen = capture_screen()
minimap = capture_minimap(screen)
undiscovered_areas = detect_undiscovered_areas(minimap)
items = detect_items(screen, COLOR_RANGES)
player_position = detect_player_position(screen)
# Create state representation
current_state = create_state_representation(minimap, player_position,
undiscovered_areas, items)
# Get action from policy
state_tensor = preprocess_state(current_state)
action_params = model.predict(state_tensor)
# Generate and execute click
angle = action_params
distance_multiplier = action_params[1]
click_position = generate_click(angle, distance_multiplier, player_position)
execute_click(click_position)
# Calculate reward (if not first step)
if previous_state is not None:
reward = define_reward_function(previous_state, current_state, action_params)
rewards.append(reward)
# Store state and action
states.append(current_state)
actions.append(action_params)
previous_state = current_state
time.sleep(0.1) # Adjust as needed
# Update model using collected experiences
if len(rewards) > 0:
update_policy_model(model, states, actions, rewards)
# Save model checkpoint
if episode % 10 == 0:
model.save(f"model_checkpoint_{episode}.h5")
return model
Implementation Considerations
1. Training Methodology
The hybrid approach of imitation learning followed by reinforcement learning offers several advantages:
-
Faster initial learning: By observing human gameplay first, the AI can quickly learn basic strategies rather than starting from random exploration[2][3].
-
Continuous improvement: The reinforcement learning phase allows the AI to surpass human demonstrations by discovering optimal strategies through experimentation[4][5].
This approach is particularly effective for your use case because:
- The 3-minute game loop provides a clear episode boundary for RL training
- The task has clear success metrics (explored map area, items collected)
- The continuous nature of the environment makes pure RL challenging to start from scratch
2. State Representation Optimization
For efficient learning, the state representation should:
- Focus on relative positions rather than absolute screen coordinates
- Encode the mini-map data efficiently to capture exploration opportunities
- Include sufficient history to understand movement patterns
3. Real-time Performance
Since the system needs to operate in real-time:
- Optimize the computer vision components using GPU acceleration when possible
- Implement a buffer system to handle any processing delays
- Consider running detection algorithms at a lower frequency than the game loop
Final Implementation Steps
-
Calibration Tools: Create utilities to calibrate color ranges for undiscovered areas and items
-
Visualization: Implement a visualization overlay to show what the AI is "seeing" and planning
-
Performance Metrics: Track and graph exploration percentage, items collected, and efficiency over time
-
Reset Mechanism: Implement the ability to detect game end and trigger resets programmatically
This implementation will provide a solid foundation for an AI that can efficiently explore maps and collect items based on visual information from the game screen and mini-map. The hybrid learning approach ensures both rapid initial learning and continuous optimization beyond human performance.