Path of Exile Autonomous Navigation System
This program will autonomously navigate in Path of Exile by analyzing the minimap, discovering unexplored areas, and collecting loot items. It uses computer vision for game state detection and reinforcement learning for intelligent navigation.
Core Program
import cv2
import numpy as np
import pyautogui
import time
import keyboard
import os
import random
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from collections import deque
import matplotlib.pyplot as plt
import json
from datetime import datetime
class PoENavigator:
def __init__(self):
# Configuration
self.minimap_region = None # Will be set during calibration
self.player_position = None # Center of minimap
self.loot_colors = [] # RGB values for loot detection
self.undiscovered_color_range = {
'lower': np.array([0, 0, 0]), # Default black
'upper': np.array([50, 50, 50]) # Dark gray
}
self.click_multiplier = 1.0 # Adjusts click distance
self.reset_interval = 120 # Reset every 2 minutes
self.last_reset_time = time.time()
# Training data
self.training_data = []
self.reward_history = []
self.model = None
self.is_training = False
self.memory = deque(maxlen=10000)
self.gamma = 0.95 # Discount factor
self.epsilon = 1.0 # Exploration rate
self.epsilon_min = 0.1
self.epsilon_decay = 0.995
# Performance metrics
self.areas_discovered = 0
self.items_collected = 0
self.setup_folders()
def setup_folders(self):
"""Create necessary folders for data storage"""
os.makedirs("training_data", exist_ok=True)
os.makedirs("models", exist_ok=True)
os.makedirs("logs", exist_ok=True)
def calibrate(self):
"""Calibrate the system by detecting minimap location"""
print("Starting calibration...")
print("Please hover your mouse over the top-left corner of the minimap and press 'T'")
while not keyboard.is_pressed('t'):
time.sleep(0.1)
top_left = pyautogui.position()
time.sleep(0.5)
print("Now hover your mouse over the bottom-right corner of the minimap and press 'T'")
while not keyboard.is_pressed('t'):
time.sleep(0.1)
bottom_right = pyautogui.position()
self.minimap_region = (
top_left[0], top_left[1],
bottom_right[0] - top_left[0],
bottom_right[1] - top_left[1]
)
# Set player position as center of minimap
self.player_position = (
self.minimap_region[0] + self.minimap_region[2] // 2,
self.minimap_region[1] + self.minimap_region[3] // 2
)
print(f"Minimap calibrated: {self.minimap_region}")
print(f"Player position set to: {self.player_position}")
def add_loot_color(self, r, g, b, tolerance=15):
"""Add a color to detect for loot pickup"""
self.loot_colors.append({
'rgb': (r, g, b),
'lower': np.array([max(0, r-tolerance), max(0, g-tolerance), max(0, b-tolerance)]),
'upper': np.array([min(255, r+tolerance), min(255, g+tolerance), min(255, b+tolerance)])
})
print(f"Added loot color RGB({r},{g},{b}) with tolerance {tolerance}")
def set_undiscovered_color_range(self, lower_rgb, upper_rgb):
"""Set the color range that represents undiscovered areas on the minimap"""
self.undiscovered_color_range = {
'lower': np.array(lower_rgb),
'upper': np.array(upper_rgb)
}
print(f"Undiscovered area color range set: {lower_rgb} to {upper_rgb}")
def capture_minimap(self):
"""Capture the current state of the minimap"""
screenshot = pyautogui.screenshot(region=self.minimap_region)
return cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
def detect_undiscovered_areas(self, minimap_img):
"""Detect undiscovered areas on the minimap"""
# Convert to HSV for better color detection
hsv = cv2.cvtColor(minimap_img, cv2.COLOR_BGR2HSV)
# Create mask for undiscovered area colors
mask = cv2.inRange(hsv, self.undiscovered_color_range['lower'],
self.undiscovered_color_range['upper'])
# Find contours of undiscovered areas
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
undiscovered_points = []
if contours:
# Find the centroid of each contour
for contour in contours:
if cv2.contourArea(contour) > 10: # Filter out noise
M = cv2.moments(contour)
if M["m00"] != 0:
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
undiscovered_points.append((cx, cy))
return undiscovered_points, mask
def detect_loot(self, screen_img):
"""Detect loot items on the screen based on configured colors"""
hsv = cv2.cvtColor(screen_img, cv2.COLOR_BGR2HSV)
loot_positions = []
for color in self.loot_colors:
mask = cv2.inRange(hsv, color['lower'], color['upper'])
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) > 5: # Filter small noise
M = cv2.moments(contour)
if M["m00"] != 0:
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
# Convert to screen coordinates
screen_x = cx + self.minimap_region[0]
screen_y = cy + self.minimap_region[1]
loot_positions.append((screen_x, screen_y))
return loot_positions
def calculate_click_position(self, target_point):
"""Calculate where to click based on the target point relative to player position"""
# Get center of minimap (player position)
center_x = self.minimap_region[2] // 2
center_y = self.minimap_region[3] // 2
# Calculate vector from center to target
dx = target_point[0] - center_x
dy = target_point[1] - center_y
# Calculate distance and angle
distance = np.sqrt(dx**2 + dy**2)
angle = np.arctan2(dy, dx)
# Apply multiplier to distance
adjusted_distance = distance * self.click_multiplier
# Calculate new point based on adjusted distance and angle
click_x = int(self.player_position[0] + adjusted_distance * np.cos(angle))
click_y = int(self.player_position[1] + adjusted_distance * np.sin(angle))
return (click_x, click_y)
def move_to_point(self, target_point):
"""Move the player to the target point"""
click_pos = self.calculate_click_position(target_point)
pyautogui.click(click_pos[0], click_pos[1])
time.sleep(0.5) # Wait for movement to start
return click_pos
def collect_loot(self, loot_positions):
"""Collect loot items at the given positions"""
items_collected = 0
for pos in loot_positions:
pyautogui.click(pos[0], pos[1])
items_collected += 1
time.sleep(0.2) # Small delay between clicks
self.items_collected += items_collected
return items_collected
def reset_game(self):
"""Reset the game/level"""
print("Resetting game...")
# Press a key combination to reset or return to town
pyautogui.press('f5') # Assuming F5 resets or we use portal scroll
time.sleep(5) # Wait for reset to complete
self.last_reset_time = time.time()
def create_state_representation(self, minimap_img, mask):
"""Create a simplified state representation for the AI"""
# Resize minimap to smaller dimensions for state representation
resized = cv2.resize(mask, (32, 32))
# Flatten and normalize
return resized.flatten() / 255.0
def build_model(self):
"""Build a neural network model for reinforcement learning"""
state_size = 32 * 32 # Resized minimap
action_size = 8 # 8 directions of movement
model = keras.Sequential([
layers.Dense(128, input_dim=state_size, activation='relu'),
layers.Dense(128, activation='relu'),
layers.Dense(action_size, activation='linear')
])
model.compile(loss='mse', optimizer=tf.keras.optimizers.Adam(learning_rate=0.001))
self.model = model
print("Neural network model built")
def remember(self, state, action, reward, next_state, done):
"""Store experience in memory for replay"""
self.memory.append((state, action, reward, next_state, done))
def act(self, state):
"""Choose an action based on the current state"""
if np.random.rand() <= self.epsilon:
# Exploration: random action
return random.randrange(8)
# Exploitation: use model to predict best action
act_values = self.model.predict(state.reshape(1, -1), verbose=0)
return np.argmax(act_values[0])
def replay(self, batch_size=32):
"""Train model on random batches from memory"""
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.reshape(1, -1), verbose=0)[0]
)
target_f = self.model.predict(state.reshape(1, -1), verbose=0)
target_f[0][action] = target
self.model.fit(state.reshape(1, -1), target_f, epochs=1, verbose=0)
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
def convert_action_to_point(self, action, minimap_center):
"""Convert a discrete action (0-7) to a point on the minimap"""
# 8 possible directions (N, NE, E, SE, S, SW, W, NW)
angle = action * (2 * np.pi / 8)
distance = 30 # Fixed distance
x = int(minimap_center[0] + distance * np.cos(angle))
y = int(minimap_center[1] + distance * np.sin(angle))
# Ensure within minimap bounds
x = max(0, min(x, self.minimap_region[2] - 1))
y = max(0, min(y, self.minimap_region[3] - 1))
return (x, y)
def calculate_reward(self, undiscovered_before, undiscovered_after, items_collected):
"""Calculate reward based on newly discovered areas and collected items"""
# Count pixels in undiscovered masks
before_count = np.sum(undiscovered_before > 0)
after_count = np.sum(undiscovered_after > 0)
# If we discovered new areas, before_count should be larger
discovery_reward = (before_count - after_count) * 0.01
discovery_reward = max(0, discovery_reward) # Ensure non-negative
# Reward for collecting items
item_reward = items_collected * 10
total_reward = discovery_reward + item_reward
return total_reward
def train(self, episodes=100):
"""Train the model using reinforcement learning"""
self.is_training = True
if not self.model:
self.build_model()
for episode in range(episodes):
print(f"Episode {episode+1}/{episodes}")
self.reset_game()
total_reward = 0
# Initial state
minimap_img = self.capture_minimap()
undiscovered_points, undiscovered_mask = self.detect_undiscovered_areas(minimap_img)
state = self.create_state_representation(minimap_img, undiscovered_mask)
# Main training loop
steps = 0
done = False
while not done and steps < 100: # Limit steps per episode
# Choose action
action = self.act(state)
# Convert action to a point and move
minimap_center = (self.minimap_region[2]//2, self.minimap_region[3]//2)
target_point = self.convert_action_to_point(action, minimap_center)
self.move_to_point(target_point)
# Give time for game to update
time.sleep(1)
# Get new state
new_minimap_img = self.capture_minimap()
new_undiscovered, new_mask = self.detect_undiscovered_areas(new_minimap_img)
next_state = self.create_state_representation(new_minimap_img, new_mask)
# Detect loot items in full screen
screen_img = np.array(pyautogui.screenshot())
loot_positions = self.detect_loot(screen_img)
items_collected = self.collect_loot(loot_positions)
# Calculate reward
reward = self.calculate_reward(undiscovered_mask, new_mask, items_collected)