Creating an AI Model to Learn and Automate Game Exploration
Creating an AI that can learn from player actions and automate gameplay is an exciting project that combines computer vision, reinforcement learning, and imitation learning. I'll outline a comprehensive approach to build a system that can monitor the mini-map, identify unexplored areas, and navigate efficiently while collecting items.
System Architecture
Your AI system will need several core components:
- Screen Capture Module: To continuously capture and process the game screen
- Computer Vision System: To analyze the mini-map and identify unexplored areas and items
- Action Controller: To translate decisions into mouse clicks
- Learning Algorithm: To learn optimal strategies from player demonstrations and self-play
Screen Capture and Processing
First, you'll need to capture the game screen and isolate the relevant regions:
import cv2
import numpy as np
import pyautogui
import time
def capture_screen():
# Capture the entire screen
screenshot = pyautogui.screenshot()
# Convert to numpy array
frame = np.array(screenshot)
# Convert from RGB to BGR format for OpenCV
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
return frame
def extract_minimap(frame, minimap_position):
# Extract the minimap region
x, y, w, h = minimap_position
minimap = frame[y:y+h, x:x+w]
return minimap
Mini-map Analysis
You'll need to process the mini-map to identify unexplored areas:
def identify_unexplored_areas(minimap, color_range):
# Convert to HSV for better color detection
hsv = cv2.cvtColor(minimap, cv2.COLOR_BGR2HSV)
# Define lower and upper bounds for the unexplored area color
lower_bound = np.array(color_range)
upper_bound = np.array(color_range[1])
# Create a mask of all pixels within the color range
mask = cv2.inRange(hsv, lower_bound, upper_bound)
# Find contours of unexplored areas
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Find centroid of largest unexplored area
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
Item Detection
To detect items on the ground:
def detect_items(frame, item_color_ranges):
items = []
for color_range in item_color_ranges:
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_bound = np.array(color_range)
upper_bound = np.array(color_range[1])
mask = cv2.inRange(hsv, lower_bound, upper_bound)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) > 50: # Minimum size to avoid 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))
return items
Learning Approach
For this task, I recommend a hybrid approach combining imitation learning and reinforcement learning, similar to what's described in the search results[2][3][4].
Phase 1: Imitation Learning
Start with imitation learning to bootstrap the AI with basic behaviors:
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, MaxPooling2D
class ImitationLearner:
def __init__(self):
self.model = self._build_model()
self.training_data = []
def _build_model(self):
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(84, 84, 3)),
MaxPooling2D(2, 2),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D(2, 2),
Flatten(),
Dense(128, activation='relu'),
Dense(64, activation='relu'),
Dense(3) # Output: direction_x, direction_y, click_strength
])
model.compile(optimizer='adam', loss='mse')
return model
def collect_training_data(self, minimap_state, player_action):
self.training_data.append((minimap_state, player_action))
def train(self, epochs=10, batch_size=32):
if not self.training_data:
return
X = np.array([data for data in self.training_data])
y = np.array([data[1] for data in self.training_data])
self.model.fit(X, y, epochs=epochs, batch_size=batch_size)
def predict_action(self, minimap_state):
minimap_state = np.expand_dims(minimap_state, axis=0)
return self.model.predict(minimap_state)
Phase 2: Reinforcement Learning
After initial training, use Deep Q-Learning to refine the agent's strategy[4][7]:
import random
from collections import deque
class DeepQAgent:
def __init__(self, state_size, action_size):
self.state_size = state_size
self.action_size = action_size
self.memory = deque(maxlen=2000)
self.gamma = 0.95 # discount rate
self.epsilon = 1.0 # exploration rate
self.epsilon_min = 0.01
self.epsilon_decay = 0.995
self.model = self._build_model()
def _build_model(self):
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=self.state_size),
MaxPooling2D(2, 2),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D(2, 2),
Flatten(),
Dense(128, activation='relu'),
Dense(64, activation='relu'),
Dense(self.action_size, activation='linear')
])
model.compile(optimizer='adam', loss='mse')
return model
def remember(self, state, action, reward, next_state, done):
self.memory.append((state, action, reward, next_state, done))
def act(self, state):
if np.random.rand() <= self.epsilon:
# Return a random action (exploration)
return np.random.randint(0, self.action_size)
# Use the model to predict the best action (exploitation)
act_values = self.model.predict(state)
return np.argmax(act_values)
def replay(self, batch_size):
if len(self.memory) < batch_size:
return
minibatch = random.sample(self.memory, batch_size)
for state, action, reward, next_state, done in minibatch:
target = reward
if not done:
target = (reward + self.gamma *
np.amax(self.model.predict(next_state)))
target_f = self.model.predict(state)
target_f[action] = target
self.model.fit(state, target_f, epochs=1, verbose=0)
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
Implementing the Game Controller
The controller translates AI decisions into in-game actions:
def calculate_click_position(minimap_center, target_point, game_center, distance_multiplier):
# Calculate direction vector from minimap center to target
direction_x = target_point - minimap_center
direction_y = target_point[1] - minimap_center[1]
# Normalize direction
magnitude = np.sqrt(direction_x**2 + direction_y**2)
if magnitude > 0:
normalized_x = direction_x / magnitude
normalized_y = direction_y / magnitude
else:
return game_center # No movement if no direction
# Calculate click position based on game center and multiplier
click_x = game_center + normalized_x * distance_multiplier
click_y = game_center[1] + normalized_y * distance_multiplier
return (int(click_x), int(click_y))
def perform_click(position):
pyautogui.click(position, position[1])
Reward System
The reward function is critical for reinforcement learning[5]:
def calculate_reward(current_state, next_state, items_collected, time_elapsed):
# Reward for exploring new areas
exploration_reward = measure_exploration_progress(current_state, next_state)
# Reward for collecting items
item_reward = items_collected * 5.0
# Time penalty to encourage efficiency
time_penalty = -0.1 * time_elapsed
return exploration_reward + item_reward + time_penalty
def measure_exploration_progress(current_state, next_state):
# Calculate how much new area was discovered
current_unexplored = count_unexplored_pixels(current_state)
next_unexplored = count_unexplored_pixels(next_state)
# Reward based on reduction in unexplored area
return (current_unexplored - next_unexplored) * 0.1
Training Pipeline
The complete training pipeline combines all these components:
def train_agent():
# Configuration
minimap_position = (1200, 50, 200, 200) # x, y, width, height
game_center = (640, 360) # Center of gameplay area
minimap_center = (minimap_position + minimap_position[2]//2,
minimap_position[1] + minimap_position[3]//2)
distance_multiplier = 100
unexplored_color_range = [([160, 100, 100], [180, 255, 255])] # HSV range for red
item_color_ranges = [([20, 100, 100], [30, 255, 255])] # Example: HSV range for yellow items
# Initialize learning agents
imitation_learner = ImitationLearner()
dq_agent = DeepQAgent((84, 84, 3), 8) # 8 possible directions
# Training loop
learning_phase = "imitation" # Start with imitation learning
episodes = 100
for episode in range(episodes):
print(f"Episode {episode+1}/{episodes}")
# Reset game (placeholder - implement game-specific reset)
reset_game()
# Game loop - 3 minutes
start_time = time.time()
total_reward = 0
items_collected = 0
while time.time() - start_time < 180: # 3 minutes
# Capture and process screen
frame = capture_screen()
minimap = extract_minimap(frame, minimap_position)
# Process minimap to find unexplored areas
unexplored_target = identify_unexplored_areas(minimap, unexplored_color_range)
# Detect items
items = detect_items(frame, item_color_ranges)
# Decision: prioritize items or exploration
if items and np.random.rand() < 0.7: # 70% chance to pick up items when visible
target = items
click_pos = target # Direct click on item
elif unexplored_target:
click_pos = calculate_click_position(
minimap_center, unexplored_target, game_center, distance_multiplier)
else:
# Random exploration if no clear target
random_angle = np.random.rand() * 2 * np.pi
random_x = minimap_center + np.cos(random_angle) * 50
random_y = minimap_center[1] + np.sin(random_angle) * 50
click_pos = calculate_click_position(
minimap_center, (random_x, random_y), game_center, distance_multiplier)
# Execute action
perform_click(click_pos)
# Wait for game to respond
time.sleep(0.5)
# Capture new state
new_frame = capture_screen()
new_minimap = extract_minimap(new_frame, minimap_position)
# Calculate reward
new_items = detect_items(new_frame, item_color_ranges)
items_collected += max(0, len(items) - len(new_items))
reward = calculate_reward(minimap, new_minimap, items_collected, 0.5)
total_reward += reward
# Store experience
if learning_phase == "imitation":
# If in imitation phase, just record player actions
if is_player_acting():
player_action = get_player_action()
imitation_learner.collect_training_data(minimap, player_action)
else:
# Reinforcement learning phase
state = preprocess_state(minimap)
next_state = preprocess_state(new_minimap)
action = direction_to_action(click_pos, game_center)
done = time.time() - start_time >= 180
dq_agent.remember(state, action, reward, next_state, done)
# Train on batch
if len(dq_agent.memory) > 32:
dq_agent.replay(32)
# End of episode
print(f"Episode {episode+1} complete. Total reward: {total_reward}")
# Switch from imitation to reinforcement after 20 episodes
if episode == 20:
learning_phase = "reinforcement"
print("Switching to reinforcement learning phase")
# Train imitation learner one final time
imitation_learner.train(epochs=50)
# Initialize DQ agent with imitation learning
# (Implementation depends on how the models are structured)
Evaluation and Fine-tuning
To evaluate your AI's performance:
def evaluate_agent(agent, num_episodes=5):
total_rewards = []
for episode in range(num_episodes):
reset_game()
episode_reward = 0
start_time = time.time()
while time.time() - start_time < 180:
frame = capture_screen()
minimap = extract_minimap(frame, minimap_position)
state = preprocess_state(minimap)
action = agent.act(state)
click_pos = action_to_click_position(action, game_center)
perform_click(click_pos)
time.sleep(0.5)
new_frame = capture_screen()
new_minimap = extract_minimap(new_frame, minimap_position)
items_before = detect_items(frame, item_color_ranges)
items_after = detect_items(new_frame, item_color_ranges)
items_collected = max(0, len(items_before) - len(items_after))
reward = calculate_reward(minimap, new_minimap, items_collected, 0.5)