我會給你程式碼 幫我找出有限制FPS的CODE 沒有這段程式碼請說沒有
class Config:
'''
====== Configuration Parameters ======
Tune these values based on your gameplay and detection needs.
--------------------------------------
'''
# ────────────────
# Perference
# ────────────────
is_use_aoe = True # use aoe skill to attack instead of magic claw
is_use_teleport_to_walk = False # use teleport to walk
teleport_cooldown = 1 # second
is_edge_teleport = True
code
# ────────────────
# Edge Teleport
# ────────────────
edge_teleport_box_width = 120
edge_teleport_box_height = 70
edge_teleport_color_code = (255,127,127) # (R,G,B)
# ────────────────
# Keyboard Mapping
# ────────────────
aoe_skill_key = "1" # It can be monk's healing skill
magic_claw_key = "1"
jump_key = "space"
heal_key = "4"
add_mp_key = "5"
teleport_key = "2"
# ────────────────
# Player Localization
# ────────────────
# offset from the nametag's top-left corner to the player's center
nametag_offset = (-50, 30) # pixel
nametag_diff_thres = 0.4
# ────────────────
# Camera Localization
# ────────────────
# only use this vertical range of the screen to localize camera on map
camera_ceiling = 60 # pixel (top)
camera_floor = 665 # pixel (bottom)
localize_diff_thres = 0.5
localize_downscale_factor = 1.0 #0.25 # ratio = 1/4
# ────────────────
# Attack Settings
# ────────────────
# aoe skill attack range relative to player position
aoe_skill_range_x = 400 # pixels (horizontal range)
aoe_skill_range_y = 150 # pixels (vertical range)
# magic claw skill attack range relative to player position
magic_claw_range_x = 350 # pixels (horizontal range)
magic_claw_range_y = 70 # pixels (vertical range)
# ────────────────
# Monster Detection
# ────────────────
monster_diff_thres = 0.8 # template match similarity threshold
monster_search_margin = 50 # extra margin around attack box for monster search
blur_range = 5
# ────────────────
# Route Detection (color code)
# ────────────────
color_code_search_range = 80 # radius to find nearest color route from player center
# ────────────────
# Movement Behavior
# ────────────────
up_drag_duration = 0.1 # hold duration for 'up' key to prevent rope-sticking (in seconds)
watch_dog_timeout = 10 # seconds, if player doesn't move for 3 second, random perform an action
watch_dog_range = 10 # pixel, if player location is smaller than watch_dog_range, consider it doesn't move
# ────────────────
# Debug Options
# ────────────────
enable_debug_windows = True # show debug window (false = better performance)
# ────────────────
# Runes Warning
# ────────────────
rune_warning_top_left = (513, 196)
rune_warning_bottom_right = (768, 236)
rune_warning_diff_thres = 0.2
# ────────────────
# Rune Detection
# ────────────────
rune_detect_box_width = 120
rune_detect_box_height = 150
rune_detect_diff_thres = 0.1
rune_finding_timeout = 600 # second
near_rune_duration = 5 # second
# ────────────────
# Rune mini-game
# ────────────────
arrow_box_size = 80 # pixel, 75x75 box
arrow_box_interval = 170 # pixel width
arrow_box_start_point = (355, 355)
arrow_box_diff_thres = 0.2
# ────────────────
# HP Bar and HP bar
# ────────────────
hp_bar_top_left = (348, 732)
hp_bar_bottom_right = (509, 749)
mp_bar_top_left = (517, 732)
mp_bar_bottom_right = (678, 749)
heal_ratio = 0.5 # heal when hp is below 50%
add_mp_ratio = 0.5 # drink potion when mp is below 50%
# ────────────────
# Patrol
# ────────────────
monster_patrol_dif_thres = 0.8
# ────────────────
# Don't modify the following parameter unless you know what you are doing
# ────────────────
game_window_title = 'MapleStory Worlds-Artale (繁體中文版)'
# color code for patrol route
color_code = {
# R G B
(255, 0, 0): "walk left", # red
(0, 0, 255): "walk right", # blue
(255,127,0): "jump left", # orange
(0,255,255): "jump right", # sky blue
(127,255,0): "jump down", # light_green
(255,0,255): "jump", # purple
(127,127,127): "up", # gray
(0,255,0): "stop", # green
(255,255,0): "goal", # yellow
(255,0,127): "teleport up", # pink
(127,0,255): "teleport down", # light_purple
}
window_size = (752, 1282)
Assistant
您提供的程式碼中沒有包含有限制 FPS(Frames Per Second,幀率)的相關設定或控制程式碼。
import time
import random
import argparse
import glob
import sys
CV import
import numpy as np
import cv2
local import
from config.config import Config
from logger import logger
from util import find_pattern_sqdiff, draw_rectangle, screenshot, nms,
load_image, get_mask, get_minimap_loc_size, get_player_location_on_minimap, is_mac
from KeyBoardController import KeyBoardController
if is_mac():
from GameWindowCapturorForMac import GameWindowCapturor
else:
from GameWindowCapturor import GameWindowCapturor
from HealthMonitor import HealthMonitor
class MapleStoryBot:
'''
MapleStoryBot
'''
def init(self, args):
'''
Init MapleStoryBot
'''
self.cfg = Config # Configuration
self.args = args # User arguments
self.status = "hunting" # 'resting', 'finding_rune', 'near_rune'
self.idx_routes = 0 # Index of route map
self.monster_info = [] # monster information
self.fps = 0 # Frame per second
self.is_first_frame = True # first frame flag
self.rune_detect_level = 0 # higher the level, lower the rune detect threshold
# Coordinate (top-left coordinate)
self.loc_nametag = (0, 0) # nametag location on game screen
self.loc_minimap = (0, 0) # minimap location on game screen
self.loc_player = (0, 0) # player location on game screen
self.loc_player_minimap = (0, 0) # player location on minimap
self.loc_minimap_global = (0, 0) # minimap location on global map
self.loc_player_global = (0, 0) # player location on global map
self.loc_watch_dog = (0, 0) # watch dog location on global map
# Images
self.frame = None # raw image
self.img_frame = None # game window frame
self.img_frame_gray = None # game window frame graysale
self.img_frame_debug = None # game window frame for visualization
self.img_route = None # route map
self.img_route_debug = None # route map for visualization
self.img_minimap = None # minimap on game screen
# Timers
self.t_last_frame = time.time() # Last frame timer, for fps calculation
self.t_last_switch_status = time.time() # Last status switches timer
self.t_watch_dog = time.time() # Last movement timer
self.t_last_teleport = time.time() # Last teleport timer
self.t_patrol_last_attack = time.time() # Last patrol attack timer
self.t_last_attack = time.time() # Last attack timer for cooldown
# Patrol mode
self.is_patrol_to_left = True # Patrol direction flag
self.patrol_turn_point_cnt = 0 # Patrol tuning back counter
while True:
t_start = time.time()
# Process one game window frame
mapleStoryBot.run_once()
# Exit if 'q' is pressed
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
# Cap FPS to save system resource
frame_duration = time.time() - t_start
target_duration = 1.0 / mapleStoryBot.cfg.fps_limit
if frame_duration < target_duration:
time.sleep(target_duration - frame_duration)
import time
import random
import argparse
import glob
import sys
import numpy as np
import cv2
local import
from config.legacy.config_legacy import Config
from logger import logger
from util import find_pattern_sqdiff, draw_rectangle, screenshot, nms, load_image, get_mask
from KeyBoardController import KeyBoardController
from GameWindowCapturorSelector import GameWindowCapturor
class MapleStoryBot:
'''
MapleStoryBot
'''
def init(self, args):
self.cfg = Config # Configuration
self.args = args
self.status = "hunting" # 'resting', 'finding_rune', 'near_rune', 'solving_rune'
self.idx_routes = 0 # Index of route
self.hp_ratio = 1.0 # HP bar ratio
self.mp_ratio = 1.0 # MP bar ratio
self.exp_ratio = 1.0 # EXP bar ratio
self.monster_info = [] # monster information
self.fps = 0 # Frame per second
self.is_first_frame = True # Disable cached location for first frame
self.rune_detect_level = 0
# Coordinate (top-left coordinate)
self.loc_nametag = (0, 0) # nametag location on window
self.loc_camera = (0, 0) # camera location on map
self.loc_watch_dog = (0, 0) # watch dog
self.loc_player_global = (0, 0) # player location on map
self.loc_player = (0, 0) # player location on window
self.loc_player_minimap = (0, 0) # Player's location on minimap
self.loc_minimap = (0, 0)
# Images
self.frame = None # raw image
self.img_frame = None # game window frame
self.img_frame_gray = None # game window frame graysale
self.img_frame_debug = None
self.img_route = None # route map
self.img_route_debug = None
# Timers
self.t_last_frame = time.time() # Last frame timer, for fps calculation
self.t_last_switch_status = time.time() # Last status switches timer
self.t_watch_dog = time.time() # Last movement timer
self.t_last_teleport = time.time() # Last teleport timer
self.t_patrol_last_attack = time.time() # Last patrol attack timer
self.t_last_camera_missed = time.time() # Last camera loc missed
# Patrol mode
self.is_patrol_to_left = True
self.patrol_turn_point_cnt = 0
self.img_frame_gray_last = None
code
Assistant
您提供的這份完整程式碼中,有限制 FPS 的程式碼段如下:
python
while True:
t_start = time.time()
# Process one game window frame
mapleStoryBot.run_once()
# Exit if 'q' is pressed
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
# Cap FPS to save system resource
frame_duration = time.time() - t_start
target_duration = 1.0 / mapleStoryBot.cfg.fps_limit
if frame_duration < target_duration:
time.sleep(target_duration - frame_duration)
import time
import random
import argparse
import glob
import sys
import os
import shutil
CV import
import numpy as np
import cv2
local import
from config.config import Config
from logger import logger
from util import find_pattern_sqdiff, draw_rectangle, screenshot, nms,
load_image, get_mask, get_minimap_loc_size, get_player_location_on_minimap,
to_opencv_hsv
from KeyBoardListener import KeyBoardListener
from GameWindowCapturor import GameWindowCapturor
class RouteRecorder():
'''
Route recorder
'''
def update_info_on_img_frame_debug(self):
'''
update_info_on_img_frame_debug
'''
# Print text at bottom left corner
self.fps = round(1.0 / (time.time() - self.t_last_frame))
text_y_interval = 23
text_y_start = 550
dt_screenshot = time.time() - self.kb.t_func_key[1]
dt_save_route = time.time() - self.kb.t_func_key[2]
dt_save_map = time.time() - self.kb.t_func_key[3]
text_list = [
f"FPS: {self.fps}",
f"Press 'F1' to {'pause' if self.is_enable else 'start'} route record",
f"Press 'F2' to save screenshot{' : Saved' if dt_screenshot < 0.7 else ''}",
f"Press 'F3' to save route{' : Saved' if dt_save_route < 0.7 else ''}",
f"Press 'F4' to save map{' : Saved' if dt_save_map < 0.7 else ''}",
]
for idx, text in enumerate(text_list):
cv2.putText(
self.img_frame_debug, text,
(10, text_y_start + text_y_interval*idx),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
code
Assistant
您這份「Auto generate route map」的程式碼中有限制 FPS 的地方是:
python
while True:
t_start = time.time()
# Process one game window frame
routeRecorder.run_once()
# Exit if 'q' is pressed
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
# Cap FPS to save system resource
frame_duration = time.time() - t_start
target_duration = 1.0 / routeRecorder.cfg.fps_limit
if frame_duration < target_duration:
time.sleep(target_duration - frame_duration)
import cv2
import datetime
import os
import platform
import numpy as np
Local import
from logger import logger
OS_NAME = platform.system()
def is_mac():
return OS_NAME == 'Darwin'
def is_windows():
return OS_NAME == 'Windows'
def load_image(path, mode=cv2.IMREAD_COLOR):
'''
Load image from disk and verify existence.
'''
if not os.path.exists(path):
logger.error(f"Image not found: {path}")
raise FileNotFoundError(f"Image not found: {path}")
code
# Load image
img = cv2.imread(path, mode)
if img is None:
logger.error(f"Failed to load image file: {path}")
raise ValueError(f"Failed to load image: {path}")
logger.info(f"Loaded image: {path}")
return img
Parameters:
- monsters: List of dictionaries, each representing a detected monster with:
- "position": (x, y) top-left corner
- "size": (width, height)
- "score": similarity/confidence score from template matching
- iou_threshold: Float, intersection-over-union threshold to suppress overlapping boxes
Returns:
- List of filtered monster dictionaries after applying NMS
'''
boxes = []
for m in monsters:
x, y = m["position"]
w, h = m["size"]
# [x1, y1, x2, y2, score, original_data]
boxes.append([x, y, x + w, y + h, m["score"], m])
# Sort by score descending
boxes.sort(key=lambda x: x[4], reverse=True)
keep = []
while boxes:
best = boxes.pop(0)
keep.append(best[5]) # original monster_info
boxes = [b for b in boxes if get_iou(best, b) < iou_threshold]
return keep
def get_iou(box1, box2):
'''
Calculate the Intersection over Union (IoU) between two bounding boxes.
Assistant
您提供的這份 util 工具函式模組,其中沒有任何與 FPS 限制(Frames Per Second)相關的程式碼。
class Config:
'''
====== Configuration Parameters ======
Tune these values based on your gameplay and detection needs.
--------------------------------------
'''
# ────────────────
# Keyboard Mapping
# ────────────────
# Adjust the following key to match the in-game keybinding for your character.
code
Assistant
您這段 Config 類別中,確實包含 FPS 限制相關的設定:
python
# ────────────────
# System
# ────────────────
# FPS(Frame per Second) limit for main thread
fps_limit = 10
show_debug_window = True # False, disable debug window to save system resource
Traceback (most recent call last):
File "C:\Users\Jay\Desktop\MapleStoryAutoLevelUp-main\MapleStoryAutoLevelUp.py", line 17, in
import yaml
ModuleNotFoundError: No module named 'yaml'
安裝完成後,再次執行程式就不會出現 ModuleNotFoundError: No module named 'yaml'。
如果你是在虛擬環境中,請確認已切換到該環境後再安裝。
如還有其他問題,也可以繼續詢問!
User
哪段程式碼有提到有其他玩家
Assistant
您提供的所有程式碼及敘述中,沒有看到任何一段程式碼明確提及或處理「其他玩家」的內容。
這些程式碼主要聚焦於:
擷取遊戲畫面(截圖)
偵測怪物(Monster)位置
健康監控(HP/MP)
路線點擊與尋路(Route)
血條與符文偵測
控制鍵盤與行為指令
似乎都只針對主角角色與怪物相關資訊,沒有偵測或判斷遊戲中的其他玩家(例如其他人類角色、隊友等)。
如果您需要偵測或處理「其他玩家」,通常會在:
圖像處理中增加辨識其他玩家的模版或特徵(例如名字板、玩家角色外觀模板匹配)
行為邏輯中針對玩家與怪物進行區分
網路或遊戲狀態中抓取玩家相關資料(需遊戲API或加碼)
若您有特定相關需求,或程式碼中您懷疑有提及「其他玩家」的部分,可以提供,我可以協助深入解析。
User
WARNING: Minimap not found in the game frame.
[2025-06-22 21:47:26] WARNING: Failed to get minimap location and size.
[2025-06-22 21:47:26] WARNING: Minimap not found in the game frame.
[2025-06-22 21:47:26] WARNING: Failed to get minimap location and size.
[2025-06-22 21:47:26] WARNING: Minimap not found in the game frame.
[2025-06-22 21:47:26] WARNING: Failed to get minimap location and size.
[2025-06-22 21:47:26] WARNING: Minimap not found in the game frame.
[2025-06-22 21:47:26] WARNING: Failed to get minimap location and size.
[2025-06-22 21:47:28] WARNING: Other player movement > 10px detected, triggering channel change.
Start channel change process
Assistant
從您的日誌來看,有兩個主要訊息:
Minimap 找不到
code
WARNING: Minimap not found in the game frame.
WARNING: Failed to get minimap location and size.
這代表程式無法在遊戲畫面截圖中找到 minimap 的位置及大小,通常可能原因有:
遊戲解析度或視窗大小與程式預期不符。
minimap 的顏色、邊框或樣式跟程式尋找的條件不符。
minimap 有被遮擋或不在視野範圍內。
偵測到其他玩家移動
code
WARNING: Other player movement > 10px detected, triggering channel change.
Start channel change process
Minimap not found 是主要造成定位跟路線錯誤問題的可能原因,解決 minimap 偵測問題是首要。
有偵測到「其他玩家移動」,說明程式中對玩家群體有一定的辨識與反應。
可以提供發生換頻道部分的程式碼,我能協助您檢查該邏輯細節與調整建議。
如果需要我協助分析您專案內其他玩家偵測或 minimap 定位的程式碼,請告訴我!
User
Start channel change process
Exception in thread Thread-1 (run):
Traceback (most recent call last):
File "C:\Users\Jay\AppData\Local\Programs\Python\Python313\Lib\threading.py", line 1043, in _bootstrap_inner
self.run()
~~~~~~~~^^
File "C:\Users\Jay\AppData\Local\Programs\Python\Python313\Lib\threading.py", line 994, in run
self._target(*self.args, **self.kwargs)
~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Jay\Desktop\MapleStoryAutoLevelUp-main\KeyBoardController.py", line 202, in run
pyautogui.keyUp("up")
~~~~~~~~~~~~~~~^^^^^^
File "C:\Users\Jay\AppData\Local\Programs\Python\Python313\Lib\site-packages\pyautogui_init.py", line 593, in wrapper
failSafeCheck()
~~~~~~~~~~~~~^^
File "C:\Users\Jay\AppData\Local\Programs\Python\Python313\Lib\site-packages\pyautogui_init.py", line 1734, in failSafeCheck
raise FailSafeException(
"PyAutoGUI fail-safe triggered from mouse moving to a corner of the screen. To disable this fail-safe, set pyautogui.FAILSAFE to False. DISABLING FAIL-SAFE IS NOT RECOMMENDED."
)
pyautogui.FailSafeException: PyAutoGUI fail-safe triggered from mouse moving to a corner of the screen. To disable this fail-safe, set pyautogui.FAILSAFE to False. DISABLING FAIL-SAFE IS NOT RECOMMENDED.
[2025-06-22 21:48:15] WARNING: Other player movement > 10px detected, triggering channel change.
Start channel change process
Assistant
從錯誤訊息來看,您的程式執行時觸發了 PyAutoGUI 的「fail-safe」機制:
code
pyautogui.FailSafeException: PyAutoGUI fail-safe triggered from mouse moving to a corner of the screen. To disable this fail-safe, set pyautogui.FAILSAFE to False. DISABLING FAIL-SAFE IS NOT RECOMMENDED.
# Health monitoring state
self.hp_ratio = 1.0
self.mp_ratio = 1.0
self.exp_ratio = 1.0
self.last_heal_time = 0
self.last_mp_time = 0
# Frame data (will be updated by main thread)
self.img_frame = None
self.frame_lock = threading.Lock()
# Debug information
# hp/mp/exp bars loc and size, [(x,y,w,h), ...]
self.loc_size_bars = [(0, 0, 0, 0),
(0, 0, 0, 0),
(0, 0, 0, 0)]
def start(self):
'''
Start health monitoring thread
'''
if not self.running:
self.running = True
self.thread = threading.Thread(target=self._monitor_loop, daemon=True)
self.thread.start()
logger.info("[Health Monitor]: Started")
def stop(self):
'''
Stop health monitoring thread
'''
self.running = False
if self.thread:
self.thread.join()
logger.info("[Health Monitor]: Stopped")
def enable(self):
'''
Enable health monitoring
'''
self.enabled = True
def disable(self):
'''
Disable health monitoring
'''
self.enabled = False
def update_frame(self, img_frame):
'''
Update frame data from main thread
'''
with self.frame_lock:
self.img_frame = img_frame
def get_hp_mp_exp_ratio(self):
'''
Extracts the player's HP, MP, and EXP ratios from game frame.
This function:
- Crops the predefined HP, MP, and EXP bar regions from the game frame.
- Identifies empty areas in each bar.
- Computes the fill ratio for each bar as: 1 - (empty_pixels / total_pixels).
Returns:
tuple: (hp_ratio, mp_ratio, exp_ratio), each a float between 0 and 1.
'''
if self.img_frame is None:
return None, None, None
with self.frame_lock:
img_frame = self.img_frame.copy()
img_frame_gray = cv2.cvtColor(img_frame, cv2.COLOR_BGR2GRAY)
white_mask = cv2.inRange(img_frame_gray, 240, 255)
# cv2.imshow("white_mask", white_mask)
contours, _ = cv2.findContours(white_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
loc_size_bars = []
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
# for game window resolution 752x1282, w/h == 7.5, w*h == 3630
if 4 < w/h < 10 and 2500 < w*h < 5000:
loc_size_bars.append((x, y, w, h))
# sort contours by x coordinate
loc_size_bars = sorted(loc_size_bars, key=lambda bar: bar[0])
if len(loc_size_bars) != 3:
logger.warning(f"[Health Monitor]: HP/MP/EXP bar detection has an unexpected result:{loc_size_bars}")
return (None, None, None)
# Update loc_size_bars
self.loc_size_bars = loc_size_bars
# Get bar filled ratio
ratio_bars = []
for x, y, w, h in loc_size_bars:
ratio_bars.append(get_bar_ratio(img_frame[y:y+h, x:x+w]))
return ratio_bars
def get_hp_mp_ratio_legacy(self):
'''
Deprecated: This hp/mp bar detection method require specific window resolution as input
and use hard-coded pixel coordinate to capture hp/mp bar
This function is replaced by get_hp_mp_exp_ratio() which is more flexiable and
can work on different window resolution
Extract HP and MP ratios from current frame
'''
if self.img_frame is None:
return 1.0, 1.0
with self.frame_lock:
img_frame = self.img_frame.copy()
# HP crop
hp_bar = img_frame[self.cfg.hp_bar_top_left[1]:self.cfg.hp_bar_bottom_right[1]+1,
self.cfg.hp_bar_top_left[0]:self.cfg.hp_bar_bottom_right[0]+1]
# MP crop
mp_bar = img_frame[self.cfg.mp_bar_top_left[1]:self.cfg.mp_bar_bottom_right[1]+1,
self.cfg.mp_bar_top_left[0]:self.cfg.mp_bar_bottom_right[0]+1]
# HP Detection (detect empty part)
empty_mask_hp = (hp_bar[:,:,0] == hp_bar[:,:,1]) & (hp_bar[:,:,0] == hp_bar[:,:,2])
empty_pixels_hp = max(0, len(empty_mask_hp[empty_mask_hp]) - 6) # 6 pixel always be white
total_pixels_hp = hp_bar.shape[0] * hp_bar.shape[1] - 6
hp_ratio = 1 - (empty_pixels_hp / max(1, total_pixels_hp))
# MP Detection (detect empty part)
empty_mask_mp = (mp_bar[:,:,0] == mp_bar[:,:,1]) & (mp_bar[:,:,0] == mp_bar[:,:,2])
empty_pixels_mp = max(0, len(empty_mask_mp[empty_mask_mp]) - 6) # 6 pixel always be white
total_pixels_mp = mp_bar.shape[0] * mp_bar.shape[1] - 6
mp_ratio = 1 - (empty_pixels_mp / max(1, total_pixels_mp))
return max(0, min(1, hp_ratio)), max(0, min(1, mp_ratio))
def _monitor_loop(self):
'''
Main monitoring loop running in separate thread
'''
while self.running:
try:
if not self.enabled or self.args.disable_control:
time.sleep(0.1)
continue
# Get current HP/MP ratios
hp_ratio, mp_ratio, exp_ratio = self.get_hp_mp_exp_ratio()
if hp_ratio is not None:
self.hp_ratio = hp_ratio
if mp_ratio is not None:
self.mp_ratio = mp_ratio
if exp_ratio is not None:
self.exp_ratio = exp_ratio
current_time = time.time()
# Check if need to heal (with cooldown)
if (self.hp_ratio <= self.cfg.heal_ratio and
current_time - self.last_heal_time > self.cfg.heal_cooldown):
self._heal()
self.last_heal_time = current_time
logger.info(f"[Health Monitor]: Auto heal triggered, HP: {self.hp_ratio*100:.1f}%")
# Check if need MP (with cooldown)
if (self.mp_ratio <= self.cfg.add_mp_ratio and
current_time - self.last_mp_time > self.cfg.mp_cooldown):
self._add_mp()
self.last_mp_time = current_time
logger.info(f"[Health Monitor]: Auto MP triggered, MP: {self.mp_ratio*100:.1f}%")
# Sleep to avoid excessive CPU usage
time.sleep(0.05) # Check every 50ms
except Exception as e:
logger.error(f"[Health Monitor]: {e}")
time.sleep(0.1)
def _heal(self):
'''
Execute heal action
'''
try:
self.kb.press_key(self.cfg.heal_key, 0.05)
except Exception as e:
logger.error(f"[Health Monitor]: Heal action failed: {e}")
def _add_mp(self):
'''
Execute MP recovery action
'''
try:
self.kb.press_key(self.cfg.add_mp_key, 0.05)
except Exception as e:
logger.error(f"[Health Monitor]: MP action failed: {e}")
# use 'ctrl', 'alt' for mac, because it's hard to get around
# macOS's security settings
if is_mac():
self.toggle_key = keyboard.Key.ctrl
self.screenshot_key = keyboard.Key.alt
else:
self.toggle_key = keyboard.Key.f1
self.screenshot_key = keyboard.Key.f2
# set up attack key
self.attack_key = ""
if args.attack == "aoe_skill":
self.attack_key = cfg.aoe_skill_key
elif args.attack == "magic_claw":
self.attack_key = cfg.magic_claw_key
else:
logger.error(f"Unexpected attack argument: {args.attack}")
# Start keyboard control thread
threading.Thread(target=self.run, daemon=True).start()
listener = keyboard.Listener(on_press=self.on_press)
listener.start()
def on_press(self, key):
'''
Handle key press events.
'''
try:
# Handle regular character keys
key.char
except AttributeError:
# Handle special keys
if key == self.toggle_key:
if time.time() - self.t_last_toggle > self.debounce_interval:
self.toggle_enable()
self.t_last_toggle = time.time()
elif key == self.screenshot_key:
if time.time() - self.t_last_screenshot > self.debounce_interval:
self.is_need_screen_shot = True
self.t_last_screenshot = time.time()
def toggle_enable(self):
'''
toggle_enable
'''
self.is_enable = not self.is_enable
logger.info(f"Player pressed F1, is_enable:{self.is_enable}")
# Make sure all key are released
self.release_all_key()
def press_key(self, key, duration=0.05):
'''
Simulates a key press for a specified duration
'''
pyautogui.keyDown(key)
time.sleep(duration)
pyautogui.keyUp(key)
def disable(self):
'''
disable keyboard controlller
'''
self.is_enable = False
def enable(self):
'''
enable keyboard controlller
'''
self.is_enable = True
def set_command(self, new_command):
'''
Set keyboard command
'''
self.command = new_command
# logger.info(f"Set command to {new_command}")
def is_game_window_active(self):
'''
Check if the game window is currently the active (foreground) window.
Returns:
- True
- False
'''
if is_mac():
active_window = Quartz.CGWindowListCopyWindowInfo(
Quartz.kCGWindowListOptionOnScreenOnly | Quartz.kCGWindowListExcludeDesktopElements,
Quartz.kCGNullWindowID
)
for window in active_window:
window_name = window.get(Quartz.kCGWindowName, '')
if window_name and self.window_title in window_name:
return True
return False
else:
active_window = gw.getActiveWindow()
return active_window is not None and self.window_title in active_window.title
def release_all_key(self):
'''
Release all key
'''
pyautogui.keyUp("left")
pyautogui.keyUp("right")
pyautogui.keyUp("up")
pyautogui.keyUp("down")
# Also release attack keys to stop any ongoing attacks
pyautogui.keyUp(self.attack_key)
def limit_fps(self):
'''
Limit FPS
'''
# If the loop finished early, sleep to maintain target FPS
target_duration = 1.0 / self.fps_limit # seconds per frame
frame_duration = time.time() - self.t_last_run
if frame_duration < target_duration:
time.sleep(target_duration - frame_duration)
# Update FPS
self.fps = round(1.0 / (time.time() - self.t_last_run))
self.t_last_run = time.time()
# logger.info(f"FPS = {self.fps}")
def run(self):
'''
run
'''
while True:
# Check if game window is active
if not self.is_enable or not self.is_game_window_active():
self.limit_fps()
continue
# Buff skill
# if not self.is_in_buffer_skill_active_duration():
for i, buff_skill_key in enumerate(self.cfg.buff_skill_keys):
cooldown = self.cfg.buff_skill_cooldown[i]
if time.time() - self.t_last_buff_cast[i] >= cooldown and \
time.time() - self.t_last_action > self.cfg.buff_skill_action_cooldown:
self.press_key(buff_skill_key)
logger.info(f"[Buff] Press buff skill key: '{buff_skill_key}' (cooldown: {cooldown}s)")
# Reset timers
self.t_last_buff_cast[i] = time.time()
self.t_last_action = time.time()
break
# check if is needed to release 'Up' key
if time.time() - self.t_last_up > self.cfg.up_drag_duration:
pyautogui.keyUp("up")
# check if is needed to release 'Down' key
if time.time() - self.t_last_down > self.cfg.down_drag_duration:
pyautogui.keyUp("down")
if self.command == "walk left":
pyautogui.keyUp("right")
pyautogui.keyDown("left")
elif self.command == "walk right":
pyautogui.keyUp("left")
pyautogui.keyDown("right")
elif self.command == "jump left":
pyautogui.keyUp("right")
pyautogui.keyDown("left")
self.press_key(self.cfg.jump_key)
pyautogui.keyUp("left")
elif self.command == "jump right":
pyautogui.keyUp("left")
pyautogui.keyDown("right")
self.press_key(self.cfg.jump_key)
pyautogui.keyUp("right")
elif self.command == "jump down":
pyautogui.keyUp("right")
pyautogui.keyUp("left")
pyautogui.keyDown("down")
self.press_key(self.cfg.jump_key)
pyautogui.keyUp("down")
elif self.command == "jump":
pyautogui.keyUp("left")
pyautogui.keyUp("right")
self.press_key(self.cfg.jump_key)
elif self.command == "up":
pyautogui.keyUp("down")
pyautogui.keyDown("up")
self.t_last_up = time.time()
elif self.command == "down":
pyautogui.keyUp("up")
pyautogui.keyDown("down")
self.t_last_down = time.time()
if self.command == "teleport left":
pyautogui.keyUp("right")
pyautogui.keyDown("left")
self.press_key(self.cfg.teleport_key)
elif self.command == "teleport right":
pyautogui.keyUp("left")
pyautogui.keyDown("right")
self.press_key(self.cfg.teleport_key)
elif self.command == "teleport up":
pyautogui.keyDown("up")
self.press_key(self.cfg.teleport_key)
pyautogui.keyUp("up")
elif self.command == "teleport down":
pyautogui.keyDown("down")
self.press_key(self.cfg.teleport_key)
pyautogui.keyUp("down")
elif self.command == "attack":
self.press_key(self.attack_key)
self.t_last_action = time.time()
elif self.command == "attack left":
pyautogui.keyUp("right")
pyautogui.keyDown("left")
time.sleep(self.cfg.character_turn_delay) # Small delay for character to turn
self.press_key(self.attack_key)
pyautogui.keyUp("left")
self.t_last_action = time.time()
elif self.command == "attack right":
pyautogui.keyUp("left")
pyautogui.keyDown("right")
time.sleep(self.cfg.character_turn_delay) # Small delay for character to turn
self.press_key(self.attack_key)
pyautogui.keyUp("right")
self.t_last_action = time.time()
elif self.command == "stop":
self.release_all_key()
self.command = "" # Clear command after stopping
elif self.command == "heal":
self.press_key(self.cfg.heal_key)
self.command = ""
elif self.command == "add mp":
self.press_key(self.cfg.add_mp_key)
self.command = ""
else:
pass
self.limit_fps()
# set up attack key
if cfg.is_use_aoe:
self.attack_key = cfg.aoe_skill_key
else:
self.attack_key = cfg.magic_claw_key
# Start keyboard control thread
threading.Thread(target=self.run, daemon=True).start()
def toggle_enable(self):
'''
toggle_enable
'''
self.is_enable = not self.is_enable
print(f"Player pressed F1, is_enable:{self.is_enable}")
# Make sure all key are released
self.release_all_key()
def press_key(self, key, duration):
'''
Simulates a key press for a specified duration
'''
keyboard.press(key)
time.sleep(duration)
keyboard.release(key)
def disable(self):
'''
disable keyboard controlller
'''
self.is_enable = False
def enable(self):
'''
enable keyboard controlller
'''
self.is_enable = True
def set_command(self, new_command):
'''
Set keyboard command
'''
self.command = new_command
def is_game_window_active(self):
'''
Check if the game window is currently the active (foreground) window.
Returns:
- True
- False
'''
active_window = gw.getActiveWindow()
return active_window is not None and self.window_title in active_window.title
def release_all_key(self):
'''
Release all key
'''
keyboard.release("left")
keyboard.release("right")
keyboard.release("up")
keyboard.release("down")
def run(self):
'''
run
'''
while True:
# Check if F1 key is pressed
if keyboard.is_pressed("F1") and \
time.time() - self.t_last_toggle > self.debounce_interval:
self.toggle_enable()
self.t_last_toggle = time.time()
# Check if F2 key is pressed
if keyboard.is_pressed("F2") and \
time.time() - self.t_last_screenshot > self.debounce_interval:
self.is_need_screen_shot = True
self.t_last_screenshot = time.time()
# Check if game window is active
if not self.is_enable or not self.is_game_window_active():
time.sleep(0.033)
continue
# check if is needed to release 'Up' key
if time.time() - self.t_last_up > self.cfg.up_drag_duration:
keyboard.release("up")
# check if is needed to release 'Down' key
if time.time() - self.t_last_down > self.cfg.down_drag_duration:
keyboard.release("down")
if self.command == "walk left":
keyboard.release("right")
keyboard.press("left")
elif self.command == "walk right":
keyboard.release("left")
keyboard.press("right")
elif self.command == "jump left":
keyboard.release("right")
keyboard.press("left")
self.press_key(self.cfg.jump_key, 0.02)
keyboard.release("left")
elif self.command == "jump right":
keyboard.release("left")
keyboard.press("right")
self.press_key(self.cfg.jump_key, 0.02)
keyboard.release("right")
elif self.command == "jump down":
keyboard.release("right")
keyboard.release("left")
keyboard.press("down")
self.press_key(self.cfg.jump_key, 0.02)
keyboard.release("down")
elif self.command == "jump":
keyboard.release("left")
keyboard.release("right")
self.press_key(self.cfg.jump_key, 0.02)
elif self.command == "up":
keyboard.release("down")
keyboard.press("up")
self.t_last_up = time.time()
elif self.command == "down":
keyboard.release("up")
keyboard.press("down")
self.t_last_down = time.time()
if self.command == "teleport left":
keyboard.release("right")
keyboard.press("left")
self.press_key(self.cfg.teleport_key, 0.02)
elif self.command == "teleport right":
keyboard.release("left")
keyboard.press("right")
self.press_key(self.cfg.teleport_key, 0.02)
elif self.command == "teleport up":
keyboard.press("up")
self.press_key(self.cfg.teleport_key, 0.02)
keyboard.release("up")
elif self.command == "teleport down":
keyboard.press("down")
self.press_key(self.cfg.teleport_key, 0.02)
keyboard.release("down")
elif self.command == "attack":
self.press_key(self.attack_key, 0.02)
elif self.command == "attack left":
keyboard.release("right")
keyboard.press("left")
self.press_key(self.attack_key, 0.02)
keyboard.release("left")
elif self.command == "attack right":
keyboard.release("left")
keyboard.press("right")
self.press_key(self.attack_key, 0.02)
keyboard.release("right")
elif self.command == "stop":
self.release_all_key()
elif self.command == "heal":
self.press_key(self.cfg.heal_key, 0.02)
self.command = ""
elif self.command == "add mp":
self.press_key(self.cfg.add_mp_key, 0.02)
self.command = ""
else:
pass
time.sleep(0.033) # Cap at 30 fps
# Timer
self.t_func_key = [0]*12 # 'F1', 'F2', .... 'F12'
# Keys
self.movement_keys = {
keyboard.Key.up: "up",
keyboard.Key.down: "down",
keyboard.Key.left: "left",
keyboard.Key.right: "right",
keyboard.Key.space: "space"
}
self.func_keys = {
getattr(keyboard.Key, f"f{i+1}"): i for i in range(12)
}
# Start keyboard control thread
threading.Thread(target=self.run, daemon=True).start()
listener = keyboard.Listener(on_press=self.on_press,
on_release=self.on_release)
listener.start()
def on_release(self, key):
'''
Handle key release events and update key_pressing list.
'''
try:
# Regular keys (like 'a', '1', etc.)
k = key.char.lower()
except AttributeError:
k = self.movement_keys.get(key, None)
# Remove the key from key_pressing list if it's in there
if k in self.key_pressing:
self.key_pressing.remove(k)
def on_press(self, key):
'''
Handle key press events.
'''
try:
# Regular character keys (e.g., 'a', 'w', '1')
k = key.char.lower()
except AttributeError:
# Handle F1, F2, F3, ... F12
if key in self.func_keys:
idx = self.func_keys[key]
if time.time() - self.t_func_key[idx] > self.debounce_interval:
self.is_pressed_func_key[idx] = True
self.t_func_key[idx] = time.time()
k = self.movement_keys.get(key, None)
if k and k not in self.key_pressing:
self.key_pressing.append(k)
def toggle_enable(self):
'''
toggle_enable
'''
# self.is_enable = not self.is_enable
logger.info(f"Player pressed F1, is_enable:{self.is_enable}")
def disable(self):
'''
disable keyboard controlller
'''
self.is_enable = False
def enable(self):
'''
enable keyboard controlller
'''
self.is_enable = True
def is_game_window_active(self):
'''
Check if the game window is currently the active (foreground) window.
Returns:
- True
- False
'''
active_window = gw.getActiveWindow()
return active_window is not None and self.window_title in active_window.title
def limit_fps(self):
'''
Limit FPS
'''
# If the loop finished early, sleep to maintain target FPS
target_duration = 1.0 / self.fps_limit # seconds per frame
frame_duration = time.time() - self.t_last_run
if frame_duration < target_duration:
time.sleep(target_duration - frame_duration)
# Update FPS
self.fps = round(1.0 / (time.time() - self.t_last_run))
self.t_last_run = time.time()
# logger.info(f"FPS = {self.fps}")
def run(self):
'''
run
'''
while True:
# Check if game window is active
if not self.is_enable or not self.is_game_window_active():
self.limit_fps()
continue
self.limit_fps()
# Set status to hunting for startup
self.switch_status("hunting")
# Overwrite config.py for macOS
# TODO: move custimized config to config_mac.py
if is_mac():
self.cfg.minimap_upscale_factor = 2 # Mac laptop typically has a smaller screen
self.cfg.game_window_title = 'MapleStory Worlds'
self.cfg.window_size = (776, 1280) # Set resolution to (1280x720) in game setting
self.cfg.monster_health_bar_color = (90, 201, 108) # (B,G,R)
self.cfg.minimap_player_color = (84, 255, 255) # BGR
if args.patrol:
# Patrol mode doesn't need map or route
self.img_map = None
self.img_routes = []
self.img_route_rest = None
else:
# Load map.png from minimaps/
self.img_map = load_image(f"minimaps/{args.map}/map.png",
cv2.IMREAD_COLOR)
# Load route*.png from minimaps/
route_files = sorted(glob.glob(f"minimaps/{args.map}/route*.png"))
route_files = [p for p in route_files if not p.endswith("route_rest.png")]
self.img_routes = [
cv2.cvtColor(load_image(p), cv2.COLOR_BGR2RGB) for p in route_files
]
# Load route_rest.png from minimaps/
self.img_route_rest = cv2.cvtColor(
load_image(f"minimaps/{args.map}/route_rest.png"), cv2.COLOR_BGR2RGB)
# Load player's name tag
self.img_nametag = load_image(f"nametag/{args.nametag}.png")
self.img_nametag_gray = load_image(f"nametag/{args.nametag}.png", cv2.IMREAD_GRAYSCALE)
# Load rune images from rune/
self.img_rune_warning = load_image("rune/rune_warning.png", cv2.IMREAD_GRAYSCALE)
self.img_rune = load_image("rune/rune.png")
self.img_rune_gray = load_image("rune/rune.png", cv2.IMREAD_GRAYSCALE)
self.img_arrows = {
"left":
[load_image("rune/arrow_left_1.png"),
load_image("rune/arrow_left_2.png"),
load_image("rune/arrow_left_3.png"),],
"right":
[load_image("rune/arrow_right_1.png"),
load_image("rune/arrow_right_2.png"),
load_image("rune/arrow_right_3.png"),],
"up":
[load_image("rune/arrow_up_1.png"),
load_image("rune/arrow_up_2.png"),
load_image("rune/arrow_up_3.png")],
"down":
[load_image("rune/arrow_down_1.png"),
load_image("rune/arrow_down_2.png"),
load_image("rune/arrow_down_3.png"),],
}
# Load monsters images from monster/{monster_name}
self.monsters = {}
for monster_name in args.monsters.split(","):
imgs = []
for file in glob.glob(f"monster/{monster_name}/{monster_name}*.png"):
# Add original image
img = load_image(file)
imgs.append((img, get_mask(img, (0, 255, 0))))
# Add flipped image
img_flip = cv2.flip(img, 1)
imgs.append((img_flip, get_mask(img_flip, (0, 255, 0))))
if imgs:
self.monsters[monster_name] = imgs
else:
logger.error(f"No images found in monster/{monster_name}/{monster_name}*")
raise RuntimeError(f"No images found in monster/{monster_name}/{monster_name}*")
logger.info(f"Loaded monsters: {list(self.monsters.keys())}")
# Start keyboard controller thread
self.kb = KeyBoardController(self.cfg, args)
if args.disable_control:
self.kb.disable()
# Start game window capturing thread
logger.info("Waiting for game window to activate, please click on game window")
self.capture = GameWindowCapturor(self.cfg)
# Start health monitoring thread
self.health_monitor = HealthMonitor(self.cfg, args, self.kb)
self.health_monitor.start()
def get_player_location_by_nametag(self):
'''
Detects the player's location based on the nametag position in the game window.
This function works by:
- Extracting a vertical region of interest (ROI) where the nametag is expected.
- Padding the ROI to avoid template matching edge issues.
- Using template matching to locate the nametag, split into left and right halves
to improve robustness against partial occlusion.
- Selecting the best match (left or right) based on score and cache status.
- Computing the player's center position by applying a fixed offset to the nametag.
Returns:
loc_player (tuple): The (x, y) coordinates of the player's estimated location.
'''
# Get camera region in the game window
img_camera = self.img_frame_gray[self.cfg.camera_ceiling:self.cfg.camera_floor, :]
# Get nametag image and search image
if self.cfg.nametag_detection_mode == "white_mask":
# Apply Gaussian blur for smoother white detection
img_camera = cv2.GaussianBlur(img_camera, (3, 3), 0)
img_nametag = cv2.GaussianBlur(self.img_nametag_gray, (3, 3), 0)
lower_white, upper_white = (150, 255)
img_roi = cv2.inRange(img_camera, lower_white, upper_white)
img_nametag = cv2.inRange(img_nametag, lower_white, upper_white)
elif self.cfg.nametag_detection_mode == "grayscale":
img_roi = img_camera
img_nametag = self.img_nametag_gray
else:
logger.error(f"Unsupported nametag detection mode: {self.cfg.nametag_detection_mode}")
return
# cv2.imshow("img_roi", img_roi)
# cv2.imshow("img_nametag", img_nametag)
# Pad search region to deal with fail detection when player is at map edge
(pad_y, pad_x) = self.img_nametag.shape[:2]
img_roi = cv2.copyMakeBorder(
img_roi,
pad_y, pad_y, pad_x, pad_x,
borderType=cv2.BORDER_REPLICATE # replicate border for safe matching
)
# Get last frame name tag location
if self.is_first_frame:
last_result = None
else:
last_result = (
self.loc_nametag[0] + pad_x,
self.loc_nametag[1] - self.cfg.camera_ceiling + pad_y
)
# Get number of splits
h, w = img_nametag.shape
num_splits = max(1, w // self.cfg.nametag_split_width)
w_split = w // num_splits
# Get nametag's background mask
mask = get_mask(self.img_nametag, (0, 255, 0))
# Vertically split the nametag image
nametag_splits = {}
for i in range(num_splits):
x_s = i * w_split
x_e = (i + 1) * w_split if i < num_splits - 1 else w
nametag_splits[f"{i+1}/{num_splits}"] = {
"img": img_nametag[:, x_s:x_e],
"mask": mask[:, x_s:x_e],
"last_result": (
(last_result[0] + x_s, last_result[1]) if last_result else None
),
"score_penalty": 0.0,
"offset_x": x_s
}
# Match tempalte
matches = []
for tag_type, split in nametag_splits.items():
loc, score, is_cached = find_pattern_sqdiff(
img_roi,
split["img"],
last_result=split["last_result"],
mask=split["mask"],
global_threshold=self.cfg.nametag_global_thres
)
w_match = split["img"].shape[1]
h_match = split["img"].shape[0]
score += split["score_penalty"]
matches.append((tag_type, loc, score, w_match, h_match, is_cached, split["offset_x"]))
# Select best match and fix offset:
matches.sort(key=lambda x: (not x[5], x[2])) # prefer cached, then low score
tag_type, loc_nametag, score, w_match, h_match, is_cached, offset_x = matches[0]
# Adjust match location back to full nametag coordinates
loc_nametag = (loc_nametag[0] - offset_x, loc_nametag[1])
loc_nametag = (
loc_nametag[0] - pad_x,
loc_nametag[1] - pad_y + self.cfg.camera_ceiling
)
# Only update nametag location when score is good enough
if score < self.cfg.nametag_diff_thres:
self.loc_nametag = loc_nametag
loc_player = (
self.loc_nametag[0] - self.cfg.nametag_offset[0],
self.loc_nametag[1] - self.cfg.nametag_offset[1]
)
# Draw name tag detection box for debugging
draw_rectangle(self.img_frame_debug, self.loc_nametag,
self.img_nametag.shape, (0, 255, 0), "")
text = f"NameTag,{round(score, 2)}," + \
f"{'cached' if is_cached else 'missed'}," + \
f"{tag_type}"
cv2.putText(self.img_frame_debug, text,
(self.loc_nametag[0],
self.loc_nametag[1] + self.img_nametag.shape[0] + 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
# Draw player center for debugging
cv2.circle(self.img_frame_debug,
loc_player, radius=3,
color=(0, 0, 255), thickness=-1)
return loc_player
def get_player_location_on_global_map(self):
'''
get_player_location_on_global_map
'''
self.loc_minimap_global, score, _ = find_pattern_sqdiff(
self.img_map,
self.img_minimap)
loc_player_global = (
self.loc_minimap_global[0] + self.loc_player_minimap[0],
self.loc_minimap_global[1] + self.loc_player_minimap[1]
)
# Draw local minimap rectangle
camera_bottom_right = (
self.loc_minimap_global[0] + self.img_minimap.shape[1],
self.loc_minimap_global[1] + self.img_minimap.shape[0]
)
cv2.rectangle(self.img_route_debug, self.loc_minimap_global,
camera_bottom_right, (0, 255, 255), 1)
cv2.putText(
self.img_route_debug,
f"Minimap,score({round(score, 2)})",
(self.loc_minimap_global[0], self.loc_minimap_global[1]+15),
cv2.FONT_HERSHEY_SIMPLEX, 0.4,
(0, 255, 255), 1
)
# Draw player center
cv2.circle(self.img_route_debug,
loc_player_global, radius=2,
color=(0, 255, 255), thickness=-1)
return loc_player_global
def get_nearest_color_code(self):
'''
Searches for the nearest color-coded action marker
around the player on the route map.
This function:
- Scans each pixel in the search box to find nearest color code
- Tracks the closest matching pixel using Manhattan distance (|dx| + |dy|).
- Returns a dictionary containing the nearest matching
pixel's position, color, action label, and distance.
Returns:
dict or None: Dictionary containing:
- "pixel": (x, y) coordinate of the matched pixel
- "color": matched RGB color tuple
- "action": corresponding action string from config
- "distance": Manhattan distance from player
Returns None if no matching color is found within the region.
'''
x0, y0 = self.loc_player_global
h, w = self.img_route.shape[:2]
x_min = max(0, x0 - self.cfg.color_code_search_range)
x_max = min(w, x0 + self.cfg.color_code_search_range)
y_min = max(0, y0 - self.cfg.color_code_search_range)
y_max = min(h, y0 + self.cfg.color_code_search_range)
nearest = None
min_dist = float('inf')
for y in range(y_min, y_max):
for x in range(x_min, x_max):
pixel = tuple(self.img_route[y, x]) # (R, G, B)
if pixel in self.cfg.color_code:
dist = abs(x - x0) + abs(y - y0)
if dist < min_dist:
min_dist = dist
nearest = {
"pixel": (x, y),
"color": pixel,
"action": self.cfg.color_code[pixel],
"distance": dist
}
# Debug
draw_rectangle(
self.img_route_debug,
(x_min, y_min),
(self.cfg.color_code_search_range*2,
self.cfg.color_code_search_range*2),
(0, 0, 255), "", text_height=0.4, thickness=1,
)
# Draw a straigt line from map_loc_player to color_code["pixel"]
if nearest is not None:
cv2.line(
self.img_route_debug,
self.loc_player_global, # start point
nearest["pixel"], # end point
(0, 255, 0), # green line
1 # thickness
)
# Print color code on debug image
cv2.putText(
self.img_frame_debug, f"Route Action: {nearest['action']}",
(720, 90),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
cv2.putText(
self.img_frame_debug, f"Route Index: {self.idx_routes}",
(720, 120),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
return nearest # if not found return none
def get_nearest_monster(self, is_left = True, overlap_threshold=0.5):
'''
Finds the nearest monster within the player's attack range.
This function:
- Defines an attack box relative to the player position,
depending on the facing direction (`is_left`).
- Iterates through all detected monsters and checks which ones overlap
with the attack box.
- Returns the closest valid monster that meets the overlap criteria.
Args:
is_left (bool): If True, assume the player is facing left;
adjusts attack box accordingly.
overlap_threshold (float): Minimum IoU area ratio required to consider a hit.
Returns:
dict or None: The nearest monster's info dict, or None if no valid match.
'''
# Get attack box
if self.args.attack == "aoe_skill":
dx = self.cfg.aoe_skill_range_x // 2
dy = self.cfg.aoe_skill_range_y // 2
x0 = max(0, self.loc_player[0] - dx)
x1 = min(self.img_frame.shape[1], self.loc_player[0] + dx)
y0 = max(0, self.loc_player[1] - dy)
y1 = min(self.img_frame.shape[0], self.loc_player[1] + dy)
elif self.args.attack == "magic_claw":
if is_left:
x0 = self.loc_player[0] - self.cfg.magic_claw_range_x
x1 = self.loc_player[0]
else:
x0 = self.loc_player[0]
x1 = x0 + self.cfg.magic_claw_range_x
y0 = self.loc_player[1] - self.cfg.magic_claw_range_y//2
y1 = y0 + self.cfg.magic_claw_range_y
else:
logger.error(f"Unsupported attack mode: {self.args.attack}")
return None
# Draw attack box on debug window
draw_rectangle(
self.img_frame_debug, (x0, y0),
(y1-y0, x1-x0),
(0, 0, 255), "Attack Box"
)
nearest_monster = None
min_distance = float('inf')
for monster in self.monster_info:
mx1, my1 = monster["position"]
mw, mh = monster["size"]
mx2 = mx1 + mw
my2 = my1 + mh
# Calculate intersection
ix1 = max(x0, mx1)
iy1 = max(y0, my1)
ix2 = min(x1, mx2)
iy2 = min(y1, my2)
iw = max(0, ix2 - ix1)
ih = max(0, iy2 - iy1)
inter_area = iw * ih
monster_area = mw * mh
if monster_area == 0:
continue # skip degenerate box
if inter_area/monster_area >= overlap_threshold:
# Compute distance to player center
monster_center = (mx1 + mw // 2, my1 + mh // 2)
dx = monster_center[0] - self.loc_player[0]
dy = monster_center[1] - self.loc_player[1]
distance = abs(dx) + abs(dy) # Manhattan distance
if distance < min_distance:
min_distance = distance
nearest_monster = monster
return nearest_monster
def get_monsters_in_range(self, top_left, bottom_right):
'''
get_monsters_in_range
'''
x0, y0 = top_left
x1, y1 = bottom_right
img_roi = self.img_frame[y0:y1, x0:x1]
monster_info = []
for monster_name, monster_imgs in self.monsters.items():
for img_monster, mask_monster in monster_imgs:
if self.args.patrol:
pass # Don't detect monster using template in patrol mode
elif self.cfg.monster_detect_mode == "template_free":
# Generate mask where pixel is exactly (0,0,0)
black_mask = np.all(img_roi == [0, 0, 0], axis=2).astype(np.uint8) * 255
cv2.imshow("Black Pixel Mask", black_mask)
# Shift player's location into ROI coordinate system
px, py = self.loc_player
px_in_roi = px - x0
py_in_roi = py - y0
# Define rectangle range around player (in ROI coordinate)
char_x_min = max(0, px_in_roi - self.cfg.character_width // 2)
char_x_max = min(img_roi.shape[1], px_in_roi + self.cfg.character_width // 2)
char_y_min = max(0, py_in_roi - self.cfg.character_height // 2)
char_y_max = min(img_roi.shape[0], py_in_roi + self.cfg.character_height // 2)
# Zero out mask inside this region (ignore player's own character)
black_mask[char_y_min:char_y_max, char_x_min:char_x_max] = 0
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (20, 20))
closed_mask = cv2.morphologyEx(black_mask, cv2.MORPH_CLOSE, kernel)
# cv2.imshow("Black Mask", closed_mask)
# draw player character bounding box
draw_rectangle(
self.img_frame_debug, (char_x_min+x0, char_y_min+y0),
(self.cfg.character_height, self.cfg.character_width),
(255, 0, 0), "Character Box"
)
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(closed_mask, connectivity=8)
monster_info = []
min_area = 1000
for i in range(1, num_labels):
x, y, w, h, area = stats[i]
if area > min_area:
monster_info.append({
"name": "",
"position": (x0+x, y0+y),
"size": (h, w),
"score": 1.0,
})
elif self.cfg.monster_detect_mode == "contour_only":
# Use only black lines contour to detect monsters
# Create masks (already grayscale)
mask_pattern = np.all(img_monster == [0, 0, 0], axis=2).astype(np.uint8) * 255
mask_roi = np.all(img_roi == [0, 0, 0], axis=2).astype(np.uint8) * 255
# Apply Gaussian blur (soften the masks)
img_monster_blur = cv2.GaussianBlur(mask_pattern, (self.cfg.blur_range, self.cfg.blur_range), 0)
img_roi_blur = cv2.GaussianBlur(mask_roi, (self.cfg.blur_range, self.cfg.blur_range), 0)
# Check template vs ROI size before matching
h_roi, w_roi = img_roi_blur.shape[:2]
h_temp, w_temp = img_monster_blur.shape[:2]
if h_temp > h_roi or w_temp > w_roi:
return [] # template bigger than roi, skip this matching
# Perform template matching
res = cv2.matchTemplate(img_roi_blur, img_monster_blur, cv2.TM_SQDIFF_NORMED)
# Apply soft threshold
match_locations = np.where(res <= self.cfg.monster_diff_thres)
h, w = img_monster.shape[:2]
for pt in zip(*match_locations[::-1]):
monster_info.append({
"name": monster_name,
"position": (pt[0] + x0, pt[1] + y0),
"size": (h, w),
"score": res[pt[1], pt[0]],
})
elif self.cfg.monster_detect_mode == "grayscale":
img_monster_gray = cv2.cvtColor(img_monster, cv2.COLOR_BGR2GRAY)
img_roi_gray = cv2.cvtColor(img_roi, cv2.COLOR_BGR2GRAY)
res = cv2.matchTemplate(
img_roi_gray,
img_monster_gray,
cv2.TM_SQDIFF_NORMED,
mask=mask_monster)
match_locations = np.where(res <= self.cfg.monster_diff_thres)
h, w = img_monster.shape[:2]
for pt in zip(*match_locations[::-1]):
monster_info.append({
"name": monster_name,
"position": (pt[0] + x0, pt[1] + y0),
"size": (h, w),
"score": res[pt[1], pt[0]],
})
elif self.cfg.monster_detect_mode == "color":
res = cv2.matchTemplate(
img_roi,
img_monster,
cv2.TM_SQDIFF_NORMED,
mask=mask_monster)
match_locations = np.where(res <= self.cfg.monster_diff_thres)
h, w = img_monster.shape[:2]
for pt in zip(*match_locations[::-1]):
monster_info.append({
"name": monster_name,
"position": (pt[0] + x0, pt[1] + y0),
"size": (h, w),
"score": res[pt[1], pt[0]],
})
else:
logger.error(f"Unexpected camera localization mode: {self.cfg.monster_detect_mode}")
return []
# Apply Non-Maximum Suppression to monster detection
monster_info = nms(monster_info, iou_threshold=0.4)
# Detect monster via health bar
if self.cfg.monster_detect_with_health_bar:
# Create color mask for Monsters' HP bar
mask = cv2.inRange(img_roi,
np.array(self.cfg.monster_health_bar_color),
np.array(self.cfg.monster_health_bar_color))
# Find connected components (each cluster of green pixels)
num_labels, labels, stats, centroids = \
cv2.connectedComponentsWithStats(mask, connectivity=8)
for i in range(1, num_labels): # skip background (label 0)
x, y, w, h, area = stats[i]
if area < 3: # small noise filter
continue
# Guess a monster bounding box
y += 10
x = max(0, x)
y = max(0, y)
w = 70
h = 70
monster_info.append({
"name": "Health Bar",
"position": (x0 + x, y0 + y),
"size": (h, w),
"score": 1.0,
})
# Debug
# Draw attack detection range
draw_rectangle(
self.img_frame_debug, (x0, y0), (y1-y0, x1-x0),
(255, 0, 0), "Monster Detection Box"
)
# Draw monsters bounding box
for monster in monster_info:
if monster["name"] == "Health Bar":
color = (0, 255, 255)
else:
color = (0, 255, 0)
draw_rectangle(
self.img_frame_debug, monster["position"], monster["size"],
color, str(round(monster['score'], 2))
)
return monster_info
def switch_status(self, new_status):
'''
Switch to new status and log the transition.
Parameters:
- new_status: string, the new status to switch to.
'''
# Ignore dummy transition
if self.status == new_status:
return
t_elapsed = round(time.time() - self.t_last_switch_status)
logger.info(f"[switch_status] From {self.status}({t_elapsed} sec) to {new_status}.")
self.status = new_status
self.t_last_switch_status = time.time()
def solve_rune(self):
'''
Automatically solves the rune puzzle mini-game by recognizing directional arrows
on the screen and simulating the correct key presses.
This function:
- Continuously checks whether the rune game is active.
- For each of the 4 arrows:
- Compares the cropped image with all known arrow templates.
- Selects the best-matching arrow direction.
- Simulates a key press corresponding to the detected arrow direction.
- Repeats until the rune game ends.
Note:
- Skips key press simulation if `--disable_control` flag is set.
Returns:
None
'''
while self.is_in_rune_game():
for arrow_idx in [0,1,2,3]:
# Get lastest game screen frame buffer
self.frame = self.capture.get_frame()
# Resize game screen to 1296x759
self.img_frame = cv2.resize(self.frame, (1296, 759),
interpolation=cv2.INTER_NEAREST)
# Crop arrow detection box
x = self.cfg.arrow_box_start_point[0] + self.cfg.arrow_box_interval*arrow_idx
y = self.cfg.arrow_box_start_point[1]
size = self.cfg.arrow_box_size
img_roi = self.img_frame[y:y+size, x:x+size]
# Loop through all possible arrows template and choose the most possible one
best_score = float('inf')
best_direction = ""
for direction, arrow_list in self.img_arrows.items():
for img_arrow in arrow_list:
_, score, _ = find_pattern_sqdiff(
img_roi, img_arrow,
mask=get_mask(img_arrow, (0, 255, 0)))
if score < best_score:
best_score = score
best_direction = direction
logger.info(f"[solve_rune] Arrow({arrow_idx}) is {best_direction} with score({best_score})")
# Update img_frame_debug
self.img_frame_debug = self.img_frame.copy()
draw_rectangle(
self.img_frame_debug, (x, y), (size, size),
(0, 0, 255), str(round(best_score, 2))
)
# Update debug window
self.update_img_frame_debug()
cv2.waitKey(1)
# For logging
screenshot(self.img_frame_debug, "solve_rune")
# Press the key for 0.5 second
if not self.args.disable_control:
self.kb.press_key(best_direction, 0.5)
time.sleep(1)
logger.info(f"[solve_rune] Solved all arrows")
def is_player_stuck(self):
"""
Checks whether the player is stuck (not moving)
based on their global position on map.
This function:
- Compares the player's current position with their last known position
tracked by the watchdog.
- If the player has moved beyond a threshold (`watch_dog_range`),
it resets the watchdog timer.
- If the player hasn't moved and the elapsed time exceeds (`watch_dog_timeout`),
it flags the player as stuck and resets the watchdog.
Returns:
bool: True if the player is stuck, False otherwise.
"""
dx = abs(self.loc_player_global[0] - self.loc_watch_dog[0])
dy = abs(self.loc_player_global[1] - self.loc_watch_dog[1])
current_time = time.time()
if dx + dy > self.cfg.watch_dog_range:
# Player moved, reset watchdog timer
self.loc_watch_dog = self.loc_player_global
self.t_watch_dog = current_time
return False
dt = current_time - self.t_watch_dog
if dt > self.cfg.watch_dog_timeout:
# watch dog idle for too long, player stuck
self.loc_watch_dog = self.loc_player_global
self.t_watch_dog = current_time
logger.warning(f"[is_player_stuck] Player stuck for {dt} seconds.")
return True
return False
def is_rune_warning(self):
'''
Checks whether the rune warning icon is appear on the game frame.
This function:
- Crops a specific region where the rune warning icon is expected.
- Compare the cropped region against the known rune warning image template.
- Returns True if rune warning template matched
Returns:
bool: True if the rune warning is detected, False otherwise.
'''
x0, y0 = self.cfg.rune_warning_top_left
x1, y1 = self.cfg.rune_warning_bottom_right
_, score, _ = find_pattern_sqdiff(
self.img_frame_gray[y0:y1, x0:x1],
self.img_rune_warning)
if self.status == "hunting" and score < self.cfg.rune_warning_diff_thres:
logger.info(f"[is_rune_warning] Detect rune warning on screen with score({score})")
return True
else:
return False
def is_rune_near_player(self):
'''
Checks if a rune icon is visible around the player's position.
This function:
- Uses template matching to detect the rune icon within this predefine box.
- Dynamically adjusts the detection threshold based on the rune detection level.
Returns:
bool: True if a rune is found near the player, False otherwise.
'''
# Calculate bounding box
h, w = self.img_frame.shape[:2]
x0 = max(0, self.loc_player[0] - self.cfg.rune_detect_box_width // 2)
y0 = max(0, self.loc_player[1] - self.cfg.rune_detect_box_height)
x1 = min(w, self.loc_player[0] + self.cfg.rune_detect_box_width // 2)
y1 = min(h, self.loc_player[1])
# Debug
draw_rectangle(
self.img_frame_debug, (x0, y0), (y1-y0, x1-x0),
(255, 0, 0), "Rune Detection Range"
)
# Find rune icon near player
if (x1 - x0) < self.img_rune.shape[1] or \
(y1 - y0) < self.img_rune.shape[0]:
return False # Skip check if box is out of range
else:
img_roi = self.img_frame[y0:y1, x0:x1]
loc_rune, score, _ = find_pattern_sqdiff(
img_roi,
self.img_rune,
mask=get_mask(self.img_rune, (0, 255, 0)))
# # Draw rectangle for debug
# draw_rectangle(
# self.img_frame_debug,
# (x0 + loc_rune[0], y0 + loc_rune[1]),
# self.img_rune.shape,
# (255, 0, 255), # purple in BGR
# f"Rune,{round(score, 2)}"
# )
detect_thres = self.cfg.rune_detect_diff_thres + self.rune_detect_level*self.cfg.rune_detect_level_coef
if score < detect_thres:
logger.info(f"[Rune Detect] Found rune near player with score({score})," + \
f"level({self.rune_detect_level}),threshold({detect_thres})")
# Draw rectangle for debug
draw_rectangle(
self.img_frame_debug,
(x0 + loc_rune[0], y0 + loc_rune[1]),
self.img_rune.shape,
(255, 0, 255), # purple in BGR
f"Rune,{round(score, 2)}"
)
screenshot(self.img_frame_debug, "rune_detected")
return True
else:
return False
def is_in_rune_game(self):
'''
Determines whether the rune puzzle game screen is currently active.
This function:
- Extracts the RoI where the first arrow of the rune puzzle appears.
- Performs masked template matching with all known arrow templates.
- Computes the best matching score across all arrow directions.
- If the best match score is below a threshold,
the rune puzzle is considered active.
Returns:
bool: True if the rune game is detected on screen, False otherwise.
'''
# Get lastest game screen frame buffer
self.frame = self.capture.get_frame()
# Resize game screen to 1296x759
self.img_frame = cv2.resize(self.frame, (1296, 759), interpolation=cv2.INTER_NEAREST)
# Crop arrow detection box
x, y = self.cfg.arrow_box_start_point
size = self.cfg.arrow_box_size
img_roi = self.img_frame[y:y+size, x:x+size]
# Check if arrow exist on screen
best_score = float('inf')
for direc, arrow_list in self.img_arrows.items():
for img_arrow in arrow_list:
_, score, _ = find_pattern_sqdiff(
img_roi, img_arrow,
mask=get_mask(img_arrow, (0, 255, 0)))
if score < best_score:
best_score = score
draw_rectangle(
self.img_frame_debug, (x, y), (size, size),
(0, 0, 255), str(round(best_score, 2))
)
if best_score < self.cfg.arrow_box_diff_thres:
logger.info(f"Arrow screen detected with score({score})")
return True
return False
def is_near_edge(self):
'''
Detects whether the player is near a teleport edge region
This function:
- Defines a rectangular search region around the player's current global location.
- Scans for pixels matching a specific edge teleport color code within the region.
- If matching pixels are found, it computes the average X position of those pixels.
- Compares that average to the player's X position to determine whether the edge is on the left or right.
Returns:
str: One of:
- "edge on left"
- "edge on right"
- "" (empty string if no edge is detected nearby)
'''
x0, y0 = self.loc_player_global
h, w = self.img_route.shape[:2]
x_min = max(0, x0 - self.cfg.edge_teleport_box_width//2)
x_max = min(w, x0 + self.cfg.edge_teleport_box_width//2)
y_min = max(0, y0 - self.cfg.edge_teleport_box_height//2)
y_max = min(h, y0 + self.cfg.edge_teleport_box_height//2)
# Debug: draw search box
# draw_rectangle(
# self.img_route_debug,
# (x_min, y_min),
# (y_max - y_min, x_max - x_min),
# (0, 0, 255), "Edge Check", thickness=1, text_height=0.4
# )
# Find mask of matching pixels
roi = self.img_route[y_min:y_max, x_min:x_max]
mask = np.all(roi == self.cfg.edge_teleport_color_code, axis=2)
coords = np.column_stack(np.where(mask))
# No edge pixel
if coords.size == 0:
return ""
# Calculate mean position of matching pixels
mean_x = np.mean(coords[:, 1])
# Compare to roi center
if mean_x < x0:
return "edge on left"
else:
return "edge on right"
def get_random_action(self):
'''
get_random_action
'''
action = random.choice(list(self.cfg.color_code.values()))
logger.warning(f"Perform random action: {action}")
return action
def update_info_on_img_frame_debug(self):
'''
update_info_on_img_frame_debug
'''
# Print text at bottom left corner
self.fps = round(1.0 / (time.time() - self.t_last_frame))
text_y_interval = 23
text_y_start = 550
dt_screenshot = time.time() - self.kb.t_last_screenshot
text_list = [
f"FPS: {self.fps}",
f"Status: {self.status}",
f"Resolution: {self.frame.shape[0]}x{self.frame.shape[1]}",
f"Press 'F1' to {'pause' if self.kb.is_enable else 'start'} Bot",
f"Press 'F2' to save screenshot{' : Saved' if dt_screenshot < 0.7 else ''}"]
for idx, text in enumerate(text_list):
cv2.putText(
self.img_frame_debug, text,
(10, text_y_start + text_y_interval*idx),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
# Draw minimap rectangle on img debug
draw_rectangle(
self.img_frame_debug,
self.loc_minimap,
self.img_minimap.shape[:2],
(0, 0, 255), "minimap",thickness=2
)
# Don't draw minimap in patrol mode
if self.args.patrol:
return
# Compute crop region with boundary check
crop_w, crop_h = 80, 80
x0 = max(0, self.loc_player_global[0] - crop_w // 2)
y0 = max(0, self.loc_player_global[1] - crop_h // 2)
x1 = min(self.img_route_debug.shape[1], x0 + crop_w)
y1 = min(self.img_route_debug.shape[0], y0 + crop_h)
# Check if valid crop region
if x1 <= x0 or y1 <= y0:
return
# Crop region
mini_map_crop = self.img_route_debug[y0:y1, x0:x1]
mini_map_crop = cv2.resize(mini_map_crop,
(int(mini_map_crop.shape[1] * 3),
int(mini_map_crop.shape[0] * 3)),
interpolation=cv2.INTER_NEAREST)
# Paste into top-right corner of self.img_frame_debug
h_crop, w_crop = mini_map_crop.shape[:2]
h_frame, w_frame = self.img_frame_debug.shape[:2]
x_paste = w_frame - w_crop - 10 # 10px margin from right
y_paste = 70
self.img_frame_debug[y_paste:y_paste + h_crop, x_paste:x_paste + w_crop] = mini_map_crop
# Draw border around minimap
cv2.rectangle(
self.img_frame_debug,
(x_paste, y_paste),
(x_paste + w_crop, y_paste + h_crop),
color=(255, 255, 255), # White border
thickness=2
)
def update_img_frame_debug(self):
'''
update_img_frame_debug
'''
cv2.imshow("Game Window Debug",
self.img_frame_debug[self.cfg.camera_ceiling:self.cfg.camera_floor, :])
# Update FPS timer
self.t_last_frame = time.time()
def run_once(self):
'''
Process one game window frame
'''
# Get window game raw frame
self.frame = self.capture.get_frame()
if self.frame is None:
logger.warning("Failed to capture game frame.")
return
# Make sure resolution is as expected
if self.cfg.window_size != self.frame.shape[:2]:
text = f"Unexpeted window size: {self.frame.shape[:2]} (expect {self.cfg.window_size})"
logger.error(text)
return
# Resize raw frame to (1296, 759)
self.img_frame = cv2.resize(self.frame, (1296, 759),
interpolation=cv2.INTER_NEAREST)
# Get minimap coordinate and size on game window
minimap_result = get_minimap_loc_size(self.img_frame)
if minimap_result is None:
logger.warning("Failed to get minimap location and size.")
else:
x, y, w, h = minimap_result
self.loc_minimap = (x, y)
self.img_minimap = self.img_frame[y:y+h, x:x+w]
# Grayscale game window
self.img_frame_gray = cv2.cvtColor(self.img_frame, cv2.COLOR_BGR2GRAY)
# Image for debug use
self.img_frame_debug = self.img_frame.copy()
# Get current route image
if not self.args.patrol:
self.img_route = self.img_routes[self.idx_routes]
self.img_route_debug = cv2.cvtColor(self.img_route, cv2.COLOR_RGB2BGR)
# Update health monitor with current frame
self.health_monitor.update_frame(self.img_frame[self.cfg.camera_floor:, :])
# Draw HP/MP/EXP bar on debug window
ratio_bars = [self.health_monitor.hp_ratio,
self.health_monitor.mp_ratio,
self.health_monitor.exp_ratio]
for i, bar_name in enumerate(["HP", "MP", "EXP"]):
x_s, y_s = (250, 90)
# Print bar ratio on debug window
cv2.putText(self.img_frame_debug,
f"{bar_name}: {ratio_bars[i]*100:.1f}%",
(x_s, y_s + 30*i),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 2)
# Draw bar on debug window
x_s, y_s = (410, 73)
# print(self.health_monitor.loc_size_bars)
x, y, w, h = self.health_monitor.loc_size_bars[i]
self.img_frame_debug[y_s+30*i:y_s+h+30*i, x_s:x_s+w] = \
self.img_frame[self.cfg.camera_floor:, :][y:y+h, x:x+w]
# Check whether "PLease remove runes" warning appears on screen
if self.is_rune_warning():
self.rune_detect_level = 0
self.switch_status("finding_rune") # Stop hunting and start find runes
# Get player location in game window
self.loc_player = self.get_player_location_by_nametag()
# Get player location on minimap
loc_player_minimap = get_player_location_on_minimap(
self.img_minimap,
minimap_player_color=self.cfg.minimap_player_color)
if loc_player_minimap:
self.loc_player_minimap = loc_player_minimap
# Get player location on global map
if self.args.patrol:
self.loc_player_global = self.loc_player_minimap
else:
self.loc_player_global = self.get_player_location_on_global_map()
# Check whether a rune icon is near player
if self.is_rune_near_player():
self.switch_status("near_rune")
# Check whether we entered the rune mini-game
if self.status == "near_rune":
self.kb.set_command("stop") # stop character
time.sleep(0.1) # Wait for character to stop
self.kb.disable() # Disable kb thread during rune solving
# Attempt to trigger rune
if not self.args.disable_control:
self.kb.press_key("up", 0.02)
time.sleep(1) # Wait for rune game to pop up
# If entered the game, start solving rune
if self.is_in_rune_game():
self.solve_rune() # Blocking until runes solved
self.rune_detect_level = 0 # reset rune detect level
self.switch_status("hunting")
# Restore kb thread
self.kb.enable()
# Get monster search box
margin = self.cfg.monster_search_margin
if self.args.attack == "aoe_skill":
dx = self.cfg.aoe_skill_range_x // 2 + margin
dy = self.cfg.aoe_skill_range_y // 2 + margin
elif self.args.attack == "magic_claw":
dx = self.cfg.magic_claw_range_x + margin
dy = self.cfg.magic_claw_range_y + margin
else:
logger.error(f"Unsupported attack mode: {self.args.attack}")
return
x0 = max(0, self.loc_player[0] - dx)
x1 = min(self.img_frame.shape[1], self.loc_player[0] + dx)
y0 = max(0, self.loc_player[1] - dy)
y1 = min(self.img_frame.shape[0], self.loc_player[1] + dy)
# Get monsters in the search box
self.monster_info = self.get_monsters_in_range((x0, y0), (x1, y1))
# Get attack direction
if self.args.attack == "aoe_skill":
if len(self.monster_info) == 0:
attack_direction = None
else:
attack_direction = "I don't care"
nearest_monster = self.get_nearest_monster()
elif self.args.attack == "magic_claw":
# Get nearest monster to player
monster_left = self.get_nearest_monster(is_left = True)
monster_right = self.get_nearest_monster(is_left = False)
# Compute distance for left
distance_left = float('inf')
if monster_left is not None:
mx, my = monster_left["position"]
mw, mh = monster_left["size"]
center_left = (mx + mw // 2, my + mh // 2)
distance_left = abs(center_left[0] - self.loc_player[0]) + \
abs(center_left[1] - self.loc_player[1])
# Compute distance for right
distance_right = float('inf')
if monster_right is not None:
mx, my = monster_right["position"]
mw, mh = monster_right["size"]
center_right = (mx + mw // 2, my + mh // 2)
distance_right = abs(center_right[0] - self.loc_player[0]) + \
abs(center_right[1] - self.loc_player[1])
# Choose attack direction and nearest monster
attack_direction = None
nearest_monster = None
# Additional validation: check if monster is actually on the correct side
def is_monster_on_correct_side(monster, direction):
if monster is None:
return False
mx, my = monster["position"]
mw, mh = monster["size"]
monster_center_x = mx + mw // 2
player_x = self.loc_player[0]
if direction == "left":
return monster_center_x < player_x # Monster should be left of player
else: # direction == "right"
return monster_center_x > player_x # Monster should be right of player
# Only choose direction if there's a clear winner and monster is on correct side
if monster_left is not None and monster_right is None and is_monster_on_correct_side(monster_left, "left"):
attack_direction = "left"
nearest_monster = monster_left
elif monster_right is not None and monster_left is None and is_monster_on_correct_side(monster_right, "right"):
attack_direction = "right"
nearest_monster = monster_right
elif monster_left is not None and monster_right is not None:
# Both sides have monsters, check distance and side validation
left_valid = is_monster_on_correct_side(monster_left, "left")
right_valid = is_monster_on_correct_side(monster_right, "right")
if left_valid and not right_valid:
attack_direction = "left"
nearest_monster = monster_left
elif right_valid and not left_valid:
attack_direction = "right"
nearest_monster = monster_right
elif left_valid and right_valid and distance_left < distance_right - 50:
attack_direction = "left"
nearest_monster = monster_left
elif left_valid and right_valid and distance_right < distance_left - 50:
attack_direction = "right"
nearest_monster = monster_right
# If both valid but distances too close, don't attack to avoid confusion
# Debug attack direction selection
if monster_left is not None or monster_right is not None:
left_side_ok = is_monster_on_correct_side(monster_left, "left") if monster_left else False
right_side_ok = is_monster_on_correct_side(monster_right, "right") if monster_right else False
debug_text = f"L:{distance_left:.0f}({left_side_ok}) R:{distance_right:.0f}({right_side_ok}) Dir:{attack_direction}"
cv2.putText(self.img_frame_debug, debug_text,
(10, 450), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 2)
command = ""
if self.args.patrol:
x, y = self.loc_player
h, w = self.img_frame.shape[:2]
loc_player_ratio = float(x)/float(w)
left_ratio, right_ratio = self.cfg.patrol_range
# Check if we need to change patrol direction
if self.is_patrol_to_left and loc_player_ratio < left_ratio:
self.patrol_turn_point_cnt += 1
elif (not self.is_patrol_to_left) and loc_player_ratio > right_ratio:
self.patrol_turn_point_cnt += 1
if self.patrol_turn_point_cnt > self.cfg.turn_point_thres:
self.is_patrol_to_left = not self.is_patrol_to_left
self.patrol_turn_point_cnt = 0
# Set command for patrol mode
# Use proper attack range checking instead of just checking if monsters exist
if (time.time() - self.t_patrol_last_attack > self.cfg.patrol_attack_interval and
len(self.monster_info) > 0 and nearest_monster is not None):
# Check if monster is actually in attack range
if attack_direction == "I don't care" or attack_direction == "left" or attack_direction == "right":
command = "attack"
self.t_patrol_last_attack = time.time()
elif self.is_patrol_to_left:
command = "walk left"
else:
command = "walk right"
else:
# get color code from img_route
color_code = self.get_nearest_color_code()
if color_code:
if color_code["action"] == "goal":
# Switch to next route map
self.idx_routes = (self.idx_routes+1)%len(self.img_routes)
logger.debug(f"Change to new route:{self.idx_routes}")
command = color_code["action"]
# teleport away from edge to avoid falling off cliff
if self.is_near_edge() and \
time.time() - self.t_last_teleport > self.cfg.teleport_cooldown:
command = command.replace("walk", "teleport")
self.t_last_teleport = time.time() # update timer
if self.cfg.teleport_key == "": # disable teleport skill
command = command.replace("teleport", "jump")
# Special logic for each status, overwrite color code action
if self.status == "hunting":
# Perform a random action when player stuck
if not self.args.patrol and self.is_player_stuck():
command = self.get_random_action()
elif command in ["up", "down", "jump right", "jump left"]:
pass # Don't attack or heal while character is on rope or jumping
# Note: HP/MP monitoring is now handled by separate HealthMonitor thread
elif attack_direction == "I don't care" and nearest_monster is not None and \
time.time() - self.t_last_attack > self.cfg.attack_cooldown:
command = "attack"
self.t_last_attack = time.time()
elif attack_direction == "left" and nearest_monster is not None and \
time.time() - self.t_last_attack > self.cfg.attack_cooldown:
command = "attack left"
self.t_last_attack = time.time()
elif attack_direction == "right" and nearest_monster is not None and \
time.time() - self.t_last_attack > self.cfg.attack_cooldown:
command = "attack right"
self.t_last_attack = time.time()
elif self.status == "finding_rune":
if self.is_player_stuck():
command = self.get_random_action()
# Check if finding rune timeout
if time.time() - self.t_last_switch_status > self.cfg.rune_finding_timeout:
self.rune_detect_level = 0 # reset level
self.switch_status("resting")
# Check if need to raise level to lower the detection threshold
dt = int(time.time() - self.t_last_switch_status)
self.rune_detect_level = dt // self.cfg.rune_detect_level_raise_interval
elif self.status == "near_rune":
# Stay in near_rune status for only a few seconds
if time.time() - self.t_last_switch_status > self.cfg.near_rune_duration:
self.switch_status("hunting")
elif self.status == "resting":
self.img_routes = [self.img_route_rest] # Set up resting route
self.idx_routes = 0
else:
logger.error(f"Unknown status: {self.status}")
# send command to keyboard controller
self.kb.set_command(command)
# Debug: show current command on screen
if command and len(command) > 0:
cv2.putText(self.img_frame_debug, f"CMD: {command}",
(10, 480), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
# Check if need to save screenshot
if self.kb.is_need_screen_shot:
screenshot(self.img_frame)
self.kb.is_need_screen_shot = False
# Enable cached location since second frame
self.is_first_frame = False
#####################
### Debug Windows ###
#####################
# Don't show debug window to save system resource
if not self.cfg.show_debug_window:
return
# Print text on debug image
self.update_info_on_img_frame_debug()
# Show debug image on window
self.update_img_frame_debug()
# Resize img_route_debug for better visualization
if not self.args.patrol:
self.img_route_debug = cv2.resize(
self.img_route_debug, (0, 0),
fx=self.cfg.minimap_upscale_factor,
fy=self.cfg.minimap_upscale_factor,
interpolation=cv2.INTER_NEAREST)
cv2.imshow("Route Map Debug", self.img_route_debug)
if name == 'main':
parser = argparse.ArgumentParser()
parser.add_argument(
'--disable_control',
action='store_true',
help='Disable simulated keyboard input'
)
code
parser.add_argument(
'--patrol',
action='store_true',
help='Enable patrol mode'
)
# Argument to specify map name
parser.add_argument(
'--map',
type=str,
default='lost_time_1',
help='Specify the map name'
)
parser.add_argument(
"--monsters",
type=str,
default="evolved_ghost",
help="Specify which monsters to load, comma-separated"
"(e.g., --monsters green_mushroom,zombie_mushroom)"
)
parser.add_argument(
'--attack',
type=str,
default='magic_claw',
help='Choose attack method, "magic_claw", "aoe_skill"'
)
parser.add_argument(
'--nametag',
type=str,
default='example',
help='Choose nametag png file in nametag/'
)
try:
mapleStoryBot = MapleStoryBot(parser.parse_args())
except Exception as e:
logger.error(f"MapleStoryBot Init failed: {e}")
sys.exit(1)
else:
while True:
t_start = time.time()
# Process one game window frame
mapleStoryBot.run_once()
# Exit if 'q' is pressed
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
# Cap FPS to save system resource
frame_duration = time.time() - t_start
target_duration = 1.0 / mapleStoryBot.cfg.fps_limit
if frame_duration < target_duration:
time.sleep(target_duration - frame_duration)
cv2.destroyAllWindows()
# Set status to hunting for start
self.switch_status("hunting")
map_dir = "minimaps" if self.cfg.is_use_minimap else "maps"
if args.patrol:
# Patrol mode doesn't need map or route
self.img_map = None
self.img_routes = []
self.img_route_rest = None
else:
# Load map for camera localization
if self.cfg.is_use_minimap:
self.img_map = load_image(f"{map_dir}/{args.map}/map.png",
cv2.IMREAD_COLOR)
else:
self.img_map = load_image(f"{map_dir}/{args.map}/map.png",
cv2.IMREAD_GRAYSCALE)
self.img_map_resized = cv2.resize(
self.img_map, (0, 0),
fx=self.cfg.localize_downscale_factor,
fy=self.cfg.localize_downscale_factor)
# Load route*.png images
route_files = sorted(glob.glob(f"{map_dir}/{args.map}/route*.png"))
route_files = [p for p in route_files if not p.endswith("route_rest.png")]
self.img_routes = [
cv2.cvtColor(load_image(p), cv2.COLOR_BGR2RGB) for p in route_files
]
# Load rest route
self.img_route_rest = cv2.cvtColor(
load_image(f"{map_dir}/{args.map}/route_rest.png"), cv2.COLOR_BGR2RGB)
# Upscale minimap route map for better debug visualization
if self.cfg.is_use_minimap:
img_routes_resized = []
for img_route in self.img_routes:
img_routes_resized.append(cv2.resize(
img_route, (0, 0),
fx=self.cfg.minimap_upscale_factor,
fy=self.cfg.minimap_upscale_factor,
interpolation=cv2.INTER_NEAREST))
self.img_routes = img_routes_resized
self.img_route_rest = cv2.resize(
self.img_route_rest, (0, 0),
fx=self.cfg.minimap_upscale_factor,
fy=self.cfg.minimap_upscale_factor,
interpolation=cv2.INTER_NEAREST)
# Load other images
self.img_nametag = load_image("name_tag.png")
self.img_nametag_gray = load_image("name_tag.png", cv2.IMREAD_GRAYSCALE)
self.img_rune_warning = load_image("rune/rune_warning.png", cv2.IMREAD_GRAYSCALE)
self.img_rune = load_image("rune/rune.png")
self.img_rune_gray = load_image("rune/rune.png", cv2.IMREAD_GRAYSCALE)
self.img_arrows = {
"left":
[load_image("rune/arrow_left_1.png"),
load_image("rune/arrow_left_2.png"),
load_image("rune/arrow_left_3.png"),],
"right":
[load_image("rune/arrow_right_1.png"),
load_image("rune/arrow_right_2.png"),
load_image("rune/arrow_right_3.png"),],
"up":
[load_image("rune/arrow_up_1.png"),
load_image("rune/arrow_up_2.png"),
load_image("rune/arrow_up_3.png")],
"down":
[load_image("rune/arrow_down_1.png"),
load_image("rune/arrow_down_2.png"),
load_image("rune/arrow_down_3.png"),],
}
# Load monsters images from monster/{monster_name}
self.monsters = {}
for monster_name in args.monsters.split(","):
imgs = []
for file in glob.glob(f"monster/{monster_name}/{monster_name}*.png"):
# Add original image
img = load_image(file)
imgs.append((img, get_mask(img, (0, 255, 0))))
# Add flipped image
img_flip = cv2.flip(img, 1)
imgs.append((img_flip, get_mask(img_flip, (0, 255, 0))))
if imgs:
self.monsters[monster_name] = imgs
else:
logger.error(f"No images found in monster/{monster_name}/{monster_name}*")
raise RuntimeError(f"No images found in monster/{monster_name}/{monster_name}*")
logger.info(f"Loaded monsters: {list(self.monsters.keys())}")
# Start keyboard controller thread
self.kb = KeyBoardController(self.cfg, args)
if args.disable_control:
self.kb.disable()
# Start game window capturing thread
logger.info("Waiting for game window to activate, please click on game window")
self.capture = GameWindowCapturor(self.cfg)
def get_minimap_location(self):
'''
get_minimap_location
'''
loc_minimap, score, is_cached = find_pattern_sqdiff(
self.img_frame, self.img_map)
return loc_minimap
def get_player_location_on_minimap(self):
"""
Get the player's location on the minimap by detecting a unique 4-pixel color.
Return the player's location in minimap coordinates.
"""
# Crop the minimap from the game screen
x0, y0 = self.loc_minimap
h, w, _ = self.img_route.shape
img_minimap = self.img_frame[y0:y0 + h//4, x0:x0 + w//4]
# Find pixels matching the player color
mask = cv2.inRange(img_minimap,
self.cfg.minimap_player_color,
self.cfg.minimap_player_color)
coords = cv2.findNonZero(mask)
if coords is None or len(coords) < 4:
logger.warning("Fail to locate player location on minimap")
return None
# Calculate the average location of the matching pixels
avg = coords.mean(axis=0)[0] # shape (1,2), so we take [0]
loc_player_minimap = (int(round(avg[0] * self.cfg.minimap_upscale_factor)),
int(round(avg[1] * self.cfg.minimap_upscale_factor)))
# Draw red circle to mark player's location on minimap
cv2.circle(self.img_route_debug, loc_player_minimap,
radius=4, color=(0, 255, 255), thickness=2)
return loc_player_minimap
def get_nearest_color_code_on_minimap(self):
'''
get_nearest_color_code_on_minimap
'''
x0, y0 = self.loc_player_minimap
h, w = self.img_route.shape[:2]
x_min = max(0, x0 - self.cfg.minimap_color_code_search_range)
x_max = min(w, x0 + self.cfg.minimap_color_code_search_range)
y_min = max(0, y0 - self.cfg.minimap_color_code_search_range)
y_max = min(h, y0 + self.cfg.minimap_color_code_search_range)
nearest = None
min_dist = float('inf')
for y in range(y_min, y_max):
for x in range(x_min, x_max):
pixel = tuple(self.img_route[y, x]) # (R, G, B)
if pixel in self.cfg.color_code:
dist = abs(x - x0) + abs(y - y0)
if dist < min_dist:
min_dist = dist
nearest = {
"pixel": (x, y),
"color": pixel,
"action": self.cfg.color_code[pixel],
"distance": dist
}
# Debug
draw_rectangle(
self.img_route_debug,
(x_min, y_min),
(self.cfg.minimap_color_code_search_range*2,
self.cfg.minimap_color_code_search_range*2),
(0, 0, 255), "Search Range",
)
# Draw a straigt line from map_loc_player to color_code["pixel"]
if nearest is not None:
cv2.line(
self.img_route_debug,
self.loc_player_minimap, # start point
nearest["pixel"], # end point
(0, 255, 0), # green line
1 # thickness
)
# Print color code on debug image
cv2.putText(
self.img_frame_debug, f"Route Action: {nearest["action"]}",
(720, 90),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
cv2.putText(
self.img_frame_debug, f"Route Index: {self.idx_routes}",
(720, 120),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
return nearest # if not found return none
def switch_status(self, new_status):
'''
Switch to new status and log the transition.
Parameters:
- new_status: string, the new status to switch to.
'''
# Ignore dummy transition
if self.status == new_status:
return
t_elapsed = round(time.time() - self.t_last_switch_status)
logger.info(f"[switch_status] From {self.status}({t_elapsed} sec) to {new_status}.")
self.status = new_status
self.t_last_switch_status = time.time()
def get_nearest_monster(self, is_left = True, overlap_threshold=0.5):
'''
get_nearest_monster
'''
if is_left:
x0 = self.loc_player[0] - self.cfg.magic_claw_range_x
else:
x0 = self.loc_player[0]
y0 = self.loc_player[1] - self.cfg.magic_claw_range_y//2
x1 = x0 + self.cfg.magic_claw_range_x
y1 = y0 + self.cfg.magic_claw_range_y
# Debug, magic claw hit box
draw_rectangle(
self.img_frame_debug, (x0, y0),
(self.cfg.magic_claw_range_y, self.cfg.magic_claw_range_x),
(0, 0, 255), "Attack Box"
)
nearest_monster = None
min_distance = float('inf')
for monster in self.monster_info:
mx1, my1 = monster["position"]
mw, mh = monster["size"]
mx2 = mx1 + mw
my2 = my1 + mh
# Calculate intersection
ix1 = max(x0, mx1)
iy1 = max(y0, my1)
ix2 = min(x1, mx2)
iy2 = min(y1, my2)
iw = max(0, ix2 - ix1)
ih = max(0, iy2 - iy1)
inter_area = iw * ih
monster_area = mw * mh
if monster_area == 0:
continue # skip degenerate box
if inter_area/monster_area >= overlap_threshold:
# Compute distance to player center
monster_center = (mx1 + mw // 2, my1 + mh // 2)
dx = monster_center[0] - self.loc_player[0]
dy = monster_center[1] - self.loc_player[1]
distance = abs(dx) + abs(dy) # Manhattan distance
if distance < min_distance:
min_distance = distance
nearest_monster = monster
return nearest_monster
def solve_rune(self):
'''
Solve the rune puzzle by detecting the arrow directions and pressing corresponding keys.
'''
while self.is_in_rune_game():
for arrow_idx in [0,1,2,3]:
# Get lastest game screen frame buffer
self.frame = self.capture.get_frame()
# Resize game screen to 1296x759
self.img_frame = cv2.resize(self.frame, (1296, 759),
interpolation=cv2.INTER_NEAREST)
# Crop arrow detection box
x = self.cfg.arrow_box_start_point[0] + self.cfg.arrow_box_interval*arrow_idx
y = self.cfg.arrow_box_start_point[1]
size = self.cfg.arrow_box_size
img_roi = self.img_frame[y:y+size, x:x+size]
# Loop through all possible arrows template and choose the most possible one
best_score = float('inf')
best_direction = ""
for direction, arrow_list in self.img_arrows.items():
for img_arrow in arrow_list:
_, score, _ = find_pattern_sqdiff(
img_roi, img_arrow,
mask=get_mask(img_arrow, (0, 255, 0)))
if score < best_score:
best_score = score
best_direction = direction
logger.info(f"[solve_rune] Arrow({arrow_idx}) is {best_direction} with score({best_score})")
# Update img_frame_debug
self.img_frame_debug = self.img_frame.copy()
draw_rectangle(
self.img_frame_debug, (x, y), (size, size),
(0, 0, 255), str(round(best_score, 2))
)
# Update debug window
self.update_img_frame_debug()
cv2.waitKey(1)
# For logging
screenshot(self.img_frame_debug, "solve_rune")
# Press the key for 0.5 second
if not self.args.disable_control:
self.kb.press_key(best_direction, 0.5)
time.sleep(1)
logger.info(f"[solve_rune] Solved all arrows")
def is_player_stuck(self):
"""
Detect if the player is stuck (not moving).
If stuck for more than WATCH_DOG_TIMEOUT seconds, performs a random action.
"""
dx = abs(self.loc_player_global[0] - self.loc_watch_dog[0])
dy = abs(self.loc_player_global[1] - self.loc_watch_dog[1])
current_time = time.time()
if dx + dy > self.cfg.watch_dog_range:
# Player moved, reset watchdog timer
self.loc_watch_dog = self.loc_player_global
self.t_watch_dog = current_time
return False
dt = current_time - self.t_watch_dog
if dt > self.cfg.watch_dog_timeout:
# watch dog idle for too long, player stuck
self.loc_watch_dog = self.loc_player_global
self.t_watch_dog = current_time
logger.warning(f"[is_player_stuck] Player stuck for {dt} seconds.")
return True
return False
def is_player_stuck_minimap(self):
"""
Detect if the player is stuck (not moving).
If stuck for more than WATCH_DOG_TIMEOUT seconds, performs a random action.
"""
dx = abs(self.loc_player_minimap[0] - self.loc_watch_dog[0])
dy = abs(self.loc_player_minimap[1] - self.loc_watch_dog[1])
current_time = time.time()
if dx + dy > self.cfg.watch_dog_range:
# Player moved, reset watchdog timer
self.loc_watch_dog = self.loc_player_minimap
self.t_watch_dog = current_time
return False
dt = current_time - self.t_watch_dog
if dt > self.cfg.watch_dog_timeout:
# watch dog idle for too long, player stuck
self.loc_watch_dog = self.loc_player_minimap
self.t_watch_dog = current_time
logger.warning(f"[is_player_stuck] Player stuck for {dt} seconds.")
return True
return False
def get_nearest_color_code(self):
'''
get_nearest_color_code
'''
x0, y0 = self.loc_player_global
h, w = self.img_route.shape[:2]
x_min = max(0, x0 - self.cfg.color_code_search_range)
x_max = min(w, x0 + self.cfg.color_code_search_range)
y_min = max(0, y0 - self.cfg.color_code_search_range)
y_max = min(h, y0 + self.cfg.color_code_search_range)
nearest = None
min_dist = float('inf')
for y in range(y_min, y_max):
for x in range(x_min, x_max):
pixel = tuple(self.img_route[y, x]) # (R, G, B)
if pixel in self.cfg.color_code:
dist = abs(x - x0) + abs(y - y0)
if dist < min_dist:
min_dist = dist
nearest = {
"pixel": (x, y),
"color": pixel,
"action": self.cfg.color_code[pixel],
"distance": dist
}
# Debug
draw_rectangle(
self.img_route_debug,
(x_min, y_min),
(self.cfg.color_code_search_range*2, self.cfg.color_code_search_range*2),
(0, 0, 255), "Color Search Range"
)
# Draw a straigt line from map_loc_player to color_code["pixel"]
if nearest is not None:
cv2.line(
self.img_route_debug,
self.loc_player_global, # start point
nearest["pixel"], # end point
(0, 255, 0), # green line
1 # thickness
)
# Print color code on debug image
cv2.putText(
self.img_frame_debug, f"Route Action: {nearest["action"]}",
(720, 90),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
cv2.putText(
self.img_frame_debug, f"Route Index: {self.idx_routes}",
(720, 120),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
return nearest # if not found return none
def get_hp_mp_exp(self):
'''
get_hp_mp_exp
'''
# HP crop
hp_bar = self.img_frame[self.cfg.hp_bar_top_left[1]:self.cfg.hp_bar_bottom_right[1]+1,
self.cfg.hp_bar_top_left[0]:self.cfg.hp_bar_bottom_right[0]+1]
# MP crop
mp_bar = self.img_frame[self.cfg.mp_bar_top_left[1]:self.cfg.mp_bar_bottom_right[1]+1,
self.cfg.mp_bar_top_left[0]:self.cfg.mp_bar_bottom_right[0]+1]
# EXP crop
exp_bar = self.img_frame[self.cfg.exp_bar_top_left[1]:self.cfg.exp_bar_bottom_right[1]+1,
self.cfg.exp_bar_top_left[0]:self.cfg.exp_bar_bottom_right[0]+1]
# HP Detection (detect empty part)
empty_mask_hp = (hp_bar[:,:,0] == hp_bar[:,:,1]) & (hp_bar[:,:,0] == hp_bar[:,:,2])
empty_pixels_hp = np.count_nonzero(empty_mask_hp)-6 # 6 pixel always be white
total_pixels_hp = hp_bar.shape[0] * hp_bar.shape[1] - 6
hp_ratio = 1 - (empty_pixels_hp / total_pixels_hp)
# MP Detection (detect empty part)
empty_mask_mp = (mp_bar[:,:,0] == mp_bar[:,:,1]) & (mp_bar[:,:,0] == mp_bar[:,:,2])
empty_pixels_mp = np.count_nonzero(empty_mask_mp)-6 # 6 pixel always be white
total_pixels_mp = mp_bar.shape[0] * mp_bar.shape[1] - 6
mp_ratio = 1 - (empty_pixels_mp / total_pixels_mp)
# EXP Detection (detect eexpty part)
empty_mask_exp = (exp_bar[:,:,0] == exp_bar[:,:,1]) & (exp_bar[:,:,0] == exp_bar[:,:,2])
eexpty_pixels_exp = np.count_nonzero(empty_mask_exp)-6 # 6 pixel always be white
total_pixels_exp = exp_bar.shape[0] * exp_bar.shape[1] - 6
exp_ratio = 1 - (eexpty_pixels_exp / total_pixels_exp)
# Compute original bar dimensions
hp_h, hp_w = hp_bar.shape[:2]
mp_h, mp_w = mp_bar.shape[:2]
exp_h, exp_w = exp_bar.shape[:2]
# Overlay HP/MP/EXP text
x_start, y_start = (250, 90)
cv2.putText(self.img_frame_debug, f"HP: {hp_ratio*100:.1f}%", (x_start, y_start),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 2)
cv2.putText(self.img_frame_debug, f"MP: {mp_ratio*100:.1f}%", (x_start, y_start+30),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 2)
cv2.putText(self.img_frame_debug, f"EXP: {exp_ratio*100:.1f}%", (x_start, y_start+60),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 2)
# Paste HP/MP/EXP bar on img_frame_debug
x_start, y_start = (410, 73)
self.img_frame_debug[y_start:y_start+hp_h, x_start:x_start+hp_w] = hp_bar
self.img_frame_debug[y_start+30:y_start+30+mp_h, x_start:x_start+mp_w] = mp_bar
self.img_frame_debug[y_start+60:y_start+60+exp_h, x_start:x_start+exp_w] = exp_bar
return hp_ratio, mp_ratio, exp_ratio
def is_rune_warning(self):
'''
is_rune_warning
'''
x0, y0 = self.cfg.rune_warning_top_left
x1, y1 = self.cfg.rune_warning_bottom_right
_, score, _ = find_pattern_sqdiff(
self.img_frame_gray[y0:y1, x0:x1],
self.img_rune_warning)
if self.status == "hunting" and score < self.cfg.rune_warning_diff_thres:
logger.info(f"[is_rune_warning] Detect rune warning on screen with score({score})")
return True
else:
return False
def is_rune_near_player(self):
'''
is_rune_near_player
'''
# Calculate bounding box
h, w = self.img_frame.shape[:2]
x0 = max(0, self.loc_player[0] - self.cfg.rune_detect_box_width // 2)
y0 = max(0, self.loc_player[1] - self.cfg.rune_detect_box_height)
x1 = min(w, self.loc_player[0] + self.cfg.rune_detect_box_width // 2)
y1 = min(h, self.loc_player[1])
# Debug
draw_rectangle(
self.img_frame_debug, (x0, y0), (y1-y0, x1-x0),
(255, 0, 0), "Rune Detection Range"
)
# Find rune icon near player
if (x1 - x0) < self.img_rune.shape[1] or \
(y1 - y0) < self.img_rune.shape[0]:
return False # Skip check if box is out of range
else:
img_roi = self.img_frame[y0:y1, x0:x1]
loc_rune, score, _ = find_pattern_sqdiff(
img_roi,
self.img_rune,
mask=get_mask(self.img_rune, (0, 255, 0)))
# # Draw rectangle for debug
# draw_rectangle(
# self.img_frame_debug,
# (x0 + loc_rune[0], y0 + loc_rune[1]),
# self.img_rune.shape,
# (255, 0, 255), # purple in BGR
# f"Rune,{round(score, 2)}"
# )
detect_thres = self.cfg.rune_detect_diff_thres + self.rune_detect_level*self.cfg.rune_detect_level_coef
if score < detect_thres:
logger.info(f"[Rune Detect] Found rune near player with score({score})," + \
f"level({self.rune_detect_level}),threshold({detect_thres})")
# Draw rectangle for debug
draw_rectangle(
self.img_frame_debug,
(x0 + loc_rune[0], y0 + loc_rune[1]),
self.img_rune.shape,
(255, 0, 255), # purple in BGR
f"Rune,{round(score, 2)}"
)
screenshot(self.img_frame_debug, "rune_detected")
return True
else:
return False
def is_in_rune_game(self):
'''
is_in_rune_game
'''
# Get lastest game screen frame buffer
self.frame = self.capture.get_frame()
# Resize game screen to 1296x759
self.img_frame = cv2.resize(self.frame, (1296, 759), interpolation=cv2.INTER_NEAREST)
# Crop arrow detection box
x, y = self.cfg.arrow_box_start_point
size = self.cfg.arrow_box_size
img_roi = self.img_frame[y:y+size, x:x+size]
# Check if arrow exist on screen
best_score = float('inf')
for direc, arrow_list in self.img_arrows.items():
for img_arrow in arrow_list:
_, score, _ = find_pattern_sqdiff(
img_roi, img_arrow,
mask=get_mask(img_arrow, (0, 255, 0)))
if score < best_score:
best_score = score
draw_rectangle(
self.img_frame_debug, (x, y), (size, size),
(0, 0, 255), str(round(best_score, 2))
)
if best_score < self.cfg.arrow_box_diff_thres:
logger.info(f"Arrow screen detected with score({score})")
return True
return False
def get_monsters_in_range(self, top_left, bottom_right):
'''
get_monsters_in_range
'''
x0, y0 = top_left
x1, y1 = bottom_right
img_roi = self.img_frame[y0:y1, x0:x1]
monster_info = []
for monster_name, monster_imgs in self.monsters.items():
for img_monster, mask_monster in monster_imgs:
if self.args.patrol:
pass # Don't detect monster using template in patrol mode
elif self.cfg.monster_detect_mode == "template_free":
# Generate mask where pixel is exactly (0,0,0)
black_mask = np.all(img_roi == [0, 0, 0], axis=2).astype(np.uint8) * 255
cv2.imshow("Black Pixel Mask", black_mask)
# Shift player's location into ROI coordinate system
px, py = self.loc_player
px_in_roi = px - x0
py_in_roi = py - y0
# Define rectangle range around player (in ROI coordinate)
char_x_min = max(0, px_in_roi - self.cfg.character_width // 2)
char_x_max = min(img_roi.shape[1], px_in_roi + self.cfg.character_width // 2)
char_y_min = max(0, py_in_roi - self.cfg.character_height // 2)
char_y_max = min(img_roi.shape[0], py_in_roi + self.cfg.character_height // 2)
# Zero out mask inside this region (ignore player's own character)
black_mask[char_y_min:char_y_max, char_x_min:char_x_max] = 0
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (20, 20))
closed_mask = cv2.morphologyEx(black_mask, cv2.MORPH_CLOSE, kernel)
# cv2.imshow("Black Mask", closed_mask)
# draw player character bounding box
draw_rectangle(
self.img_frame_debug, (char_x_min+x0, char_y_min+y0),
(self.cfg.character_height, self.cfg.character_width),
(255, 0, 0), "Character Box"
)
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(closed_mask, connectivity=8)
monster_info = []
min_area = 1000
for i in range(1, num_labels):
x, y, w, h, area = stats[i]
if area > min_area:
monster_info.append({
"name": "",
"position": (x0+x, y0+y),
"size": (h, w),
"score": 1.0,
})
elif self.cfg.monster_detect_mode == "contour_only":
# Use only black lines contour to detect monsters
# Create masks (already grayscale)
mask_pattern = np.all(img_monster == [0, 0, 0], axis=2).astype(np.uint8) * 255
mask_roi = np.all(img_roi == [0, 0, 0], axis=2).astype(np.uint8) * 255
# Apply Gaussian blur (soften the masks)
img_monster_blur = cv2.GaussianBlur(mask_pattern, (self.cfg.blur_range, self.cfg.blur_range), 0)
img_roi_blur = cv2.GaussianBlur(mask_roi, (self.cfg.blur_range, self.cfg.blur_range), 0)
# Check template vs ROI size before matching
h_roi, w_roi = img_roi_blur.shape[:2]
h_temp, w_temp = img_monster_blur.shape[:2]
if h_temp > h_roi or w_temp > w_roi:
return [] # template bigger than roi, skip this matching
# Perform template matching
res = cv2.matchTemplate(img_roi_blur, img_monster_blur, cv2.TM_SQDIFF_NORMED)
# Apply soft threshold
match_locations = np.where(res <= self.cfg.monster_diff_thres)
h, w = img_monster.shape[:2]
for pt in zip(*match_locations[::-1]):
monster_info.append({
"name": monster_name,
"position": (pt[0] + x0, pt[1] + y0),
"size": (h, w),
"score": res[pt[1], pt[0]],
})
elif self.cfg.monster_detect_mode == "grayscale":
img_monster_gray = cv2.cvtColor(img_monster, cv2.COLOR_BGR2GRAY)
img_roi_gray = cv2.cvtColor(img_roi, cv2.COLOR_BGR2GRAY)
res = cv2.matchTemplate(
img_roi_gray,
img_monster_gray,
cv2.TM_SQDIFF_NORMED,
mask=mask_monster)
match_locations = np.where(res <= self.cfg.monster_diff_thres)
h, w = img_monster.shape[:2]
for pt in zip(*match_locations[::-1]):
monster_info.append({
"name": monster_name,
"position": (pt[0] + x0, pt[1] + y0),
"size": (h, w),
"score": res[pt[1], pt[0]],
})
elif self.cfg.monster_detect_mode == "color":
res = cv2.matchTemplate(
img_roi,
img_monster,
cv2.TM_SQDIFF_NORMED,
mask=mask_monster)
match_locations = np.where(res <= self.cfg.monster_diff_thres)
h, w = img_monster.shape[:2]
for pt in zip(*match_locations[::-1]):
monster_info.append({
"name": monster_name,
"position": (pt[0] + x0, pt[1] + y0),
"size": (h, w),
"score": res[pt[1], pt[0]],
})
else:
logger.error(f"Unexpected camera localization mode: {self.cfg.monster_detect_mode}")
return []
# Apply Non-Maximum Suppression to monster detection
monster_info = nms(monster_info, iou_threshold=0.4)
# Detect monster via health bar
if self.cfg.monster_detect_with_health_bar:
# Create color mask for Monsters' HP bar
mask = cv2.inRange(img_roi,
np.array(self.cfg.monster_health_bar_color),
np.array(self.cfg.monster_health_bar_color))
# Find connected components (each cluster of green pixels)
num_labels, labels, stats, centroids = \
cv2.connectedComponentsWithStats(mask, connectivity=8)
for i in range(1, num_labels): # skip background (label 0)
x, y, w, h, area = stats[i]
if area < 3: # small noise filter
continue
# Guess a monster bounding box
y += 10
x = max(0, x)
y = max(0, y)
w = 70
h = 70
monster_info.append({
"name": "Health Bar",
"position": (x0 + x, y0 + y),
"size": (h, w),
"score": 1.0,
})
# Debug
# Draw attack detection range
draw_rectangle(
self.img_frame_debug, (x0, y0), (y1-y0, x1-x0),
(255, 0, 0), "Monster Detection Box"
)
# Draw monsters bounding box
for monster in monster_info:
if monster["name"] == "Health Bar":
color = (0, 255, 255)
else:
color = (0, 255, 0)
draw_rectangle(
self.img_frame_debug, monster["position"], monster["size"],
color, str(round(monster['score'], 2))
)
return monster_info
def get_player_location(self):
'''
get player location by detecting player's nametag
'''
img_roi = self.img_frame_gray[self.cfg.camera_ceiling:self.cfg.camera_floor, :]
# Pad search region to avoid edge cut-off issue (full template size)
(pad_y, pad_x) = self.img_nametag.shape[:2]
img_roi_padded = cv2.copyMakeBorder(
img_roi,
pad_y, pad_y, pad_x, pad_x,
borderType=cv2.BORDER_REPLICATE # replicate border for safe matching
)
# Adjust previous location
if self.is_first_frame:
last_result = None
else:
last_result = (
self.loc_nametag[0] + pad_x,
self.loc_nametag[1] - self.cfg.camera_ceiling + pad_y
)
# Split nametag into left and right half, detect seperately and pick highest socre
# This localization method is more robust for occluded nametag
h, w = self.img_nametag_gray.shape
mask_full = get_mask(self.img_nametag, (0, 255, 0))
nametag_variants = {
"left": {
"img_pattern": self.img_nametag_gray[:, :w // 2],
"mask": mask_full[:, :w // 2],
"last_result": last_result,
"score_penalty": 0.0
},
"right": {
"img_pattern": self.img_nametag_gray[:, w // 2:],
"mask": mask_full[:, w // 2:],
"last_result": (last_result[0] + w // 2, last_result[1]) if last_result else None,
"score_penalty": 0.0
}
}
# Match template for each split nametag
matches = []
for tag_type, data in nametag_variants.items():
loc, score, is_cached = find_pattern_sqdiff(
img_roi_padded,
data["img_pattern"],
last_result=data["last_result"],
mask=data["mask"],
global_threshold=0.3
)
w_match = data["img_pattern"].shape[1]
h_match = data["img_pattern"].shape[0]
score += data["score_penalty"]
matches.append((tag_type, loc, score, w_match, h_match, is_cached))
# Choose the best match
matches.sort(key=lambda x: (not x[5], x[2]))
tag_type, loc_nametag, score, w_match, h_match, is_cached = matches[0]
if tag_type == "right":
loc_nametag = (loc_nametag[0] - w_match, loc_nametag[1])
# Convert back to original (unpadded) coordinates
loc_nametag = (
loc_nametag[0] - pad_x,
loc_nametag[1] - pad_y + self.cfg.camera_ceiling
)
# Update name tag location if confidence is good
if score < self.cfg.nametag_diff_thres:
self.loc_nametag = loc_nametag
loc_player = (
self.loc_nametag[0] - self.cfg.nametag_offset[0],
self.loc_nametag[1] - self.cfg.nametag_offset[1]
)
# Draw name tag detection box for debug
draw_rectangle(
self.img_frame_debug, self.loc_nametag, self.img_nametag.shape,
(0, 255, 0), "")
text = f"NameTag,{round(score, 2)}," + \
f"{'cached' if is_cached else 'missed'}," + \
f"{tag_type}"
cv2.putText(self.img_frame_debug, text,
(self.loc_nametag[0], self.loc_nametag[1] + self.img_nametag.shape[0] + 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
# Draw player center
cv2.circle(self.img_frame_debug,
loc_player, radius=3,
color=(0, 0, 255), thickness=-1)
return loc_player
def get_player_location_global(self):
'''
get_player_location_global
'''
scale_factor = self.cfg.localize_downscale_factor
# Downscale both template and search image
img_roi = self.img_frame_gray[self.cfg.camera_ceiling:self.cfg.camera_floor, :]
img_query = cv2.resize(img_roi, (0, 0), fx=scale_factor, fy=scale_factor)
# Get previous frame result
if self.is_first_frame or \
time.time() - self.t_last_camera_missed > self.cfg.localize_cached_interval:
last_result = None
self.t_last_camera_missed = time.time()
else:
last_result = (
int(self.loc_camera[0] * scale_factor),
int(self.loc_camera[1] * scale_factor)
)
loc_camera, score, is_cached = find_pattern_sqdiff(
self.img_map_resized,
img_query,
last_result=last_result,
local_search_radius=20,
global_threshold = 0.8)
self.loc_camera = (
int(loc_camera[0] / scale_factor),
int(loc_camera[1] / scale_factor)
)
loc_player_global = (
self.loc_camera[0] + self.loc_player[0],
self.loc_camera[1] + self.loc_player[1] - self.cfg.camera_ceiling)
# Draw camera rectangle
camera_bottom_right = (
self.loc_camera[0] + self.img_frame.shape[1],
self.loc_camera[1] + self.img_frame.shape[0]
)
cv2.rectangle(self.img_route_debug, self.loc_camera,
camera_bottom_right, (0, 255, 255), 2)
cv2.putText(
self.img_route_debug,
f"Camera, score={round(score, 2)}, {'cached' if is_cached else 'missed'}",
(self.loc_camera[0], self.loc_camera[1] + 60),
cv2.FONT_HERSHEY_SIMPLEX, 2,
(0, 255, 0), 2
)
# Draw player center
cv2.circle(self.img_route_debug,
loc_player_global, radius=3,
color=(0, 0, 255), thickness=-1)
cv2.putText(self.img_route_debug, "Player",
(loc_player_global[0] - 30, loc_player_global[1] - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
return loc_player_global
def is_near_edge(self):
'''
is_near_edge
'''
if self.cfg.is_use_minimap:
x0, y0 = self.loc_player_minimap
h, w = self.img_route.shape[:2]
x_min = max(0, x0 - self.cfg.edge_teleport_minimap_box_width//2)
x_max = min(w, x0 + self.cfg.edge_teleport_minimap_box_width//2)
y_min = max(0, y0 - self.cfg.edge_teleport_minimap_box_height//2)
y_max = min(h, y0 + self.cfg.edge_teleport_minimap_box_height//2)
else:
x0, y0 = self.loc_player_global
h, w = self.img_route.shape[:2]
x_min = max(0, x0 - self.cfg.edge_teleport_box_width//2)
x_max = min(w, x0 + self.cfg.edge_teleport_box_width//2)
y_min = max(0, y0 - self.cfg.edge_teleport_box_height//2)
y_max = min(h, y0 + self.cfg.edge_teleport_box_height//2)
# Debug: draw search box
draw_rectangle(
self.img_route_debug,
(x_min, y_min),
(y_max - y_min, x_max - x_min),
(0, 0, 255), "Edge Check"
)
# Find mask of matching pixels
roi = self.img_route[y_min:y_max, x_min:x_max]
mask = np.all(roi == self.cfg.edge_teleport_color_code, axis=2)
coords = np.column_stack(np.where(mask))
# No edge pixel
if coords.size == 0:
return ""
# Calculate mean position of matching pixels
mean_x = np.mean(coords[:, 1])
# Compare to roi center
if mean_x < x0:
return "edge on left"
else:
return "edge on right"
def get_random_action(self):
'''
get_random_action
'''
action = random.choice(list(self.cfg.color_code.values()))
logger.warning(f"Perform random action: {action}")
return action
def update_info_on_img_frame_debug(self):
'''
update_info_on_img_frame_debug
'''
# Print text at bottom left corner
self.fps = round(1.0 / (time.time() - self.t_last_frame))
text_y_interval = 23
text_y_start = 550
dt_screenshot = time.time() - self.kb.t_last_screenshot
text_list = [
f"FPS: {self.fps}",
f"Status: {self.status}",
f"Press 'F1' to {"pause" if self.kb.is_enable else "start"} Bot",
f"Press 'F2' to save screenshot{" : Saved" if dt_screenshot < 0.7 else ""}"]
for idx, text in enumerate(text_list):
cv2.putText(
self.img_frame_debug, text,
(10, text_y_start + text_y_interval*idx),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
# Don't draw minimap in patrol mode
if self.args.patrol:
return
# mini-map on debug image
if self.cfg.is_use_minimap:
# Compute crop region with boundary check
crop_w, crop_h = 300, 300
x0 = max(0, self.loc_player_minimap[0] - crop_w // 2)
y0 = max(0, self.loc_player_minimap[1] - crop_h // 2)
x1 = min(self.img_route_debug.shape[1], x0 + crop_w)
y1 = min(self.img_route_debug.shape[0], y0 + crop_h)
# Crop region
mini_map_crop = self.img_route_debug[y0:y1, x0:x1]
mini_map_crop = cv2.resize(mini_map_crop,
(int(mini_map_crop.shape[1] // 1.5),
int(mini_map_crop.shape[0] // 1.5)),
interpolation=cv2.INTER_NEAREST)
# Paste into top-right corner of self.img_frame_debug
h_crop, w_crop = mini_map_crop.shape[:2]
h_frame, w_frame = self.img_frame_debug.shape[:2]
x_paste = w_frame - w_crop - 10 # 10px margin from right
y_paste = 70
self.img_frame_debug[y_paste:y_paste + h_crop, x_paste:x_paste + w_crop] = mini_map_crop
# Draw border around minimap
cv2.rectangle(
self.img_frame_debug,
(x_paste, y_paste),
(x_paste + w_crop, y_paste + h_crop),
color=(255, 255, 255), # White border
thickness=2
)
else:
# Compute crop region with boundary check
crop_w, crop_h = 400, 400
x0 = max(0, self.loc_player_global[0] - crop_w // 2)
y0 = max(0, self.loc_player_global[1] - crop_h // 2)
x1 = min(self.img_route_debug.shape[1], x0 + crop_w)
y1 = min(self.img_route_debug.shape[0], y0 + crop_h)
# Crop region
mini_map_crop = self.img_route_debug[y0:y1, x0:x1]
mini_map_crop = cv2.resize(mini_map_crop,
(mini_map_crop.shape[1] // 2, mini_map_crop.shape[0] // 2),
interpolation=cv2.INTER_NEAREST)
# Paste into top-right corner of self.img_frame_debug
h_crop, w_crop = mini_map_crop.shape[:2]
h_frame, w_frame = self.img_frame_debug.shape[:2]
x_paste = w_frame - w_crop - 10 # 10px margin from right
y_paste = 70
self.img_frame_debug[y_paste:y_paste + h_crop, x_paste:x_paste + w_crop] = mini_map_crop
# Draw border around minimap
cv2.rectangle(
self.img_frame_debug,
(x_paste, y_paste),
(x_paste + w_crop, y_paste + h_crop),
color=(255, 255, 255), # White border
thickness=2
)
def update_img_frame_debug(self):
'''
update_img_frame_debug
'''
cv2.imshow("Game Window Debug",
self.img_frame_debug[self.cfg.camera_ceiling:self.cfg.camera_floor, :])
# Update FPS timer
self.t_last_frame = time.time()
def run_once(self):
'''
Process with one game window frame
'''
# Get lastest game screen frame buffer
self.frame = self.capture.get_frame()
# Resize game screen to 1296x759
self.img_frame = cv2.resize(self.frame, (1296, 759), interpolation=cv2.INTER_NEAREST)
# Grayscale game window
self.img_frame_gray = cv2.cvtColor(self.img_frame, cv2.COLOR_BGR2GRAY)
# Image for debug use
self.img_frame_debug = self.img_frame.copy()
# Get current route image
if not self.args.patrol:
self.img_route = self.img_routes[self.idx_routes]
self.img_route_debug = cv2.cvtColor(self.img_route, cv2.COLOR_RGB2BGR)
# Get minimap location
if self.is_first_frame and self.cfg.is_use_minimap:
self.loc_minimap = self.get_minimap_location()
# Debug
if self.cfg.is_use_minimap:
h, w = self.img_map.shape[:2]
draw_rectangle(
self.img_frame_debug,
self.loc_minimap,
(h, w),
(0, 0, 255), "minimap",thickness=1
)
# Detect HP/MP/EXP bar on UI
self.hp_ratio, self.mp_ratio, self.exp_ratio = self.get_hp_mp_exp()
# Check whether "PLease remove runes" warning appears on screen
if self.is_rune_warning():
self.rune_detect_level = 0
self.switch_status("finding_rune")
# Get player location in game window
self.loc_player = self.get_player_location()
# Get player location on map
if self.cfg.is_use_minimap:
loc_player_minimap = self.get_player_location_on_minimap()
if loc_player_minimap:
self.loc_player_minimap = loc_player_minimap
else:
if not self.args.patrol:
self.loc_player_global = self.get_player_location_global()
# Check whether a rune icon is near player
if self.is_rune_near_player():
self.switch_status("near_rune")
# Check whether we entered the rune mini-game
if self.status == "near_rune":
# stop character
self.kb.set_command("stop")
time.sleep(0.1) # Wait for character to stop
self.kb.disable() # Disable kb thread during rune solving
# Attempt to trigger rune
if not self.args.disable_control:
self.kb.press_key("up", 0.02)
time.sleep(1) # Wait rune game to pop up
# If entered the game, start solving rune
if self.is_in_rune_game():
self.solve_rune() # Blocking until runes solved
self.rune_detect_level = 0 # reset rune detect level
self.switch_status("hunting")
# Restore kb thread
self.kb.enable()
# Get all monster near player
if self.args.attack == "aoe_skill":
# Search monster near player
x0 = max(0, self.loc_player[0] - self.cfg.aoe_skill_range_x//2)
x1 = min(self.img_frame.shape[1], self.loc_player[0] + self.cfg.aoe_skill_range_x//2)
y0 = max(0, self.loc_player[1] - self.cfg.aoe_skill_range_y//2)
y1 = min(self.img_frame.shape[0], self.loc_player[1] + self.cfg.aoe_skill_range_y//2)
elif self.args.attack == "magic_claw":
# Search monster nearby magic claw range
dx = self.cfg.magic_claw_range_x + self.cfg.monster_search_margin
dy = self.cfg.magic_claw_range_y + self.cfg.monster_search_margin
x0 = max(0, self.loc_player[0] - dx)
x1 = min(self.img_frame.shape[1], self.loc_player[0] + dx)
y0 = max(0, self.loc_player[1] - dy)
y1 = min(self.img_frame.shape[0], self.loc_player[1] + dy)
# Get monster in skill range
self.monster_info = self.get_monsters_in_range((x0, y0), (x1, y1))
if self.args.attack == "aoe_skill":
if len(self.monster_info) == 0:
attack_direction = None
else:
attack_direction = "I don't care"
elif self.args.attack == "magic_claw":
# Get nearest monster to player
monster_left = self.get_nearest_monster(is_left = True)
monster_right = self.get_nearest_monster(is_left = False)
# Compute distance for left
distance_left = float('inf')
if monster_left is not None:
mx, my = monster_left["position"]
mw, mh = monster_left["size"]
center_left = (mx + mw // 2, my + mh // 2)
distance_left = abs(center_left[0] - self.loc_player[0]) + \
abs(center_left[1] - self.loc_player[1])
# Compute distance for right
distance_right = float('inf')
if monster_right is not None:
mx, my = monster_right["position"]
mw, mh = monster_right["size"]
center_right = (mx + mw // 2, my + mh // 2)
distance_right = abs(center_right[0] - self.loc_player[0]) + \
abs(center_right[1] - self.loc_player[1])
# Choose attack direction
attack_direction = None
if distance_left < distance_right:
attack_direction = "left"
elif distance_right < distance_left:
attack_direction = "right"
command = ""
if self.args.patrol:
x, y = self.loc_player
h, w = self.img_frame.shape[:2]
loc_player_ratio = float(x)/float(w)
left_ratio, right_ratio = self.cfg.patrol_range
# Check if we need to change patrol direction
if self.is_patrol_to_left and loc_player_ratio < left_ratio:
self.patrol_turn_point_cnt += 1
elif (not self.is_patrol_to_left) and loc_player_ratio > right_ratio:
self.patrol_turn_point_cnt += 1
if self.patrol_turn_point_cnt > self.cfg.turn_point_thres:
self.is_patrol_to_left = not self.is_patrol_to_left
self.patrol_turn_point_cnt = 0
# Set command for patrol mode
if time.time() - self.t_patrol_last_attack > self.cfg.patrol_attack_interval:
command = "attack"
self.t_patrol_last_attack = time.time()
elif self.is_patrol_to_left:
command = "walk left"
else:
command = "walk right"
else:
# get color code from img_route
if self.cfg.is_use_minimap:
color_code = self.get_nearest_color_code_on_minimap()
else:
color_code = self.get_nearest_color_code()
if color_code:
if color_code["action"] == "goal":
# Switch to next route map
self.idx_routes = (self.idx_routes+1)%len(self.img_routes)
logger.debug(f"Change to new route:{self.idx_routes}")
command = color_code["action"]
# teleport away from edge to avoid fall off
if self.is_near_edge() and \
time.time() - self.t_last_teleport > self.cfg.teleport_cooldown:
command = command.replace("walk", "teleport")
self.t_last_teleport = time.time() # update timer
# Special logic for each status, overwrite color code action
if self.status == "hunting":
# Perform a random action when player stuck
if self.cfg.is_use_minimap and not self.args.patrol and \
self.is_player_stuck_minimap():
command = self.get_random_action()
elif not self.cfg.is_use_minimap and not self.args.patrol and \
self.is_player_stuck():
command = self.get_random_action()
elif command in ["up", "down"]:
pass # Don't attack or heal while character is on rope
# elif self.hp_ratio <= self.cfg.heal_ratio:
# command = "heal"
# elif self.mp_ratio <= self.cfg.add_mp_ratio:
# command = "add mp"
elif attack_direction == "I don't care":
command = "attack"
elif attack_direction == "left":
command = "attack left"
elif attack_direction == "right":
command = "attack right"
# WIP: teleport while walking is unstable
# elif command[:4] == "walk":
# if self.cfg.is_use_teleport_to_walk and \
# time.time() - self.t_last_teleport > self.cfg.teleport_cooldown:
# command = command.replace("walk", "teleport")
# self.t_last_teleport = time.time() # update timer
elif self.status == "finding_rune":
if self.is_player_stuck():
command = self.get_random_action()
# Check if finding rune timeout
if time.time() - self.t_last_switch_status > self.cfg.rune_finding_timeout:
self.rune_detect_level = 0 # reset level
self.switch_status("resting")
# Check if need to raise level to lower the detection threshold
self.rune_detect_level = int(time.time() - self.t_last_switch_status) // self.cfg.rune_detect_level_raise_interval
elif self.status == "near_rune":
# Stay in near_rune status for only a few seconds
if time.time() - self.t_last_switch_status > self.cfg.near_rune_duration:
self.switch_status("hunting")
elif self.status == "resting":
self.img_routes = [self.img_route_rest] # Set up resting route
self.idx_routes = 0
else:
logger.error(f"Unknown status: {self.status}")
# send command to keyboard controller
self.kb.set_command(command)
#############
### Debug ###
#############
# Print text on debug image
self.update_info_on_img_frame_debug()
# Show debug image on window
self.update_img_frame_debug()
# Check if need to save screenshot
if self.kb.is_need_screen_shot:
screenshot(mapleStoryBot.img_frame)
self.kb.is_need_screen_shot = False
# Resize img_route_debug for better visualization
if not self.args.patrol:
h, w = self.img_route_debug.shape[:2]
if not self.cfg.is_use_minimap:
self.img_route_debug = cv2.resize(self.img_route_debug, (w // 2, h // 2),
interpolation=cv2.INTER_NEAREST)
cv2.imshow("Route Map Debug", self.img_route_debug)
# Enable cached location since second frame
self.is_first_frame = False
if name == 'main':
parser = argparse.ArgumentParser()
parser.add_argument(
'--disable_control',
action='store_true',
help='Disable simulated keyboard input'
)
code
parser.add_argument(
'--patrol',
action='store_true',
help='Enable patrol mode'
)
# Argument to specify map name
parser.add_argument(
'--map',
type=str,
default='lost_time_1',
help='Specify the map name'
)
parser.add_argument(
"--monsters",
type=str,
default="evolved_ghost",
help="Specify which monsters to load, comma-separated"
"(e.g., --monsters green_mushroom,zombie_mushroom)"
)
parser.add_argument(
'--attack',
type=str,
default='magic_claw',
help='Choose attack method, "magic_claw", "aoe_skill"'
)
try:
mapleStoryBot = MapleStoryBot(parser.parse_args())
except Exception as e:
logger.error(f"MapleStoryBot Init failed: {e}")
sys.exit(1)
else:
while True:
t_start = time.time()
# Process one game window frame
mapleStoryBot.run_once()
# Exit if 'q' is pressed
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
# Cap FPS to save system resource
frame_duration = time.time() - t_start
target_duration = 1.0 / mapleStoryBot.cfg.fps_limit
if frame_duration < target_duration:
time.sleep(target_duration - frame_duration)
cv2.destroyAllWindows()
# Draw minimap rectangle on img debug
draw_rectangle(
self.img_frame_debug,
self.loc_minimap,
self.img_minimap.shape[:2],
(0, 0, 255), "minimap",thickness=1
)
# Compute crop region with boundary check
crop_w, crop_h = 80, 80
x0 = max(0, self.loc_player_global[0] - crop_w // 2)
y0 = max(0, self.loc_player_global[1] - crop_h // 2)
x1 = min(self.img_route_debug.shape[1], x0 + crop_w)
y1 = min(self.img_route_debug.shape[0], y0 + crop_h)
# Crop region
mini_map_crop = self.img_route_debug[y0:y1, x0:x1]
mini_map_crop = cv2.resize(mini_map_crop,
(int(mini_map_crop.shape[1] * 3),
int(mini_map_crop.shape[0] * 3)),
interpolation=cv2.INTER_NEAREST)
# Paste into top-right corner of self.img_frame_debug
h_crop, w_crop = mini_map_crop.shape[:2]
h_frame, w_frame = self.img_frame_debug.shape[:2]
x_paste = w_frame - w_crop - 10 # 10px margin from right
y_paste = 70
self.img_frame_debug[y_paste:y_paste + h_crop, x_paste:x_paste + w_crop] = mini_map_crop
# Draw border around minimap
cv2.rectangle(
self.img_frame_debug,
(x_paste, y_paste),
(x_paste + w_crop, y_paste + h_crop),
color=(255, 255, 255), # White border
thickness=2
)
def update_img_frame_debug(self):
'''
update_img_frame_debug
'''
cv2.imshow("Game Window Debug",
self.img_frame_debug[self.cfg.camera_ceiling:self.cfg.camera_floor, :])
# Update FPS timer
self.t_last_frame = time.time()
def get_player_location_on_global_map(self):
'''
get_player_location_on_global_map
'''
self.loc_minimap_global, score, _ = find_pattern_sqdiff(
self.img_map,
self.img_minimap)
loc_player_global = (
self.loc_minimap_global[0] + self.loc_player_minimap[0],
self.loc_minimap_global[1] + self.loc_player_minimap[1]
)
# Draw local minimap rectangle
camera_bottom_right = (
self.loc_minimap_global[0] + self.img_minimap.shape[1],
self.loc_minimap_global[1] + self.img_minimap.shape[0]
)
cv2.rectangle(self.img_route_debug, self.loc_minimap_global,
camera_bottom_right, (0, 255, 255), 1)
cv2.putText(
self.img_route_debug,
f"Minimap,score({round(score, 2)})",
(self.loc_minimap_global[0], self.loc_minimap_global[1]+15),
cv2.FONT_HERSHEY_SIMPLEX, 0.4,
(0, 255, 255), 1
)
# Draw player center
cv2.circle(self.img_route_debug,
loc_player_global, radius=2,
color=(0, 255, 255), thickness=-1)
return loc_player_global
def replace_color_on_map(self, lower_hsv, upper_hsv, replace_color=(0, 0, 0)):
'''
Replace pixels in self.img_map that fall within the given HSV range
and are part of a connected component with area > 15.
'''
hsv_map = cv2.cvtColor(self.img_map, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_map, to_opencv_hsv(lower_hsv), to_opencv_hsv(upper_hsv))
# Connected components
num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(mask, connectivity=8)
for i in range(1, num_labels): # skip background
area = stats[i, cv2.CC_STAT_AREA]
if area > 10:
component_mask = (labels == i)
self.img_map[component_mask] = replace_color
def __init__(self, args):
'''
Init MapleStoryBot
'''
self.cfg = Config # Configuration
self.args = args # User arguments
self.idx_routes = 0 # Index of route map
self.fps = 0 # Frame per second
self.is_first_frame = True # first frame flag
self.is_enable = True
# Coordinate (top-left coordinate)
self.loc_minimap = (0, 0) # minimap location on game screen
self.loc_player = (0, 0) # player location on game screen
self.loc_player_minimap = (0, 0) # player location on minimap
self.loc_minimap_global = (0, 0) # minimap location on global map
self.loc_player_global = (0, 0) # player location on global map
self.loc_player_global_last = None # playeer location on global map last frame
# Images
self.frame = None # raw image
self.img_frame = None # game window frame
self.img_frame_debug = None # game window frame for visualization
self.img_route = None # route map
self.img_route_debug = None # route map for visualization
self.img_minimap = None # minimap on game screen
self.img_map = None # map
# Timers
self.t_last_frame = time.time() # Last frame timer, for fps calculation
self.t_last_draw_blob = time.time() # Last draw blob timer
# Check create new map directory
map_dir = os.path.join("minimaps", args.new_map)
if os.path.exists(map_dir):
user_input = input(f"[Warning] Directory '{map_dir}' already exists. Replace it? (y/n): ").strip().lower()
if user_input == 'y':
shutil.rmtree(map_dir) # Delete existing directory
logger.info(f"Removed existing directory: {map_dir}")
else:
sys.exit(0)
os.makedirs(map_dir) # Create new map directory
logger.info(f"Created new directory: {map_dir}")
# Start keyboard listener thread
self.kb = KeyBoardListener(self.cfg)
# Start game window capturing thread
logger.info("Waiting for game window to activate, please click on game window")
self.capture = GameWindowCapturor(self.cfg)
def ensure_img_map_capacity(self, x, y, h, w):
'''
Ensure that self.img_map is large enough to contain the region defined by (x, y, h, w).
Always add at least self.cfg.map_scan_padding when expanding in any direction.
'''
map_h, map_w = self.img_map.shape[:2]
pad = self.cfg.map_scan_padding
# Compute required expansion margins
expand_top = pad - y if y < pad else 0
expand_left = pad - x if x < pad else 0
expand_bottom = y + h + pad - map_h if y + h + pad > map_h else 0
expand_right = x + w + pad - map_w if x + w + pad > map_w else 0
expand_top = max(0, expand_top)
expand_left = max(0, expand_left)
expand_bottom = max(0, expand_bottom)
expand_right = max(0, expand_right)
# If no expansion needed, return
if expand_top == 0 and expand_bottom == 0 and expand_left == 0 and expand_right == 0:
return
# Create new canvas and paste old image
new_h = map_h + expand_top + expand_bottom
new_w = map_w + expand_left + expand_right
new_map = np.zeros((new_h, new_w, 3), dtype=np.uint8)
new_map[expand_top:expand_top + map_h, expand_left:expand_left + map_w] = self.img_map
self.img_map = new_map
# Also update all global coordinates that depend on the map (optional)
self.loc_minimap_global = (
self.loc_minimap_global[0] + expand_left,
self.loc_minimap_global[1] + expand_top
)
def remove_color_code_pixels(self, img):
"""
Set all pixels in self.img_map to black if they match any color in color_code (assumed RGB).
"""
for rgb in self.cfg.color_code.keys():
bgr = (rgb[2], rgb[1], rgb[0]) # Convert RGB → BGR
mask = np.all(img == bgr, axis=2)
img[mask] = (0, 0, 0)
return img
def update_minimap(self):
'''
update_minimap
'''
def run_once(self):
'''
Process with one game window frame
'''
# Get lastest game screen frame buffer
self.frame = self.capture.get_frame()
# Resize game screen to 1296x759
self.img_frame = cv2.resize(self.frame, (1296, 759), interpolation=cv2.INTER_NEAREST)
# Image for debug use
self.img_frame_debug = self.img_frame.copy()
# Get minimap from game window
if self.is_first_frame:
x, y, w, h = get_minimap_loc_size(self.img_frame)
# Discard 1 pixel boundary of the minimap
x += 1
y += 1
w -= 2
h -= 2
self.loc_minimap = (x, y)
self.img_minimap = self.img_frame[y:y+h, x:x+w]
# copy minimap to map
self.img_map = self.img_minimap.copy()
pad = self.cfg.map_scan_padding
self.img_map = cv2.copyMakeBorder(
self.img_map,
top=pad, bottom=pad, left=pad, right=pad,
borderType=cv2.BORDER_CONSTANT,
value=(0, 0, 0) # Black padding
)
# Replace player "yellow" dot to black on map
self.replace_color_on_map(
(55, 40, 80),
(60, 100, 100)
)
# Replace other player "red" dot to black on map
self.replace_color_on_map((0, 80, 80),
(5, 100, 100))
# Update route
self.img_route = self.remove_color_code_pixels(self.img_map.copy())
self.img_route_debug = self.img_route.copy()
else:
x, y = self.loc_minimap
h, w = self.img_minimap.shape[:2]
self.img_minimap = self.img_frame[y:y+h, x:x+w]
# Perform template matching to find where the current minimap fits in the global map
self.loc_minimap_global, score, _ = find_pattern_sqdiff(
self.img_map,
self.img_minimap
)
x, y = self.loc_minimap_global
h, w = self.img_minimap.shape[:2]
# Ensure img_map is big enough to fit the newly explored region
self.ensure_img_map_capacity(x, y, h, w)
# Create mask where img_map is black
map_slice = self.img_map[y:y+h, x:x+w]
black_mask = np.all(map_slice == [0, 0, 0], axis=2)
map_slice[black_mask] = self.img_minimap[black_mask]
# Replace player "yellow" dot to black on map
self.replace_color_on_map(
(55, 40, 80),
(60, 100, 100)
)
# Replace other player "red" dot to black on map
self.replace_color_on_map((0, 80, 80),
(5, 100, 100))
cv2.imshow("Map", self.img_map)
self.img_route_debug = self.img_route.copy()
# Get player location on minimap
loc_player_minimap = get_player_location_on_minimap(self.img_minimap)
if loc_player_minimap:
self.loc_player_minimap = loc_player_minimap
# Get player location on global map
self.loc_player_global = self.get_player_location_on_global_map()
# Determine which color code to use based on user input
action = ""
is_draw_blob = False
key_press = self.kb.key_pressing
if "space" in key_press:
if "left" in key_press:
action = "jump left"
elif "right" in key_press:
action = "jump right"
elif "down" in key_press:
action = "jump down"
else:
action = "jump"
is_draw_blob = True
elif "e" in key_press: # Teleport skill
if "left" in key_press:
action = "teleport left"
elif "right" in key_press:
action = "teleport right"
elif "down" in key_press:
action = "teleport down"
elif "up" in key_press:
action = "teleport up"
else:
action = ""
is_draw_blob = True
elif "up" in key_press:
action = "up"
elif "down" in key_press:
action = "down"
elif "left" in key_press:
action = "walk left"
elif "right" in key_press:
action = "walk right"
else:
action = ""
# Check if need to change route
if self.kb.is_pressed_func_key[2]: # 'F3' is pressed
action = "goal"
is_draw_blob = True
self.kb.is_pressed_func_key[2] = False
elif self.kb.is_pressed_func_key[0]: # 'F1' is pressed
self.is_enable = not self.is_enable
logger.info(f"User press F1, is_enable = {self.is_enable}")
self.kb.is_pressed_func_key[0] = False
# Update route image
if self.is_enable and action != "":
# Get color from action
dict_action_to_color = {v: k for k, v in self.cfg.color_code.items()}
color_rgb = dict_action_to_color.get(action, None)
color_bgr = (color_rgb[2], color_rgb[1], color_rgb[0])
# Draw a line from the last position to the current one (if available)
px, py = self.loc_player_global
if is_draw_blob:
dt = time.time() - self.t_last_draw_blob
if dt > self.cfg.route_recoder_draw_blob_cooldown:
# Draw a small filled circle at current position
cv2.circle(self.img_route,
(px, py),
radius=2,
color=color_bgr,
thickness=-1) # filled circle
self.t_last_draw_blob = time.time()
self.loc_player_global_last = None
else:
if self.loc_player_global_last is None:
px_last, py_last = self.loc_player_global
else:
px_last, py_last = self.loc_player_global_last
cv2.line(self.img_route,
(px_last, py_last),
(px , py),
color=color_bgr,
thickness=1)
self.loc_player_global_last = self.loc_player_global
# Save route image if goal is drawn
if action == "goal":
out_path = f"minimaps/{self.args.new_map}/route{self.idx_routes+1}.png"
cv2.imwrite(out_path, self.img_route)
self.idx_routes += 1
self.img_route = self.img_map.copy()
logger.info(f"Save route image to {out_path}")
# Save img_map to map.png
if self.kb.is_pressed_func_key[3]: # 'F4' is pressed
out_path = f"minimaps/{self.args.new_map}/map.png"
cv2.imwrite(out_path, self.img_map)
self.kb.is_pressed_func_key[3] = False
logger.info(f"Save map image to {out_path}")
#####################
### Debug Windows ###
#####################
# Print text on debug image
self.update_info_on_img_frame_debug()
# Show debug image on window
self.update_img_frame_debug()
# Check if need to save screenshot
if self.kb.is_pressed_func_key[1]: # 'F2' is pressed
screenshot(self.img_frame)
self.kb.is_pressed_func_key[1] = False
# Resize img_route_debug for better visualization
self.img_route_debug = cv2.resize(
self.img_route_debug, (0, 0),
fx=self.cfg.minimap_upscale_factor,
fy=self.cfg.minimap_upscale_factor,
interpolation=cv2.INTER_NEAREST)
cv2.imshow("Route Map Debug", self.img_route_debug)
# Enable cached location since second frame
self.is_first_frame = False
if name == 'main':
parser = argparse.ArgumentParser()
code
# Argument to specify map name
parser.add_argument(
'--new_map',
type=str,
default='new_map',
help='Specify the new map name'
)
try:
routeRecorder = RouteRecorder(parser.parse_args())
except Exception as e:
logger.error(f"RouteRecorder Init failed: {e}")
sys.exit(1)
else:
while True:
t_start = time.time()
# Process one game window frame
routeRecorder.run_once()
# Exit if 'q' is pressed
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
# Cap FPS to save system resource
frame_duration = time.time() - t_start
target_duration = 1.0 / routeRecorder.cfg.fps_limit
if frame_duration < target_duration:
time.sleep(target_duration - frame_duration)
cv2.destroyAllWindows()
code
Each box is expected to be a tuple or list with at least 4 values:
(x1, y1, x2, y2), where:
- (x1, y1) is the top-left corner
- (x2, y2) is the bottom-right corner
Returns:
A float representing the IoU value (0.0 ~ 1.0).
If there is no overlap, returns 0.0.
'''
x1, y1, x2, y2 = box1[:4]
x1_p, y1_p, x2_p, y2_p = box2[:4]
inter_x1 = max(x1, x1_p)
inter_y1 = max(y1, y1_p)
inter_x2 = min(x2, x2_p)
inter_y2 = min(y2, y2_p)
if inter_x2 <= inter_x1 or inter_y2 <= inter_y1:
return 0.0
inter_area = (inter_x2 - inter_x1) * (inter_y2 - inter_y1)
area1 = (x2 - x1) * (y2 - y1)
area2 = (x2_p - x1_p) * (y2_p - y1_p)
union = area1 + area2 - inter_area
return inter_area / union
def screenshot(img, prefix="screenshot"):
'''
Save the given image as a screenshot file.
code
Parameters:
- img: numpy array (image to save).
Behavior:
- Saves the image to the "screenshot/" directory with the current timestamp as filename.
'''
os.makedirs("screenshot", exist_ok=True) # ensure directory exists
# Generate timestamp string
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = f"screenshot/{prefix}_{timestamp}.png"
cv2.imwrite(filename, img)
logger.info(f"Screenshot saved: {filename}")
def draw_rectangle(img, top_left, size, color, text,
thickness=2, text_height=0.7):
'''
Draws a rectangle with an text label.
code
Parameters:
- img: The image on which to draw (numpy array).
- top_left: Tuple (x, y), the top-left corner of the rectangle.
- size: Tuple (height, width) of the rectangle.
- color: Tuple (B, G, R), color of the rectangle and text.
- text: String to display above the rectangle.
'''
bottom_right = (top_left[0] + size[1],
top_left[1] + size[0])
cv2.rectangle(img, top_left, bottom_right, color, thickness)
cv2.putText(img, text, (top_left[0], top_left[1] - 10),
cv2.FONT_HERSHEY_SIMPLEX, text_height, color, thickness)
The function searches for the best matching location of img_pattern inside img.
It automatically converts the pattern to grayscale and generates a mask to ignore
pure white (or near-white) pixels in the template, treating them as transparent background.
Parameters:
- img: Target search image (numpy array), can be grayscale or BGR.
- img_pattern: Template image to search for (numpy array, BGR).
Returns:
- min_loc: The top-left coordinate (x, y) of the best match position.
- min_val: The matching score (lower = better for SQDIFF_NORMED).
- bool: local search success or not
'''
# Padding if img is smaller than pattern
img = pad_to_size(img, img_pattern.shape[:2])
# search last result location first to speedup
h, w = img_pattern.shape[:2]
if last_result is not None and global_threshold > 0.0:
lx, ly = last_result
x0 = max(0, lx - local_search_radius)
y0 = max(0, ly - local_search_radius)
x1 = min(img.shape[1], lx + local_search_radius + w)
y1 = min(img.shape[0], ly + local_search_radius + h)
img_roi = img[y0:y1, x0:x1]
if img_roi.shape[0] >= h and img_roi.shape[1] >= w:
res = cv2.matchTemplate(
img_roi,
img_pattern,
cv2.TM_SQDIFF_NORMED,
mask=mask
)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if min_val < global_threshold:
return (x0 + min_loc[0], y0 + min_loc[1]), min_val, True
# Global fallback
res = cv2.matchTemplate(
img,
img_pattern,
cv2.TM_SQDIFF_NORMED,
mask=mask
)
# Replace -inf/+inf/nan to 1.0 to avoid numerical error
res = np.nan_to_num(res, nan=1.0, posinf=1.0, neginf=1.0)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
return min_loc, min_val, False
def get_minimap_loc_size(img_frame):
'''
Detects the location and size of the minimap within the game frame.
code
The function works by:
- Thresholding the image get pure white(255,255,255) pixels.
- Using connected components to find white-bordered regions.
- Filtering candidates based on expected minimap size and margin rules:
- Top, bottom, left, right margins must be 1px white lines.
Returns:
(x, y, w, h): Top-left coordinate and width/height of the minimap.
Returns None if not found.
'''
white = np.array([255, 255, 255])
# Mask for pure white
mask_white = cv2.inRange(img_frame, white, white)
# Connected components with stats
num_labels, labels, stats, centroids = \
cv2.connectedComponentsWithStats(mask_white, connectivity=8)
# Loop over components (skip label 0, which is background)
for i in range(1, num_labels):
x0, y0, rw, rh, area = stats[i]
# Filter out small blobs
if rw < 100 or rh < 100:
continue
x1 = x0 + rw - 1
y1 = y0 + rh - 1
# Check 1px white top and bottom margins
if not (np.all(img_frame[y0, x0:x0+rw] == white) and \
np.all(img_frame[y1, x0:x0+rw] == white)):
continue
# Check 1px white left and right margins
if not (np.all(img_frame[y0:y0:rh, x0] == white) and \
np.all(img_frame[y0:y0:rh, x1] == white)):
continue
# Create a mask of non-white pixels
mask_minimap = np.any(img_frame[y0:y0+rh, x0:x0+rw] != white, axis=2).astype(np.uint8)
# Find bounding box of mask_minimap
coords = cv2.findNonZero(mask_minimap)
if coords is None:
continue # skip empty block
x_minimap, y_minimap, w_minimap, h_minimap = cv2.boundingRect(coords)
# Offset by original x0, y0 to get coords in original image
x_minimap += x0
y_minimap += y0
return x_minimap, y_minimap, w_minimap, h_minimap
logger.warning("Minimap not found in the game frame.")
return None # minimap not found
def get_player_location_on_minimap(img_minimap, minimap_player_color=(136, 255, 255)):
"""
Detects the player's position on the minimap.
code
The function works by:
- Creating a binary mask of all pixels in the minimap that match the configured
player color exactly.
- Verifying that at least 4 matching pixels are found (to avoid false positives).
- Computing the average of these pixel coordinates to determine the center of
the player icon on the minimap.
Returns:
(x, y): The player's location in minimap coordinates as a tuple.
Returns None if not enough matching pixels are found.
"""
mask = cv2.inRange(img_minimap,
minimap_player_color,
minimap_player_color)
coords = cv2.findNonZero(mask)
if coords is None or len(coords) < 4:
logger.warning(f"Fail to locate player location on minimap.")
return None
# Calculate the average location of the matching pixels
avg = coords.mean(axis=0)[0] # shape (1,2), so we take [0]
loc_player_minimap = (int(round(avg[0])), int(round(avg[1])))
return loc_player_minimap
def get_bar_ratio(img):
'''
Get HP/MP/EXP bar ratio with given bar image
code
Return: float [0.0 - 1.0]
'''
# Sample a horizontal line at the vertical center of the bar
h, w = img.shape[:2]
line_pixels = img[h // 2, :]
# Get left white boundary of bar
lb = 0
while lb < w and np.all(line_pixels[lb] >= 255):
lb += 1
# Get right white boundary of bar
rb = w - 1
while rb > lb and np.all(line_pixels[rb] >= 255):
rb -= 1
# Sanity check
if rb <= lb:
return 0.0
# Get unfill pixel count in bar
unfill_pixel_cnt = 0
tolerance = 10
for i in range(lb, rb + 1):
r, g, b = line_pixels[i]
if abs(int(r) - int(g)) <= tolerance and \
abs(int(r) - int(b)) <= tolerance and \
int(r) > 0:
unfill_pixel_cnt += 1
# Compute fill ratio
total_width = rb - lb + 1
fill_width = total_width - unfill_pixel_cnt
fill_ratio = fill_width / total_width if total_width > 0 else 0.0
return fill_ratio
# Key to trigger AoE skill (e.g., Monk's AoE heal or Mage's AoE attack).
aoe_skill_key = "q"
# Key to trigger the basic attack skill, like Mage's Magic Claw.
magic_claw_key = "w"
# Key to trigger Mage's teleport skill
teleport_key = "" # set to "", if need to disable teleport skill
# Key for jumping.
jump_key = "space"
# Key to use a health potion.
heal_key = "1"
# Key to use a mana potion.
add_mp_key = "2"
# ────────────────
# Buff skill
# ────────────────
# Buff skill keys, e.g., magical sheild, angel blessing
buff_skill_keys = []
buff_skill_cooldown = [] # Second
buff_skill_active_duration = 1 # second
buff_skill_action_cooldown = 1 # second, avoid cast buff skill after attack
# ────────────────
# System
# ────────────────
# FPS(Frame per Second) limit for main thread
fps_limit = 10
show_debug_window = True # False, disable debug window to save system resource
# ────────────────
# Mage Teleport
# ────────────────
# WIP feature
# whether to activate Mage's teleport skill while walking
is_use_teleport_to_walk = False
# Mage's teleport skill cooldown
teleport_cooldown = 1 # second
# ────────────────
# Edge Teleport
# ────────────────
# Mage can use teleport skill if they're too close to edge
is_edge_teleport = True
edge_teleport_box_width = 20
edge_teleport_box_height = 10
edge_teleport_color_code = (255,127,127) # (R,G,B)
# ────────────────
# NameTag Recongnition
# ────────────────
# offset from the nametag's top-left corner to the player's center
nametag_offset = (-50, 30) # pixel
nametag_diff_thres = 0.2
# Nametag template matching threshold.
# If the matching diff is smaller than <nametag_global_thres>
# it will only search area near the last frame nametag.
# If diff is bigger than <nametag_global_thres>, it will search the whole frame
# and get the best match.
# If you find the nametag is cached, but the location is incorrect.
# Disable this feature by setting nametag_global_thres = 0.0
nametag_global_thres = 0.2
nametag_split_width = 30 # pixel, vertically split nametag
nametag_detection_mode = "grayscale" # "grayscale", "white_mask"
# ────────────────
# Camera
# ────────────────
# only use this vertical range of the screen to localize camera on map
camera_ceiling = 60 # pixel (top)
camera_floor = 665 # pixel (bottom)
# ────────────────
# Attack Settings
# ────────────────
# aoe skill attack range relative to player position
aoe_skill_range_x = 400 # pixels (horizontal range)
aoe_skill_range_y = 170 # pixels (vertical range)
# magic claw skill attack range relative to player position
magic_claw_range_x = 350 # pixels (horizontal range)
magic_claw_range_y = 70 # pixels (vertical range)
# attack cooldown time in seconds
attack_cooldown = 0.05 # seconds between attacks
# character turn delay before attack
character_turn_delay = 0.02 # seconds to wait for character to turn before attacking
# ────────────────
# Monster Detection
# ────────────────
monster_diff_thres = 0.8 # 0.8 # template match similarity threshold
monster_search_margin = 50 # extra margin around attack box for monster search
blur_range = 5
monster_detect_mode = "contour_only" # "contour_only" "color", "grayscale" "template_free"
monster_detect_with_health_bar = True
monster_health_bar_color = (71,204,64) # (B,G,R)
character_width = 100
character_height = 150
# ────────────────
# Route Detection (color code)
# ────────────────
color_code_search_range = 10 # radius to find nearest color route from player center
# ────────────────
# Movement Behavior
# ────────────────
up_drag_duration = 1.0 # hold duration for 'up' key to prevent rope-sticking (in seconds)
down_drag_duration = 1.0 # seconds
watch_dog_timeout = 10 # seconds, if player doesn't move for 3 second, random perform an action
watch_dog_range = 10 # pixel, if player location is smaller than watch_dog_range, consider it doesn't move
# ────────────────
# Runes Warning
# ────────────────
rune_warning_top_left = (513, 196)
rune_warning_bottom_right = (768, 236)
rune_warning_diff_thres = 0.2
# ────────────────
# Rune Detection
# ────────────────
rune_detect_box_width = 120
rune_detect_box_height = 150
rune_detect_diff_thres = 0.1
rune_finding_timeout = 1200 # second
rune_detect_level_coef = 0.1 # raise threshold for each level
rune_detect_level_raise_interval = 60 # second
near_rune_duration = 5 # second
# ────────────────
# Rune mini-game
# ────────────────
arrow_box_size = 80 # pixel, 75x75 box
arrow_box_interval = 170 # pixel width
arrow_box_start_point = (355, 355)
arrow_box_diff_thres = 0.2
# ────────────────
# HP Bar and HP bar
# ────────────────
heal_ratio = 0.5 # heal when hp is below 50%
add_mp_ratio = 0.5 # drink potion when mp is below 50%
# Health monitor cooldowns (to prevent spam)
heal_cooldown = 0.5 # seconds between heals
mp_cooldown = 0.5 # seconds between MP potions
# ────────────────
# Mini-Map
# ────────────────
minimap_upscale_factor = 4 # upscale 4 time for debug route image
minimap_player_color = (136, 255, 255) # BGR
# ────────────────
# Patrol Mode
# ────────────────
patrol_range = [0.2, 0.8] # 0.0 - 1.0, 0.0 means the left boarder of game window
# 1.0 means the right boarder of game window
turn_point_thres = 10 # 10 frames
patrol_attack_interval = 2.5 # sec, attack every 2.5 second
# ────────────────
# Map Scan
# ────────────────
map_scan_padding = 30 # pixel, How width the black margin on map
# ────────────────
# Route recoder
# ────────────────
route_recoder_draw_blob_cooldown = 0.7 # second, can only draw blob for every 0.7 second
# ────────────────
# Don't modify the following parameter unless you know what you are doing
# ────────────────
game_window_title = 'MapleStory Worlds-Artale (繁體中文版)'
# color code for patrol route
color_code = {
# R G B
(255, 0, 0): "walk left", # red
(0, 0, 255): "walk right", # blue
(255,127,0): "jump left", # orange
(0,255,255): "jump right", # sky blue
(127,255,0): "jump down", # light_green
(255,0,255): "jump", # purple
(127,127,127): "up", # gray
(255,255,127): "down", # light_yellow
(0,255,127): "stop", # pink_green
(255,255,0): "goal", # yellow
(255,0,127): "teleport up", # pink
(127,0,255): "teleport down", # light_purple
(0, 127, 0): "teleport left", # dark green
(139, 69, 19): "teleport right" # brown
}
window_size = (752, 1282)
# Health monitoring state
self.hp_ratio = 1.0
self.mp_ratio = 1.0
self.exp_ratio = 1.0
# Timers
self.last_heal_time = 0
self.last_mp_time = 0
self.last_hp_reduce_time = 0
self.t_last_run = 0
# Frame data (will be updated by main thread)
self.img_frame = None
self.frame_lock = threading.Lock()
self.fps_limit = self.cfg["health_monitor"]["fps_limit"]
self.fps = 0
# Debug information
# hp/mp/exp bars loc and size, [(x,y,w,h), ...]
self.loc_size_bars = [(0, 0, 0, 0),
(0, 0, 0, 0),
(0, 0, 0, 0)]
def start(self):
'''
Start health monitoring thread
'''
if not self.running:
self.running = True
self.thread = threading.Thread(target=self._monitor_loop, daemon=True)
self.thread.start()
logger.info("[Health Monitor]: Started")
def stop(self):
'''
Stop health monitoring thread
'''
self.running = False
if self.thread:
self.thread.join()
logger.info("[Health Monitor]: Stopped")
def enable(self):
'''
Enable health monitoring
'''
self.enabled = True
def disable(self):
'''
Disable health monitoring
'''
self.enabled = False
def update_frame(self, img_frame):
'''
Update frame data from main thread
'''
with self.frame_lock:
self.img_frame = img_frame
def get_hp_mp_exp_ratio(self):
'''
Extracts the player's HP, MP, and EXP ratios from game frame.
This function:
- Crops the predefined HP, MP, and EXP bar regions from the game frame.
- Identifies empty areas in each bar.
- Computes the fill ratio for each bar as: 1 - (empty_pixels / total_pixels).
Returns:
tuple: (hp_ratio, mp_ratio, exp_ratio), each a float between 0 and 1.
'''
if self.img_frame is None:
return None, None, None
with self.frame_lock:
img_frame = self.img_frame.copy()
img_frame_gray = cv2.cvtColor(img_frame, cv2.COLOR_BGR2GRAY)
white_mask = cv2.inRange(img_frame_gray, 240, 255)
# cv2.imshow("white_mask", white_mask)
contours, _ = cv2.findContours(white_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
loc_size_bars = []
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
# for game window resolution 752x1282, w/h == 7.5, w*h == 3630
if 4 < w/h < 10 and 2500 < w*h < 5000:
loc_size_bars.append((x, y, w, h))
# sort contours by x coordinate
loc_size_bars = sorted(loc_size_bars, key=lambda bar: bar[0])
if len(loc_size_bars) != 3:
logger.warning(f"[Health Monitor]: HP/MP/EXP bar detection has an unexpected result:{loc_size_bars}")
return (None, None, None)
# Update loc_size_bars
self.loc_size_bars = loc_size_bars
# Get bar filled ratio
ratio_bars = []
for x, y, w, h in loc_size_bars:
ratio_bars.append(get_bar_ratio(img_frame[y:y+h, x:x+w]))
return ratio_bars
def get_hp_mp_ratio_legacy(self):
'''
Deprecated: This hp/mp bar detection method require specific window resolution as input
and use hard-coded pixel coordinate to capture hp/mp bar
This function is replaced by get_hp_mp_exp_ratio() which is more flexiable and
can work on different window resolution
Extract HP and MP ratios from current frame
'''
if self.img_frame is None:
return 1.0, 1.0
with self.frame_lock:
img_frame = self.img_frame.copy()
# HP crop
hp_bar = img_frame[self.cfg.hp_bar_top_left[1]:self.cfg.hp_bar_bottom_right[1]+1,
self.cfg.hp_bar_top_left[0]:self.cfg.hp_bar_bottom_right[0]+1]
# MP crop
mp_bar = img_frame[self.cfg.mp_bar_top_left[1]:self.cfg.mp_bar_bottom_right[1]+1,
self.cfg.mp_bar_top_left[0]:self.cfg.mp_bar_bottom_right[0]+1]
# HP Detection (detect empty part)
empty_mask_hp = (hp_bar[:,:,0] == hp_bar[:,:,1]) & (hp_bar[:,:,0] == hp_bar[:,:,2])
empty_pixels_hp = max(0, len(empty_mask_hp[empty_mask_hp]) - 6) # 6 pixel always be white
total_pixels_hp = hp_bar.shape[0] * hp_bar.shape[1] - 6
hp_ratio = 1 - (empty_pixels_hp / max(1, total_pixels_hp))
# MP Detection (detect empty part)
empty_mask_mp = (mp_bar[:,:,0] == mp_bar[:,:,1]) & (mp_bar[:,:,0] == mp_bar[:,:,2])
empty_pixels_mp = max(0, len(empty_mask_mp[empty_mask_mp]) - 6) # 6 pixel always be white
total_pixels_mp = mp_bar.shape[0] * mp_bar.shape[1] - 6
mp_ratio = 1 - (empty_pixels_mp / max(1, total_pixels_mp))
return max(0, min(1, hp_ratio)), max(0, min(1, mp_ratio))
def _monitor_loop(self):
'''
Main monitoring loop running in separate thread
'''
while self.running:
try:
if not self.enabled or self.args.disable_control:
self.limit_fps()
continue
# Get current HP/MP ratios
hp_ratio, mp_ratio, exp_ratio = self.get_hp_mp_exp_ratio()
if hp_ratio is not None:
# Check if HP bar has reduced
if self.hp_ratio > hp_ratio:
self.last_hp_reduce_time = time.time()
self.hp_ratio = hp_ratio
if mp_ratio is not None:
self.mp_ratio = mp_ratio
if exp_ratio is not None:
self.exp_ratio = exp_ratio
current_time = time.time()
# Check if need to heal (with cooldown)
if self.cfg["health_monitor"]["force_heal"]:
# Ignore cooldown and force keycontroller to heal first
if (self.hp_ratio <= self.cfg["health_monitor"]["add_hp_ratio"]):
self.kb.is_need_force_heal = True
logger.info(f"[Health Monitor]: Force heal triggered, HP: {self.hp_ratio*100:.1f}%")
else:
self.kb.is_need_force_heal = False
else:
if (self.hp_ratio <= self.cfg["health_monitor"]["add_hp_ratio"] and
current_time - self.last_heal_time > self.cfg["health_monitor"]["add_hp_cooldown"]):
self._heal()
logger.info(f"[Health Monitor]: Auto heal triggered, HP: {self.hp_ratio*100:.1f}%")
self.last_heal_time = current_time
# Check if need MP (with cooldown)
if (self.mp_ratio <= self.cfg["health_monitor"]["add_mp_ratio"] and
current_time - self.last_mp_time > self.cfg["health_monitor"]["add_mp_cooldown"]):
self._add_mp()
self.last_mp_time = current_time
logger.info(f"[Health Monitor]: Auto MP triggered, MP: {self.mp_ratio*100:.1f}%")
# Sleep to avoid excessive CPU usage
self.limit_fps()
except Exception as e:
logger.error(f"[Health Monitor]: {e}")
self.limit_fps()
def _heal(self):
'''
Execute heal action
'''
try:
self.kb.press_key(self.cfg["key"]["add_hp"], 0.05)
except Exception as e:
logger.error(f"[Health Monitor]: Heal action failed: {e}")
def _add_mp(self):
'''
Execute MP recovery action
'''
try:
self.kb.press_key(self.cfg["key"]["add_mp"], 0.05)
except Exception as e:
logger.error(f"[Health Monitor]: MP action failed: {e}")
def limit_fps(self):
'''
Limit FPS
'''
# If the loop finished early, sleep to maintain target FPS
target_duration = 1.0 / self.fps_limit # seconds per frame
frame_duration = time.time() - self.t_last_run
if frame_duration < target_duration:
time.sleep(target_duration - frame_duration)
# Update FPS
self.fps = round(1.0 / (time.time() - self.t_last_run))
self.t_last_run = time.time()
# logger.info(f"FPS = {self.fps}")
# Load defautl yaml config
cfg = load_yaml("config/config_default.yaml")
# Override with platform config
if is_mac():
cfg = override_cfg(cfg, load_yaml("config/config_macOS.yaml"))
# Override with user customized config
self.cfg = override_cfg(cfg, load_yaml(f"config/config_{args.cfg}.yaml"))
# Parse color code
self.color_code = {
tuple(map(int, k.split(','))): v
for k, v in cfg["route"]["color_code"].items()
}
# Set status to hunting for startup
self.switch_status("hunting")
if args.patrol:
# Patrol mode doesn't need map or route
self.img_map = None
self.img_routes = []
self.img_route_rest = None
else:
# Load map.png from minimaps/
self.img_map = load_image(f"minimaps/{args.map}/map.png",
cv2.IMREAD_COLOR)
# Load route*.png from minimaps/
route_files = sorted(glob.glob(f"minimaps/{args.map}/route*.png"))
route_files = [p for p in route_files if not p.endswith("route_rest.png")]
self.img_routes = [
cv2.cvtColor(load_image(p), cv2.COLOR_BGR2RGB) for p in route_files
]
# Load route_rest.png from minimaps/
self.img_route_rest = cv2.cvtColor(
load_image(f"minimaps/{args.map}/route_rest.png"), cv2.COLOR_BGR2RGB)
# Load player's name tag
self.img_nametag = load_image(f"nametag/{args.nametag}.png")
self.img_nametag_gray = load_image(f"nametag/{args.nametag}.png", cv2.IMREAD_GRAYSCALE)
# Load rune images from rune/
self.img_rune_warning = load_image("rune/rune_warning.png", cv2.IMREAD_GRAYSCALE)
self.img_runes = [load_image("rune/rune_1.png"),
load_image("rune/rune_2.png"),
load_image("rune/rune_3.png"),]
self.img_arrows = {
"left":
[load_image("rune/arrow_left_1.png"),
load_image("rune/arrow_left_2.png"),
load_image("rune/arrow_left_3.png"),],
"right":
[load_image("rune/arrow_right_1.png"),
load_image("rune/arrow_right_2.png"),
load_image("rune/arrow_right_3.png"),],
"up":
[load_image("rune/arrow_up_1.png"),
load_image("rune/arrow_up_2.png"),
load_image("rune/arrow_up_3.png")],
"down":
[load_image("rune/arrow_down_1.png"),
load_image("rune/arrow_down_2.png"),
load_image("rune/arrow_down_3.png"),],
}
# Load monsters images from monster/{monster_name}
self.monsters = {}
for monster_name in args.monsters.split(","):
imgs = []
for file in glob.glob(f"monster/{monster_name}/{monster_name}*.png"):
# Add original image
img = load_image(file)
imgs.append((img, get_mask(img, (0, 255, 0))))
# Add flipped image
img_flip = cv2.flip(img, 1)
imgs.append((img_flip, get_mask(img_flip, (0, 255, 0))))
if imgs:
self.monsters[monster_name] = imgs
else:
logger.error(f"No images found in monster/{monster_name}/{monster_name}*")
raise RuntimeError(f"No images found in monster/{monster_name}/{monster_name}*")
logger.info(f"Loaded monsters: {list(self.monsters.keys())}")
# Start keyboard controller thread
self.kb = KeyBoardController(self.cfg, args)
if args.disable_control:
self.kb.disable()
# Start game window capturing thread
logger.info("Waiting for game window to activate, please click on game window")
self.capture = GameWindowCapturor(self.cfg)
# Start health monitoring thread
self.health_monitor = HealthMonitor(self.cfg, args, self.kb)
if self.cfg["health_monitor"]["enable"]:
self.health_monitor.start()
def get_player_location_by_nametag(self):
'''
Detects the player's location based on the nametag position in the game window.
This function works by:
- Extracting a vertical region of interest (ROI) where the nametag is expected.
- Padding the ROI to avoid template matching edge issues.
- Using template matching to locate the nametag, split into left and right halves
to improve robustness against partial occlusion.
- Selecting the best match (left or right) based on score and cache status.
- Computing the player's center position by applying a fixed offset to the nametag.
Returns:
loc_player (tuple): The (x, y) coordinates of the player's estimated location.
'''
# Get camera region in the game window
img_camera = self.img_frame_gray[
self.cfg["camera"]["y_start"]:self.cfg["camera"]["y_end"], :]
# Get nametag image and search image
if self.cfg["nametag"]["mode"] == "white_mask":
# Apply Gaussian blur for smoother white detection
img_camera = cv2.GaussianBlur(img_camera, (3, 3), 0)
img_nametag = cv2.GaussianBlur(self.img_nametag_gray, (3, 3), 0)
lower_white, upper_white = (150, 255)
img_roi = cv2.inRange(img_camera, lower_white, upper_white)
img_nametag = cv2.inRange(img_nametag, lower_white, upper_white)
elif self.cfg["nametag"]["mode"] == "grayscale":
img_roi = img_camera
img_nametag = self.img_nametag_gray
else:
logger.error(f"Unsupported nametag detection mode: {self.cfg["nametag"]["mode"]}")
return
# cv2.imshow("img_roi", img_roi)
# cv2.imshow("img_nametag", img_nametag)
# Pad search region to deal with fail detection when player is at map edge
(pad_y, pad_x) = self.img_nametag.shape[:2]
img_roi = cv2.copyMakeBorder(
img_roi,
pad_y, pad_y, pad_x, pad_x,
borderType=cv2.BORDER_REPLICATE # replicate border for safe matching
)
# Get last frame name tag location
if self.is_first_frame:
last_result = None
else:
last_result = (
self.loc_nametag[0] + pad_x,
self.loc_nametag[1] + pad_y - self.cfg["camera"]["y_start"]
)
# Get number of splits
h, w = img_nametag.shape
num_splits = max(1, w // self.cfg["nametag"]["split_width"])
w_split = w // num_splits
# Get nametag's background mask
mask = get_mask(self.img_nametag, (0, 255, 0))
# Vertically split the nametag image
nametag_splits = {}
for i in range(num_splits):
x_s = i * w_split
x_e = (i + 1) * w_split if i < num_splits - 1 else w
nametag_splits[f"{i+1}/{num_splits}"] = {
"img": img_nametag[:, x_s:x_e],
"mask": mask[:, x_s:x_e],
"last_result": (
(last_result[0] + x_s, last_result[1]) if last_result else None
),
"score_penalty": 0.0,
"offset_x": x_s
}
# Match tempalte
matches = []
for tag_type, split in nametag_splits.items():
loc, score, is_cached = find_pattern_sqdiff(
img_roi,
split["img"],
last_result=split["last_result"],
mask=split["mask"],
global_threshold=self.cfg["nametag"]["global_diff_thres"]
)
w_match = split["img"].shape[1]
h_match = split["img"].shape[0]
score += split["score_penalty"]
matches.append((tag_type, loc, score, w_match, h_match, is_cached, split["offset_x"]))
# Select best match and fix offset:
matches.sort(key=lambda x: (not x[5], x[2])) # prefer cached, then low score
tag_type, loc_nametag, score, w_match, h_match, is_cached, offset_x = matches[0]
# Adjust match location back to full nametag coordinates
loc_nametag = (loc_nametag[0] - offset_x, loc_nametag[1])
loc_nametag = (
loc_nametag[0] - pad_x,
loc_nametag[1] - pad_y + self.cfg["camera"]["y_start"]
)
# Only update nametag location when score is good enough
if score < self.cfg["nametag"]["diff_thres"]:
self.loc_nametag = loc_nametag
loc_player = (
self.loc_nametag[0] - self.cfg["nametag"]["offset"][0],
self.loc_nametag[1] - self.cfg["nametag"]["offset"][1]
)
# Draw name tag detection box for debugging
draw_rectangle(self.img_frame_debug, self.loc_nametag,
self.img_nametag.shape, (0, 255, 0), "")
text = f"NameTag,{round(score, 2)}," + \
f"{'cached' if is_cached else 'missed'}," + \
f"{tag_type}"
cv2.putText(self.img_frame_debug, text,
(self.loc_nametag[0],
self.loc_nametag[1] + self.img_nametag.shape[0] + 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
# Draw player center for debugging
cv2.circle(self.img_frame_debug,
loc_player, radius=3,
color=(0, 0, 255), thickness=-1)
return loc_player
def get_player_location_on_global_map(self):
'''
get_player_location_on_global_map
'''
self.loc_minimap_global, score, _ = find_pattern_sqdiff(
self.img_map,
self.img_minimap)
loc_player_global = (
self.loc_minimap_global[0] + self.loc_player_minimap[0],
self.loc_minimap_global[1] + self.loc_player_minimap[1]
)
# Draw local minimap rectangle
camera_bottom_right = (
self.loc_minimap_global[0] + self.img_minimap.shape[1],
self.loc_minimap_global[1] + self.img_minimap.shape[0]
)
cv2.rectangle(self.img_route_debug, self.loc_minimap_global,
camera_bottom_right, (0, 255, 255), 1)
cv2.putText(
self.img_route_debug,
f"Minimap,score({round(score, 2)})",
(self.loc_minimap_global[0], self.loc_minimap_global[1]+15),
cv2.FONT_HERSHEY_SIMPLEX, 0.4,
(0, 255, 255), 1
)
# Draw player center
cv2.circle(self.img_route_debug,
loc_player_global, radius=2,
color=(0, 255, 255), thickness=-1)
return loc_player_global
def get_nearest_color_code(self):
'''
Searches for the nearest color-coded action marker
around the player on the route map.
This function:
- Scans each pixel in the search box to find nearest color code
- Tracks the closest matching pixel using Manhattan distance (|dx| + |dy|).
- Returns a dictionary containing the nearest matching
pixel's position, color, action label, and distance.
Returns:
dict or None: Dictionary containing:
- "pixel": (x, y) coordinate of the matched pixel
- "color": matched RGB color tuple
- "action": corresponding action string from config
- "distance": Manhattan distance from player
Returns None if no matching color is found within the region.
'''
x0, y0 = self.loc_player_global
h, w = self.img_route.shape[:2]
x_min = max(0, x0 - self.cfg["route"]["search_range"])
x_max = min(w, x0 + self.cfg["route"]["search_range"])
y_min = max(0, y0 - self.cfg["route"]["search_range"])
y_max = min(h, y0 + self.cfg["route"]["search_range"])
nearest = None
min_dist = float('inf')
for y in range(y_min, y_max):
for x in range(x_min, x_max):
pixel = tuple(self.img_route[y, x]) # (R, G, B)
if pixel in self.color_code:
dist = abs(x - x0) + abs(y - y0)
if dist < min_dist:
min_dist = dist
nearest = {
"pixel": (x, y),
"color": pixel,
"action": self.color_code[pixel],
"distance": dist
}
# Debug
draw_rectangle(
self.img_route_debug,
(x_min, y_min),
(self.cfg["route"]["search_range"]*2,
self.cfg["route"]["search_range"]*2),
(0, 0, 255), "", text_height=0.4, thickness=1,
)
# Draw a straigt line from map_loc_player to color_code["pixel"]
if nearest is not None:
cv2.line(
self.img_route_debug,
self.loc_player_global, # start point
nearest["pixel"], # end point
(0, 255, 0), # green line
1 # thickness
)
# Print color code on debug image
cv2.putText(
self.img_frame_debug, f"Route Action: {nearest['action']}",
(720, 90),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
cv2.putText(
self.img_frame_debug, f"Route Index: {self.idx_routes}",
(720, 120),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
return nearest # if not found return none
def get_nearest_monster(self, is_left = True, overlap_threshold=0.5):
'''
Finds the nearest monster within the player's attack range.
This function:
- Defines an attack box relative to the player position,
depending on the facing direction (`is_left`).
- Iterates through all detected monsters and checks which ones overlap
with the attack box.
- Returns the closest valid monster that meets the overlap criteria.
Args:
is_left (bool): If True, assume the player is facing left;
adjusts attack box accordingly.
overlap_threshold (float): Minimum IoU area ratio required to consider a hit.
Returns:
dict or None: The nearest monster's info dict, or None if no valid match.
'''
# Get attack box
if self.args.attack == "aoe_skill":
dx = self.cfg["aoe_skill"]["range_x"] // 2
dy = self.cfg["aoe_skill"]["range_y"] // 2
x0 = max(0, self.loc_player[0] - dx)
x1 = min(self.img_frame.shape[1], self.loc_player[0] + dx)
y0 = max(0, self.loc_player[1] - dy)
y1 = min(self.img_frame.shape[0], self.loc_player[1] + dy)
elif self.args.attack == "directional":
if is_left:
x0 = self.loc_player[0] - self.cfg["directional_attack"]["range_x"]
x1 = self.loc_player[0]
else:
x0 = self.loc_player[0]
x1 = x0 + self.cfg["directional_attack"]["range_x"]
y0 = self.loc_player[1] - self.cfg["directional_attack"]["range_y"] // 2
y1 = y0 + self.cfg["directional_attack"]["range_y"]
else:
logger.error(f"Unsupported attack mode: {self.args.attack}")
return None
# Draw attack box on debug window
draw_rectangle(
self.img_frame_debug, (x0, y0),
(y1-y0, x1-x0),
(0, 0, 255), "Attack Range"
)
nearest_monster = None
min_distance = float('inf')
for monster in self.monster_info:
mx1, my1 = monster["position"]
mw, mh = monster["size"]
mx2 = mx1 + mw
my2 = my1 + mh
# Calculate intersection
ix1 = max(x0, mx1)
iy1 = max(y0, my1)
ix2 = min(x1, mx2)
iy2 = min(y1, my2)
iw = max(0, ix2 - ix1)
ih = max(0, iy2 - iy1)
inter_area = iw * ih
monster_area = mw * mh
if monster_area == 0:
continue # skip degenerate box
if inter_area/monster_area >= overlap_threshold:
# Compute distance to player center
monster_center = (mx1 + mw // 2, my1 + mh // 2)
dx = monster_center[0] - self.loc_player[0]
dy = monster_center[1] - self.loc_player[1]
distance = abs(dx) + abs(dy) # Manhattan distance
if distance < min_distance:
min_distance = distance
nearest_monster = monster
return nearest_monster
def get_monsters_in_range(self, top_left, bottom_right):
'''
get_monsters_in_range
'''
x0, y0 = top_left
x1, y1 = bottom_right
img_roi = self.img_frame[y0:y1, x0:x1]
monster_info = []
for monster_name, monster_imgs in self.monsters.items():
for img_monster, mask_monster in monster_imgs:
if self.args.patrol:
pass # Don't detect monster using template in patrol mode
elif self.cfg["monster_detect"]["mode"] == "template_free":
# Generate mask where pixel is exactly (0,0,0)
black_mask = np.all(img_roi == [0, 0, 0], axis=2).astype(np.uint8) * 255
cv2.imshow("Black Pixel Mask", black_mask)
# Shift player's location into ROI coordinate system
px, py = self.loc_player
px_in_roi = px - x0
py_in_roi = py - y0
# Define rectangle range around player (in ROI coordinate)
char_x_min = max(0, px_in_roi - self.cfg["character"]["width"] // 2)
char_x_max = min(img_roi.shape[1], px_in_roi + self.cfg["character"]["width"] // 2)
char_y_min = max(0, py_in_roi - self.cfg["character"]["height"] // 2)
char_y_max = min(img_roi.shape[0], py_in_roi + self.cfg["character"]["height"] // 2)
# Zero out mask inside this region (ignore player's own character)
black_mask[char_y_min:char_y_max, char_x_min:char_x_max] = 0
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (20, 20))
closed_mask = cv2.morphologyEx(black_mask, cv2.MORPH_CLOSE, kernel)
# cv2.imshow("Black Mask", closed_mask)
# draw player character bounding box
draw_rectangle(
self.img_frame_debug, (char_x_min+x0, char_y_min+y0),
(self.cfg["character"]["height"], self.cfg["character"]["width"]),
(255, 0, 0), "Character Box"
)
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(closed_mask, connectivity=8)
monster_info = []
min_area = 1000
for i in range(1, num_labels):
x, y, w, h, area = stats[i]
if area > min_area:
monster_info.append({
"name": "",
"position": (x0+x, y0+y),
"size": (h, w),
"score": 1.0,
})
elif self.cfg["monster_detect"]["mode"] == "contour_only":
# Use only black lines contour to detect monsters
# Create masks (already grayscale)
mask_pattern = np.all(img_monster == [0, 0, 0], axis=2).astype(np.uint8) * 255
mask_roi = np.all(img_roi == [0, 0, 0], axis=2).astype(np.uint8) * 255
# Apply Gaussian blur (soften the masks)
blur = self.cfg["monster_detect"]["contour_blur"]
img_monster_blur = cv2.GaussianBlur(mask_pattern, (blur, blur), 0)
img_roi_blur = cv2.GaussianBlur(mask_roi, (blur, blur), 0)
# Check template vs ROI size before matching
h_roi, w_roi = img_roi_blur.shape[:2]
h_temp, w_temp = img_monster_blur.shape[:2]
if h_temp > h_roi or w_temp > w_roi:
return [] # template bigger than roi, skip this matching
# Perform template matching
res = cv2.matchTemplate(img_roi_blur, img_monster_blur, cv2.TM_SQDIFF_NORMED)
# Apply soft threshold
match_locations = np.where(res <= self.cfg["monster_detect"]["diff_thres"])
h, w = img_monster.shape[:2]
for pt in zip(*match_locations[::-1]):
monster_info.append({
"name": monster_name,
"position": (pt[0] + x0, pt[1] + y0),
"size": (h, w),
"score": res[pt[1], pt[0]],
})
elif self.cfg["monster_detect"]["mode"] == "grayscale":
img_monster_gray = cv2.cvtColor(img_monster, cv2.COLOR_BGR2GRAY)
img_roi_gray = cv2.cvtColor(img_roi, cv2.COLOR_BGR2GRAY)
res = cv2.matchTemplate(
img_roi_gray,
img_monster_gray,
cv2.TM_SQDIFF_NORMED,
mask=mask_monster)
match_locations = np.where(res <= self.cfg["monster_detect"]["diff_thres"])
h, w = img_monster.shape[:2]
for pt in zip(*match_locations[::-1]):
monster_info.append({
"name": monster_name,
"position": (pt[0] + x0, pt[1] + y0),
"size": (h, w),
"score": res[pt[1], pt[0]],
})
elif self.cfg["monster_detect"]["mode"] == "color":
res = cv2.matchTemplate(
img_roi,
img_monster,
cv2.TM_SQDIFF_NORMED,
mask=mask_monster)
match_locations = np.where(res <= self.cfg["monster_detect"]["diff_thres"])
h, w = img_monster.shape[:2]
for pt in zip(*match_locations[::-1]):
monster_info.append({
"name": monster_name,
"position": (pt[0] + x0, pt[1] + y0),
"size": (h, w),
"score": res[pt[1], pt[0]],
})
else:
logger.error(f"Unexpected camera localization mode: {self.cfg["monster_detect"]["mode"]}")
return []
# Apply Non-Maximum Suppression to monster detection
monster_info = nms(monster_info, iou_threshold=0.4)
# Detect monster via health bar
if self.cfg["monster_detect"]["with_enemy_hp_bar"]:
# Create color mask for Monsters' HP bar
mask = cv2.inRange(img_roi,
np.array(self.cfg["monster_detect"]["hp_bar_color"]),
np.array(self.cfg["monster_detect"]["hp_bar_color"]))
# Find connected components (each cluster of green pixels)
num_labels, labels, stats, centroids = \
cv2.connectedComponentsWithStats(mask, connectivity=8)
for i in range(1, num_labels): # skip background (label 0)
x, y, w, h, area = stats[i]
if area < 3: # small noise filter
continue
# Guess a monster bounding box
y += 10
x = max(0, x)
y = max(0, y)
w = 70
h = 70
monster_info.append({
"name": "Health Bar",
"position": (x0 + x, y0 + y),
"size": (h, w),
"score": 1.0,
})
# Debug
# Draw attack detection range
draw_rectangle(
self.img_frame_debug, (x0, y0), (y1-y0, x1-x0),
(255, 0, 0), "Monster Detection Box"
)
# Draw monsters bounding box
for monster in monster_info:
if monster["name"] == "Health Bar":
color = (0, 255, 255)
else:
color = (0, 255, 0)
draw_rectangle(
self.img_frame_debug, monster["position"], monster["size"],
color, str(round(monster['score'], 2))
)
return monster_info
def switch_status(self, new_status):
'''
Switch to new status and log the transition.
Parameters:
- new_status: string, the new status to switch to.
'''
# Ignore dummy transition
if self.status == new_status:
return
t_elapsed = round(time.time() - self.t_last_switch_status)
logger.info(f"[switch_status] From {self.status}({t_elapsed} sec) to {new_status}.")
self.status = new_status
self.t_last_switch_status = time.time()
def solve_rune(self):
'''
Automatically solves the rune puzzle mini-game by recognizing directional arrows
on the screen and simulating the correct key presses.
This function:
- Continuously checks whether the rune game is active.
- For each of the 4 arrows:
- Compares the cropped image with all known arrow templates.
- Selects the best-matching arrow direction.
- Simulates a key press corresponding to the detected arrow direction.
- Repeats until the rune game ends.
Note:
- Skips key press simulation if `--disable_control` flag is set.
Returns:
None
'''
while self.is_in_rune_game():
for arrow_idx in [0,1,2,3]:
# Get lastest game screen frame buffer
self.frame = self.capture.get_frame()
# Resize game screen to 1296x759
self.img_frame = cv2.resize(self.frame, (1296, 759),
interpolation=cv2.INTER_NEAREST)
# Crop arrow detection box
x0, y0 = self.cfg["rune_solver"]["arrow_box_coord"]
x = x0 + self.cfg["rune_solver"]["arrow_box_interval"] * arrow_idx
y = y0
size = self.cfg["rune_solver"]["arrow_box_size"]
img_roi = self.img_frame[y:y+size, x:x+size]
# Loop through all possible arrows template and choose the most possible one
best_score = float('inf')
best_direction = ""
for direction, arrow_list in self.img_arrows.items():
for img_arrow in arrow_list:
_, score, _ = find_pattern_sqdiff(
img_roi, img_arrow,
mask=get_mask(img_arrow, (0, 255, 0)))
if score < best_score:
best_score = score
best_direction = direction
logger.info(f"[solve_rune] Arrow({arrow_idx}) is {best_direction} with score({best_score})")
# Update img_frame_debug
self.img_frame_debug = self.img_frame.copy()
draw_rectangle(
self.img_frame_debug, (x, y), (size, size),
(0, 0, 255), str(round(best_score, 2))
)
# Update debug window
self.update_img_frame_debug()
cv2.waitKey(1)
# For logging
screenshot(self.img_frame_debug, "solve_rune")
# Press the key for 0.5 second
if not self.args.disable_control:
self.kb.press_key(best_direction, 0.5)
time.sleep(1)
logger.info(f"[solve_rune] Solved all arrows")
def is_player_stuck(self):
"""
Checks whether the player is stuck (not moving)
based on their global position on map.
This function:
- Compares the player's current position with their last known position
tracked by the watchdog.
- If the player has moved beyond a threshold (`watch_dog_range`),
it resets the watchdog timer.
- If the player hasn't moved and the elapsed time exceeds (`watch_dog_timeout`),
it flags the player as stuck and resets the watchdog.
Returns:
bool: True if the player is stuck, False otherwise.
"""
dx = abs(self.loc_player_global[0] - self.loc_watch_dog[0])
dy = abs(self.loc_player_global[1] - self.loc_watch_dog[1])
current_time = time.time()
if dx + dy > self.cfg["watchdog"]["range"]:
# Player moved, reset watchdog timer
self.loc_watch_dog = self.loc_player_global
self.t_watch_dog = current_time
return False
dt = current_time - self.t_watch_dog
if dt > self.cfg["watchdog"]["timeout"]:
# watch dog idle for too long, player stuck
self.loc_watch_dog = self.loc_player_global
self.t_watch_dog = current_time
logger.warning(f"[is_player_stuck] Player stuck for {dt} seconds.")
return True
return False
def is_rune_warning(self):
'''
Checks whether the rune warning icon is appear on the game frame.
This function:
- Crops a specific region where the rune warning icon is expected.
- Compare the cropped region against the known rune warning image template.
- Returns True if rune warning template matched
Returns:
bool: True if the rune warning is detected, False otherwise.
'''
x0, y0 = self.cfg["rune_warning"]["top_left"]
x1, y1 = self.cfg["rune_warning"]["bottom_right"]
_, score, _ = find_pattern_sqdiff(
self.img_frame_gray[y0:y1, x0:x1],
self.img_rune_warning)
if self.status == "hunting" and score < self.cfg["rune_warning"]["diff_thres"]:
logger.info(f"[is_rune_warning] Detect rune warning on screen with score({score})")
return True
else:
return False
def is_rune_near_player(self):
'''
Checks if a rune icon is visible around the player's position.
This function:
- Uses template matching to detect the rune icon within this predefine box.
- Dynamically adjusts the detection threshold based on the rune detection level.
Returns:
bool: True if a rune is found near the player, False otherwise.
'''
# Calculate bounding box
h, w = self.img_frame.shape[:2]
h_rune_box = self.cfg["rune_detect"]["box_height"]
w_rune_box = self.cfg["rune_detect"]["box_width"]
x0 = max(0, self.loc_player[0] - w_rune_box // 2)
y0 = max(0, self.loc_player[1] - h_rune_box)
x1 = min(w, self.loc_player[0] + w_rune_box // 2)
y1 = min(h, self.loc_player[1])
# Debug
draw_rectangle(
self.img_frame_debug, (x0, y0), (y1-y0, x1-x0),
(255, 0, 0), "Rune Detection Range"
)
# Make sure ROI is large enough to hold a full rune
max_rune_height = max(r.shape[0] for r in self.img_runes)
max_rune_width = max(r.shape[1] for r in self.img_runes)
if (x1 - x0) < max_rune_width or (y1 - y0) < max_rune_height:
return False # Skip check if box is out of range
# Extract ROI near player
img_roi = self.img_frame[y0:y1, x0:x1]
# Match each rune part separately
matches = []
for i, img_rune in enumerate(self.img_runes):
mask = get_mask(img_rune, (0, 255, 0))
loc, score, _ = find_pattern_sqdiff(img_roi, img_rune, mask=mask)
matches.append((i, loc, score, img_rune.shape))
# # Matches box debug
# for i, (part_idx, loc, score, shape) in enumerate(matches):
# draw_rectangle(
# self.img_frame_debug,
# (x0 + loc[0], y0 + loc[1]),
# shape,
# (255, 255, 0),
# f"{i},{round(score, 2)}",
# thickness=1,
# text_height=0.4
# )
# Filter out good matches
good_matches = [
(i, loc, score, shape)
for (i, loc, score, shape) in matches
if score < self.cfg["rune_detect"]["diff_thres"]
]
# Remove overlapping matches
good_matches = nms_matches(good_matches)
# Require at least 2 rune parts
if len(good_matches) < 2:
return False
# Horizontal: max distance between part's centers are small
x_centers = [x0 + loc[0] + shape[1] // 2 for (_, loc, _, shape) in good_matches]
if max(x_centers) - min(x_centers) > 10:
return False
# Vertical: check if all Y's are strictly increasing
ys = [y0 + loc[1] for (_, loc, _, _) in good_matches]
if not all(ys[i] < ys[i + 1] for i in range(len(ys) - 1)):
return False
logger.info(f"[Rune Detect] Found rune parts near player with scores:"
f" {[round(s, 2) for (_, _, s, _) in matches]}")
# Draw all parts on debug window
for (i, loc, score, shape) in matches:
draw_rectangle(
self.img_frame_debug,
(x0 + loc[0], y0 + loc[1]),
shape,
(255, 0, 255),
f"{i},{round(score, 2)}",
text_height=0.5,
thickness=1
)
screenshot(self.img_frame_debug, "rune_detected")
return True
def is_in_rune_game(self):
'''
Determines whether the rune puzzle game screen is currently active.
This function:
- Extracts the RoI where the first arrow of the rune puzzle appears.
- Performs masked template matching with all known arrow templates.
- Computes the best matching score across all arrow directions.
- If the best match score is below a threshold,
the rune puzzle is considered active.
Returns:
bool: True if the rune game is detected on screen, False otherwise.
'''
# Get lastest game screen frame buffer
self.frame = self.capture.get_frame()
# Resize game screen to 1296x759
self.img_frame = cv2.resize(self.frame, (1296, 759), interpolation=cv2.INTER_NEAREST)
# Crop arrow detection box
x, y = self.cfg["rune_solver"]["arrow_box_coord"]
size = self.cfg["rune_solver"]["arrow_box_size"]
img_roi = self.img_frame[y:y+size, x:x+size]
# Check if arrow exist on screen
best_score = float('inf')
for direc, arrow_list in self.img_arrows.items():
for img_arrow in arrow_list:
_, score, _ = find_pattern_sqdiff(
img_roi, img_arrow,
mask=get_mask(img_arrow, (0, 255, 0)))
if score < best_score:
best_score = score
draw_rectangle(
self.img_frame_debug, (x, y), (size, size),
(0, 0, 255), str(round(best_score, 2))
)
if best_score < self.cfg["rune_solver"]["arrow_box_diff_thres"]:
logger.info(f"Arrow screen detected with score({score})")
return True
return False
def is_near_edge(self):
'''
Detects whether the player is near a teleport edge region
This function:
- Defines a rectangular search region around the player's current global location.
- Scans for pixels matching a specific edge teleport color code within the region.
- If matching pixels are found, it computes the average X position of those pixels.
- Compares that average to the player's X position to determine whether the edge is on the left or right.
Returns:
str: One of:
- "edge on left"
- "edge on right"
- "" (empty string if no edge is detected nearby)
'''
x0, y0 = self.loc_player_global
h, w = self.img_route.shape[:2]
h_trigger_box = self.cfg["edge_teleport"]["trigger_box_height"]
w_trigger_box = self.cfg["edge_teleport"]["trigger_box_width"]
x_min = max(0, x0 - w_trigger_box//2)
x_max = min(w, x0 + w_trigger_box//2)
y_min = max(0, y0 - h_trigger_box//2)
y_max = min(h, y0 + h_trigger_box//2)
# Debug: draw search box
# draw_rectangle(
# self.img_route_debug,
# (x_min, y_min),
# (y_max - y_min, x_max - x_min),
# (0, 0, 255), "Edge Check", thickness=1, text_height=0.4
# )
# Find mask of matching pixels
roi = self.img_route[y_min:y_max, x_min:x_max]
mask = np.all(roi == self.cfg["edge_teleport"]["color_code"], axis=2)
coords = np.column_stack(np.where(mask))
# No edge pixel
if coords.size == 0:
return ""
# Calculate mean position of matching pixels
mean_x = np.mean(coords[:, 1])
# Compare to roi center
if mean_x < x0:
return "edge on left"
else:
return "edge on right"
def get_random_action(self):
'''
get_random_action
'''
action = random.choice(list(self.color_code.values()))
logger.warning(f"Perform random action: {action}")
return action
def update_info_on_img_frame_debug(self):
'''
update_info_on_img_frame_debug
'''
# Print text at bottom left corner
self.fps = round(1.0 / (time.time() - self.t_last_frame))
text_y_interval = 23
text_y_start = 550
dt_screenshot = time.time() - self.kb.t_last_screenshot
text_list = [
f"FPS: {self.fps}",
f"Status: {self.status}",
f"Resolution: {self.frame.shape[0]}x{self.frame.shape[1]}",
f"Press 'F1' to {'pause' if self.kb.is_enable else 'start'} Bot",
f"Press 'F2' to save screenshot{' : Saved' if dt_screenshot < 0.7 else ''}"]
for idx, text in enumerate(text_list):
cv2.putText(
self.img_frame_debug, text,
(10, text_y_start + text_y_interval*idx),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255),
2, cv2.LINE_AA
)
# Draw minimap rectangle on img debug
draw_rectangle(
self.img_frame_debug,
self.loc_minimap,
self.img_minimap.shape[:2],
(0, 0, 255), "minimap",thickness=2
)
# Don't draw minimap in patrol mode
if self.args.patrol:
return
# Compute crop region with boundary check
crop_w, crop_h = 80, 80
x0 = max(0, self.loc_player_global[0] - crop_w // 2)
y0 = max(0, self.loc_player_global[1] - crop_h // 2)
x1 = min(self.img_route_debug.shape[1], x0 + crop_w)
y1 = min(self.img_route_debug.shape[0], y0 + crop_h)
# Check if valid crop region
if x1 <= x0 or y1 <= y0:
return
# Crop region
mini_map_crop = self.img_route_debug[y0:y1, x0:x1]
mini_map_crop = cv2.resize(mini_map_crop,
(int(mini_map_crop.shape[1] * 3),
int(mini_map_crop.shape[0] * 3)),
interpolation=cv2.INTER_NEAREST)
# Paste into top-right corner of self.img_frame_debug
h_crop, w_crop = mini_map_crop.shape[:2]
h_frame, w_frame = self.img_frame_debug.shape[:2]
x_paste = w_frame - w_crop - 10 # 10px margin from right
y_paste = 70
self.img_frame_debug[y_paste:y_paste + h_crop, x_paste:x_paste + w_crop] = mini_map_crop
# Draw border around minimap
cv2.rectangle(
self.img_frame_debug,
(x_paste, y_paste),
(x_paste + w_crop, y_paste + h_crop),
color=(255, 255, 255), # White border
thickness=2
)
def update_img_frame_debug(self):
'''
update_img_frame_debug
'''
cv2.imshow("Game Window Debug",
self.img_frame_debug[self.cfg["camera"]["y_start"]:
self.cfg["camera"]["y_end"], :])
# Update FPS timer
self.t_last_frame = time.time()
def click_in_game_window(self, x, y):
game_window = gw.getWindowsWithTitle(self.cfg["game_window"]["title"])[0]
win_left, win_top = game_window.left, game_window.top
pyautogui.click(win_left + x, win_top + y)
def channel_change(self):
print("Start channel change process")
coords = [
(1140, 730), # 伺服器選單按鈕
(1140, 666), # 頻道按鈕
(877, 161), # 任意頻道
(585, 420), # 確定
(877, 395), # 登入後選角色
(888, 275), # 確定角色
]
for i, (x, y) in enumerate(coords[:4]):
self.click_in_game_window(x, y)
time.sleep(1)
time.sleep(25)
self.click_in_game_window(*coords[4])
time.sleep(2)
self.click_in_game_window(*coords[5])
self.kb.enable()
self.kb.set_command("stop")
time.sleep(10) #ensure if there's no lagging during log in
self.click_in_game_window(*coords[4])
time.sleep(2)
self.click_in_game_window(*coords[5])
def run_once(self):
'''
Process one game window frame
'''
# Get window game raw frame
self.frame = self.capture.get_frame()
if self.frame is None:
logger.warning("Failed to capture game frame.")
return
# Make sure resolution is as expected
if self.cfg["game_window"]["size"] != self.frame.shape[:2]:
text = f"Unexpeted window size: {self.frame.shape[:2]} (expect {self.cfg["game_window"]["size"]})"
logger.error(text)
return
# Resize raw frame to (1296, 759)
self.img_frame = cv2.resize(self.frame, (1296, 759),
interpolation=cv2.INTER_NEAREST)
# Get minimap coordinate and size on game window
minimap_result = get_minimap_loc_size(self.img_frame)
if minimap_result is None:
logger.warning("Failed to get minimap location and size.")
else:
x, y, w, h = minimap_result
self.loc_minimap = (x, y)
self.img_minimap = self.img_frame[y:y+h, x:x+w]
# Grayscale game window
self.img_frame_gray = cv2.cvtColor(self.img_frame, cv2.COLOR_BGR2GRAY)
# Image for debug use
self.img_frame_debug = self.img_frame.copy()
# Get current route image
if not self.args.patrol:
self.img_route = self.img_routes[self.idx_routes]
self.img_route_debug = cv2.cvtColor(self.img_route, cv2.COLOR_RGB2BGR)
# Update health monitor with current frame
self.health_monitor.update_frame(self.img_frame[self.cfg["camera"]["y_end"]:, :])
# Draw HP/MP/EXP bar on debug window
ratio_bars = [self.health_monitor.hp_ratio,
self.health_monitor.mp_ratio,
self.health_monitor.exp_ratio]
for i, bar_name in enumerate(["HP", "MP", "EXP"]):
x_s, y_s = (250, 90)
# Print bar ratio on debug window
cv2.putText(self.img_frame_debug,
f"{bar_name}: {ratio_bars[i]*100:.1f}%",
(x_s, y_s + 30*i),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 2)
# Draw bar on debug window
x_s, y_s = (410, 73)
# print(self.health_monitor.loc_size_bars)
x, y, w, h = self.health_monitor.loc_size_bars[i]
self.img_frame_debug[y_s+30*i:y_s+h+30*i, x_s:x_s+w] = \
self.img_frame[self.cfg["camera"]["y_end"]:, :][y:y+h, x:x+w]
# Check whether "Please remove runes" warning appears on screen
if self.is_rune_warning():
self.rune_detect_level = 0
self.switch_status("finding_rune") # Stop hunting and start find runes
# Get player location in game window
self.loc_player = self.get_player_location_by_nametag()
# Get player location on minimap
loc_player_minimap = get_player_location_on_minimap(
self.img_minimap,
minimap_player_color=self.cfg["minimap"]["player_color"])
if loc_player_minimap:
self.loc_player_minimap = loc_player_minimap
# Get other player location on minimap & change channel
'''
Detect red dot (0,0,255) and calculate the center to define as other player position.
Needs improvement - current implementation calculates a single center value for all detected red dots.
When multiple players appear at once, this reduces the perceived displacement.
Future enhancement should cluster red dots into separate groups when multiple players are detected simultaneously.
'''
loc_other_players = get_all_other_player_locations_on_minimap(self.img_minimap)
if loc_other_players:
# Calculate center value
xs = [x for (x, y) in loc_other_players]
ys = [y for (x, y) in loc_other_players]
if len(xs) == 0 or len(ys) == 0:
return
center_x = np.mean(xs)
center_y = np.mean(ys)
if np.isnan(center_x) or np.isnan(center_y):
return
center = (int(np.mean(xs)), int(np.mean(ys)))
#logger.warning(f"[RedDot] Center of mass = {center}")
# Change channel
if self.cfg["auto_change_channel"] == "true":
logger.warning("Player detected, immediately change channel.")
self.kb.set_command("stop")
self.kb.disable()
time.sleep(1)
self.channel_change()
self.red_dot_center_prev = None
return
elif self.cfg["auto_change_channel"] == "pixel":
if self.red_dot_center_prev is not None:
dx = abs(center[0] - self.red_dot_center_prev[0])
dy = abs(center[1] - self.red_dot_center_prev[1])
total = dx + dy
logger.debug(f"[RedDot] Movement dx={dx}, dy={dy}, total={total}")
if total > self.cfg["other_player_move_pixel"]:
logger.warning(f"Other player movement > {self.cfg["other_player_move_pixel"]}px detected, triggering channel change.")
self.kb.set_command("stop")
self.kb.disable()
time.sleep(1)
self.channel_change()
self.red_dot_center_prev = None
return
else:
self.red_dot_center_prev = center
else:
self.red_dot_center_prev = None
# Get player location on global map
if self.args.patrol:
self.loc_player_global = self.loc_player_minimap
else:
self.loc_player_global = self.get_player_location_on_global_map()
# Check whether a rune icon is near player
if self.status == "finding_rune" and self.is_rune_near_player():
self.switch_status("near_rune")
# Check whether we entered the rune mini-game
if self.status == "near_rune" and (not self.args.disable_control) and \
time.time() - self.t_last_rune_trigger > self.cfg["rune_find"]["rune_trigger_cooldown"]:
self.kb.set_command("stop") # stop character
time.sleep(0.1) # Wait for character to stop
self.kb.disable() # Disable kb thread during rune solving
# Attempt to trigger rune
self.kb.press_key("up", 0.02)
time.sleep(1) # Wait for rune game to pop up
# If entered the game, start solving rune
if self.is_in_rune_game():
self.solve_rune() # Blocking until runes solved
self.rune_detect_level = 0 # reset rune detect level
self.switch_status("hunting")
# Restore kb thread
self.kb.enable()
self.t_last_rune_trigger = time.time()
# Get monster search box
margin = self.cfg["monster_detect"]["search_box_margin"]
if self.args.attack == "aoe_skill":
dx = self.cfg["aoe_skill"]["range_x"] // 2 + margin
dy = self.cfg["aoe_skill"]["range_y"] // 2 + margin
elif self.args.attack == "directional":
dx = self.cfg["directional_attack"]["range_x"] + margin
dy = self.cfg["directional_attack"]["range_y"] + margin
else:
logger.error(f"Unsupported attack mode: {self.args.attack}")
return
x0 = max(0, self.loc_player[0] - dx)
x1 = min(self.img_frame.shape[1], self.loc_player[0] + dx)
y0 = max(0, self.loc_player[1] - dy)
y1 = min(self.img_frame.shape[0], self.loc_player[1] + dy)
# Get monsters in the search box
if self.status == "hunting":
self.monster_info = self.get_monsters_in_range((x0, y0), (x1, y1))
else:
self.monster_info = []
# Get attack direction
if self.args.attack == "aoe_skill":
if len(self.monster_info) == 0:
attack_direction = None
else:
attack_direction = "I don't care"
nearest_monster = self.get_nearest_monster()
elif self.args.attack == "directional":
# Get nearest monster to player
monster_left = self.get_nearest_monster(is_left = True)
monster_right = self.get_nearest_monster(is_left = False)
# Compute distance for left
distance_left = float('inf')
if monster_left is not None:
mx, my = monster_left["position"]
mw, mh = monster_left["size"]
center_left = (mx + mw // 2, my + mh // 2)
distance_left = abs(center_left[0] - self.loc_player[0]) + \
abs(center_left[1] - self.loc_player[1])
# Compute distance for right
distance_right = float('inf')
if monster_right is not None:
mx, my = monster_right["position"]
mw, mh = monster_right["size"]
center_right = (mx + mw // 2, my + mh // 2)
distance_right = abs(center_right[0] - self.loc_player[0]) + \
abs(center_right[1] - self.loc_player[1])
# Choose attack direction and nearest monster
attack_direction = None
nearest_monster = None
# Additional validation: check if monster is actually on the correct side
def is_monster_on_correct_side(monster, direction):
if monster is None:
return False
mx, my = monster["position"]
mw, mh = monster["size"]
monster_center_x = mx + mw // 2
player_x = self.loc_player[0]
if direction == "left":
return monster_center_x < player_x # Monster should be left of player
else: # direction == "right"
return monster_center_x > player_x # Monster should be right of player
# Only choose direction if there's a clear winner and monster is on correct side
if monster_left is not None and monster_right is None and is_monster_on_correct_side(monster_left, "left"):
attack_direction = "left"
nearest_monster = monster_left
elif monster_right is not None and monster_left is None and is_monster_on_correct_side(monster_right, "right"):
attack_direction = "right"
nearest_monster = monster_right
elif monster_left is not None and monster_right is not None:
# Both sides have monsters, check distance and side validation
left_valid = is_monster_on_correct_side(monster_left, "left")
right_valid = is_monster_on_correct_side(monster_right, "right")
if left_valid and not right_valid:
attack_direction = "left"
nearest_monster = monster_left
elif right_valid and not left_valid:
attack_direction = "right"
nearest_monster = monster_right
elif left_valid and right_valid and distance_left < distance_right - 50:
attack_direction = "left"
nearest_monster = monster_left
elif left_valid and right_valid and distance_right < distance_left - 50:
attack_direction = "right"
nearest_monster = monster_right
# If both valid but distances too close, don't attack to avoid confusion
# Debug attack direction selection
if monster_left is not None or monster_right is not None:
left_side_ok = is_monster_on_correct_side(monster_left, "left") if monster_left else False
right_side_ok = is_monster_on_correct_side(monster_right, "right") if monster_right else False
debug_text = f"L:{distance_left:.0f}({left_side_ok}) R:{distance_right:.0f}({right_side_ok}) Dir:{attack_direction}"
cv2.putText(self.img_frame_debug, debug_text,
(10, 450), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 2)
command = ""
if self.args.patrol:
x, y = self.loc_player
h, w = self.img_frame.shape[:2]
loc_player_ratio = float(x)/float(w)
left_ratio, right_ratio = self.cfg["patrol"]["range"]
# Check if we need to change patrol direction
if self.is_patrol_to_left and loc_player_ratio < left_ratio:
self.patrol_turn_point_cnt += 1
elif (not self.is_patrol_to_left) and loc_player_ratio > right_ratio:
self.patrol_turn_point_cnt += 1
if self.patrol_turn_point_cnt > self.cfg["patrol"]["turn_point_thres"]:
self.is_patrol_to_left = not self.is_patrol_to_left
self.patrol_turn_point_cnt = 0
# Set command for patrol mode
# Use proper attack range checking instead of just checking if monsters exist
if (time.time() - self.t_patrol_last_attack > self.cfg["patrol"]["patrol_attack_interval"] and
len(self.monster_info) > 0 and nearest_monster is not None):
# Check if monster is actually in attack range
if attack_direction == "I don't care" or attack_direction == "left" or attack_direction == "right":
command = "attack"
self.t_patrol_last_attack = time.time()
elif self.is_patrol_to_left:
command = "walk left"
else:
command = "walk right"
else:
# get color code from img_route
color_code = self.get_nearest_color_code()
if color_code:
if color_code["action"] == "goal":
# Switch to next route map
self.idx_routes = (self.idx_routes+1)%len(self.img_routes)
logger.debug(f"Change to new route:{self.idx_routes}")
command = color_code["action"]
# teleport away from edge to avoid falling off cliff
if self.is_near_edge() and \
time.time() - self.t_last_teleport > self.cfg["teleport"]["cooldown"]:
command = command.replace("walk", "teleport")
self.t_last_teleport = time.time() # update timer
if self.cfg["key"]["teleport"] == "": # disable teleport skill
command = command.replace("teleport", "jump")
# Special logic for each status, overwrite color code action
if self.status == "hunting":
# Perform a random action when player stuck
if not self.args.patrol and self.is_player_stuck():
command = self.get_random_action()
elif command in ["up", "down", "jump right", "jump left"]:
pass # Don't attack while character is on rope or jumping
elif attack_direction == "I don't care" and nearest_monster is not None and \
time.time() - self.t_last_attack > self.cfg["directional_attack"]["cooldown"]:
command = "attack"
self.t_last_attack = time.time()
elif attack_direction == "left" and nearest_monster is not None and \
time.time() - self.t_last_attack > self.cfg["directional_attack"]["cooldown"]:
command = "attack left"
self.t_last_attack = time.time()
elif attack_direction == "right" and nearest_monster is not None and \
time.time() - self.t_last_attack > self.cfg["directional_attack"]["cooldown"]:
command = "attack right"
self.t_last_attack = time.time()
elif self.status == "finding_rune":
if self.is_player_stuck():
command = self.get_random_action()
# If the HP is reduced switch to hurting (other player probably help solved the rune)
if time.time() - self.health_monitor.last_hp_reduce_time < 3:
self.switch_status("hunting")
# Check if finding rune timeout
if time.time() - self.t_last_switch_status > self.cfg["rune_find"]["timeout"]:
self.switch_status("resting")
elif self.status == "near_rune":
# Stay in near_rune status for only a few seconds
if time.time() - self.t_last_switch_status > self.cfg["rune_find"]["near_rune_duration"]:
self.switch_status("hunting")
elif self.status == "resting":
self.img_routes = [self.img_route_rest] # Set up resting route
self.idx_routes = 0
else:
logger.error(f"Unknown status: {self.status}")
# send command to keyboard controller
self.kb.set_command(command)
# Debug: show current command on screen
if command and len(command) > 0:
cv2.putText(self.img_frame_debug, f"CMD: {command}",
(10, 480), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
# Check if need to save screenshot
if self.kb.is_need_screen_shot:
screenshot(self.img_frame)
self.kb.is_need_screen_shot = False
# Enable cached location since second frame
self.is_first_frame = False
#####################
### Debug Windows ###
#####################
# Don't show debug window to save system resource
if not self.cfg["system"]["show_debug_window"]:
return
# Print text on debug image
self.update_info_on_img_frame_debug()
# Show debug image on window
self.update_img_frame_debug()
# Resize img_route_debug for better visualization
if not self.args.patrol:
self.img_route_debug = cv2.resize(
self.img_route_debug, (0, 0),
fx=self.cfg["minimap"]["debug_window_upscale"],
fy=self.cfg["minimap"]["debug_window_upscale"],
interpolation=cv2.INTER_NEAREST)
cv2.imshow("Route Map Debug", self.img_route_debug)
if name == 'main':
parser = argparse.ArgumentParser()
parser.add_argument(
'--disable_control',
action='store_true',
help='Disable simulated keyboard input'
)
code
parser.add_argument(
'--patrol',
action='store_true',
help='Enable patrol mode'
)
# Argument to specify map name
parser.add_argument(
'--map',
type=str,
default='lost_time_1',
help='Specify the map name'
)
parser.add_argument(
"--monsters",
type=str,
default="evolved_ghost",
help="Specify which monsters to load, comma-separated"
"(e.g., --monsters green_mushroom,zombie_mushroom)"
)
parser.add_argument(
'--attack',
type=str,
default='directional',
help='Choose attack method, "directional", "aoe_skill"'
)
parser.add_argument(
'--nametag',
type=str,
default='example',
help='Choose nametag png file in nametag/'
)
parser.add_argument(
'--cfg',
type=str,
default='edit_me',
help='Choose customized config yaml file in config/'
)
try:
mapleStoryBot = MapleStoryBot(parser.parse_args())
except Exception as e:
logger.error(f"MapleStoryBot Init failed: {e}")
sys.exit(1)
else:
while True:
t_start = time.time()
# Process one game window frame
mapleStoryBot.run_once()
# Exit if 'q' is pressed
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
# Cap FPS to save system resource
frame_duration = time.time() - t_start
target_duration = 1.0 / mapleStoryBot.cfg["system"]["fps_limit_main"]
if frame_duration < target_duration:
time.sleep(target_duration - frame_duration)
cv2.destroyAllWindows()
self.cfg
"false"
python
self.cfg["auto_change_channel"] = "false"
這樣程式就不會執行切頻相關代碼。
2. 直接註解或刪除程式碼中切頻段
在 run_once() 裡找到上述區塊,將以下程式碼註解或刪除:
python
if self.cfg["auto_change_channel"] == "true":
logger.warning("Player detected, immediately change channel.")
self.kb.set_command("stop")
self.kb.disable()
time.sleep(1)
self.channel_change()
self.red_dot_center_prev = None
return
elif self.cfg["auto_change_channel"] == "pixel":
if self.red_dot_center_prev is not None:
dx = abs(center[0] - self.red_dot_center_prev[0])
dy = abs(center[1] - self.red_dot_center_prev[1])
total = dx + dy
logger.debug(f"[RedDot] Movement dx={dx}, dy={dy}, total={total}")
if total > self.cfg["other_player_move_pixel"]:
logger.warning(f"Other player movement > {self.cfg['other_player_move_pixel']}px detected, triggering channel change.")
self.kb.set_command("stop")
self.kb.disable()
time.sleep(1)
self.channel_change()
self.red_dot_center_prev = None
return
else:
self.red_dot_center_prev = center
改成僅紀錄紅點位置,不執行跳頻:
python
if loc_other_players:
self.red_dot_center_prev = center
else:
self.red_dot_center_prev = None
3. 修改切頻條件永遠不滿足
如果想保留程式碼但不觸發,可以將條件改為永遠 False,如:
python
if False and self.cfg["auto_change_channel"] == "true":
# 切頻代碼...