Creating an AI Model for Game Automation with Imitation Learning
Creating an AI that can learn from player actions to navigate a game based on mini-map information involves several components working together. I'll outline a comprehensive approach to build this system using imitation learning techniques combined with computer vision.
System Architecture Overview
The system will consist of four main components:
- Screen Capture Module: Captures game screen and extracts relevant information
- Feature Extraction Module: Processes the mini-map and identifies undiscovered areas and items
- Action Decision Module: Uses a trained model to determine where to click
- Input Simulation Module: Executes clicks at the determined locations
Let's break down each component in detail.
Screen Capture and Processing
First, we need to continuously capture the game screen and extract the mini-map region:
import numpy as np
import cv2
import pyautogui
import time
class ScreenCaptureModule:
def __init__(self, minimap_region=(1700, 50, 200, 200)): # Example coordinates (x, y, width, height)
self.minimap_region = minimap_region
self.gameplay_center = None # Will be determined during calibration
def calibrate(self):
# Determine the center of the gameplay area
screen = pyautogui.screenshot()
screen_np = np.array(screen)
screen_height, screen_width = screen_np.shape[:2]
self.gameplay_center = (screen_width // 2, screen_height // 2)
print(f"Gameplay center calibrated to: {self.gameplay_center}")
def capture_screen(self):
# Capture full screen
screen = pyautogui.screenshot()
screen_np = np.array(screen)
return screen_np
def extract_minimap(self, screen_np):
# Extract the minimap region
x, y, w, h = self.minimap_region
minimap = screen_np[y:y+h, x:x+w]
return minimap
def find_minimap_center(self, minimap):
# Find the player's position (center of minimap)
height, width = minimap.shape[:2]
return (width // 2, height // 2)
Feature Extraction for Navigation and Items
Next, we need to process the mini-map to identify undiscovered areas and items:
class FeatureExtractionModule:
def __init__(self):
# Color ranges for undiscovered areas (in HSV format)
self.undiscovered_color_ranges = [
((25, 50, 70), (35, 255, 255)), # Example yellow/gold range
]
# Will be populated with item pixel ranges later
self.item_color_ranges = []
def add_item_color_range(self, lower_bound, upper_bound, item_name):
"""Add a new item color range to detect"""
self.item_color_ranges.append((lower_bound, upper_bound, item_name))
print(f"Added detection for item: {item_name}")
def detect_undiscovered_areas(self, minimap):
# Convert to HSV color space for better color detection
minimap_hsv = cv2.cvtColor(minimap, cv2.COLOR_RGB2HSV)
# Create a mask for undiscovered areas
mask = np.zeros(minimap.shape[:2], dtype=np.uint8)
for lower, upper in self.undiscovered_color_ranges:
color_mask = cv2.inRange(minimap_hsv, np.array(lower), np.array(upper))
mask = cv2.bitwise_or(mask, color_mask)
# Find contours of undiscovered areas
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# If contours are found, return the center of the largest one
if contours:
largest_contour = max(contours, key=cv2.contourArea)
M = cv2.moments(largest_contour)
if M["m00"] != 0:
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
return (cx, cy)
return None
def detect_items(self, screen_np):
"""Detect items in the full screen based on color ranges"""
screen_hsv = cv2.cvtColor(screen_np, cv2.COLOR_RGB2HSV)
items_found = []
for lower, upper, item_name in self.item_color_ranges:
mask = cv2.inRange(screen_hsv, np.array(lower), np.array(upper))
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) > 50: # Filter small noise
M = cv2.moments(contour)
if M["m00"] != 0:
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
items_found.append((cx, cy, item_name))
return items_found
Data Collection for Imitation Learning
Before we can train our AI, we need to collect data from human players:
class DataCollectionModule:
def __init__(self, screen_capture, feature_extraction):
self.screen_capture = screen_capture
self.feature_extraction = feature_extraction
self.training_data = []
self.recording = False
self.listener = None
def start_recording(self):
"""Start recording player actions"""
import pynput
from pynput import mouse
self.recording = True
def on_click(x, y, button, pressed):
if pressed and button == mouse.Button.left and self.recording:
# Capture current screen state
screen = self.screen_capture.capture_screen()
minimap = self.screen_capture.extract_minimap(screen)
minimap_center = self.screen_capture.find_minimap_center(minimap)
# Extract features
undiscovered_point = self.feature_extraction.detect_undiscovered_areas(minimap)
items = self.feature_extraction.detect_items(screen)
# Calculate relative position from minimap center
if undiscovered_point:
rel_x = undiscovered_point - minimap_center
rel_y = undiscovered_point[1] - minimap_center[1]
else:
rel_x, rel_y = 0, 0
# Save the data point
self.training_data.append({
'screen_state': {
'undiscovered_point': undiscovered_point,
'items': items
},
'action': {
'click_position': (x, y),
'relative_position': (rel_x, rel_y)
}
})
print(f"Recorded action: Click at ({x}, {y}), relative to minimap: ({rel_x}, {rel_y})")
self.listener = pynput.mouse.Listener(on_click=on_click)
self.listener.start()
print("Recording started. Play the game naturally.")
def stop_recording(self):
"""Stop recording player actions"""
if self.listener:
self.listener.stop()
self.recording = False
print(f"Recording stopped. Collected {len(self.training_data)} data points.")
def save_training_data(self, filename="training_data.npy"):
"""Save collected training data to file"""
np.save(filename, self.training_data)
print(f"Training data saved to {filename}")
Training the Model
Now we can train a model on the collected data:
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
class ModelTrainer:
def __init__(self):
self.model = None
def preprocess_data(self, training_data):
"""Preprocess the collected data for training"""
X = [] # Input features
y = [] # Output (click positions)
for data_point in training_data:
# Feature vector: [undiscovered_x, undiscovered_y, item1_x, item1_y, ...]
features = []
# Add undiscovered point relative coordinates
if data_point['screen_state']['undiscovered_point']:
features.extend(data_point['action']['relative_position'])
else:
features.extend([0, 0])
# Add item positions (limited to first 5 items for simplicity)
items = data_point['screen_state']['items'][:5]
for item in items:
features.extend([item, item[1]])
# Pad with zeros if less than 5 items
padding = (5 - len(items)) * 2
features.extend( * padding)
# Target is the click position (normalized)
target = data_point['action']['click_position']
X.append(features)
y.append(target)
return np.array(X), np.array(y)
def build_model(self, input_shape):
"""Build a neural network model for predicting click positions"""
model = Sequential([
Dense(128, activation='relu', input_shape=(input_shape,)),
Dense(64, activation='relu'),
Dense(32, activation='relu'),
Dense(2) # Output: (x, y) click position
])
model.compile(optimizer='adam', loss='mse')
return model
def train(self, X, y, epochs=100, batch_size=32):
"""Train the model on preprocessed data"""
input_shape = X.shape[1]
self.model = self.build_model(input_shape)
history = self.model.fit(
X, y,
epochs=epochs,
batch_size=batch_size,
validation_split=0.2
)
print("Model training completed")
return history
def save_model(self, filename="game_ai_model"):
"""Save the trained model"""
self.model.save(filename)
print(f"Model saved as {filename}")
Action Execution Module
The final component is the one that executes actions based on the model's predictions:
class ActionExecutionModule:
def __init__(self, screen_capture, feature_extraction, model, distance_multiplier=1.5):
self.screen_capture = screen_capture
self.feature_extraction = feature_extraction
self.model = model
self.distance_multiplier = distance_multiplier
def prepare_features(self, undiscovered_point, minimap_center, items):
"""Prepare features for model input"""
features = []
# Add undiscovered point relative coordinates
if undiscovered_point:
rel_x = undiscovered_point - minimap_center
rel_y = undiscovered_point[1] - minimap_center[1]
features.extend([rel_x, rel_y])
else:
features.extend([0, 0])
# Add item positions (limited to first 5 items for simplicity)
limited_items = items[:5]
for item in limited_items:
features.extend([item, item[1]])
# Pad with zeros if less than 5 items
padding = (5 - len(limited_items)) * 2
features.extend( * padding)
return np.array([features])
def decide_action(self):
"""Decide where to click based on current screen state"""
# Capture current screen state
screen = self.screen_capture.capture_screen()
minimap = self.screen_capture.extract_minimap(screen)
minimap_center = self.screen_capture.find_minimap_center(minimap)
# Extract features
undiscovered_point = self.feature_extraction.detect_undiscovered_areas(minimap)
items = self.feature_extraction.detect_items(screen)
# If there are items to pick up, prioritize those
if items:
closest_item = min(items, key=lambda i:
((i - self.screen_capture.gameplay_center)**2 +
(i[1] - self.screen_capture.gameplay_center[1])**2)**0.5)
return closest_item, closest_item[1]
# Otherwise, use the model to decide where to click
if undiscovered_point:
# Calculate the angle and distance from minimap center
dx = undiscovered_point - minimap_center
dy = undiscovered_point[1] - minimap_center[1]
# Scale by distance multiplier
scaled_dx = dx * self.distance_multiplier
scaled_dy = dy * self.distance_multiplier
# Calculate click position relative to gameplay center
click_x = self.screen_capture.gameplay_center + scaled_dx
click_y = self.screen_capture.gameplay_center[1] + scaled_dy
return int(click_x), int(click_y)
# If all else fails, let the model decide
features = self.prepare_features(undiscovered_point, minimap_center, items)
predicted_position = self.model.predict(features)
return int(predicted_position), int(predicted_position[1])
def execute_click(self, x, y):
"""Execute a click at the specified position"""
pyautogui.click(x, y)
print(f"Clicked at ({x}, {y})")
Main Game Loop Controller
Now we can integrate everything into a main controller:
class GameController:
def __init__(self, loop_duration=180): # 3 minutes in seconds
self.loop_duration = loop_duration
self.screen_capture = ScreenCaptureModule()
self.feature_extraction = FeatureExtractionModule()
self.data_collection = DataCollectionModule(self.screen_capture, self.feature_extraction)
self.model_trainer = ModelTrainer()
# Will be initialized after training
self.action_execution = None
# Flag to control the game loop
self.running = False
def calibrate(self):
"""Calibrate the system"""
print("Calibrating screen capture...")
self.screen_capture.calibrate()
print("Calibration complete")
def collect_training_data(self, duration=300): # 5 minutes by default
"""Collect training data from player actions"""
print(f"Starting data collection for {duration} seconds...")
self.data_collection.start_recording()
# Wait for the specified duration
for i in range(duration):
if i % 10 == 0:
print(f"Recording: {i}/{duration} seconds")
time.sleep(1)
self.data_collection.stop_recording()
self.data_collection.save_training_data()
def train_model(self):
"""Train the model on collected data"""
print("Loading training data...")
training_data = np.load("training_data.npy", allow_pickle=True)
print("Preprocessing data...")
X, y = self.model_trainer.preprocess_data(training_data)
print("Training model...")
self.model_trainer.train(X, y)
self.model_trainer.save_model()
# Initialize action execution with the trained model
self.action_execution = ActionExecutionModule(
self.screen_capture,
self.feature_extraction,
self.model_trainer.model
)
def start_game_loop(self):
"""Start the 3-minute game loop"""
if not self.action_execution:
print("Error: Model not trained. Please train the model first.")
return