// ==UserScript== // @name HV Unified // @namespace hvunified // @version 0.14.22 // @description HV Unified — battle automation, guidance, and UI enhancements for HentaiVerse // @author GaboGG + Hermes // @match *://*.hentaiverse.org/* // @match *://alt.hentaiverse.org/* // @grant none // @run-at document-end // ==/UserScript== (function() { 'use strict'; // ═══════════════════════════════════════════════════════════════════════ // CONFIG — default settings // ═══════════════════════════════════════════════════════════════════════ const VERSION = '0.14.22'; const CFG = { // — Battle automation hotkey: 'KeyQ', hotkeyMod: '', hoverEnabled: true, autoBuff: true, autoDebuff: true, autoCure: true, autoSpirit: false, // Manual spirit stance only (auto-disable at 65% SP for Spark) // — Thresholds (simulation-backed) cureHP: 0.45, // Cast Cure below this HP cureItemHP: 0.50, // Use health items at this HP cureRegenHP: 0.65, // Cast Regen below this HP manaGemMP: 0.45, // Use mana gems below this MP manaPotionMP: 0.25, // Use mana potions at this MP spiritPotionSP: 0.60, // Use spirit gems/potions below this SP (Spark costs 50%) spiritStanceOC: 80, // Manual spirit stance only (auto-disable at 65% SP for Spark) skillOC: 60, // Use weapon skills at this OC (lower = faster, key on IWBTH) useAttackSpells: false, // Don't use attack spells (let channel proc naturally) // — Out of battle autoSell: true, sellQuality: 'Average', bulkShrine: true, reTimer: true, trainingQueue: true, // — UI showCooldowns: true, showMonsterHP: true, showDurations: true, alertColours: true, showMonsterNumbers: true, cfgButton: true, showGuidance: true, showEquipAdvice: true, autoDifficulty: true, // — Combat style useAttackSpells: true, }; // ═══════════════════════════════════════════════════════════════════════ // STATE — global runtime state // ═══════════════════════════════════════════════════════════════════════ const SP = 'hvunified_'; const STATE = { page: null, level: 1, tier: 'novice', isekai: false, battleMode: '', inBattle: false, battleInitialized: false, _mysticUsed: false, // Track if Mystic Gem has been used this battle _lastActionTime: 0, _spiritForSkill: 0, // 3-state flag for burst spirit toggle (0=off, 1=toggle-on, 2=cast-done) // Timestamp of last dispatched action (for Q debounce) _baseMpCosts: {}, // Cached base MP costs for buff spells (read from magic pane at battle start) maxBuffDur: {}, // Tracks highest duration seen per buff icon (persisted to localStorage) hoverTarget: -1, interruptHover: false, interruptAlert: false, monsters: [], monsterSp: [], // SP/OC bar levels per monster (0-120, high = about to special) hp: 1, mp: 1, sp: 1, oc: 0, spiritStance: false, buffs: {}, spellsKnown: [], skillsKnown: [], itemsKnown: {}, cooldowns: {}, battleMonsterNames: [], channeling: false, monsterData: {}, difficulty: 'Normal', battleStats: { damageDealt: 0, damageTaken: 0, turns: 0, drops: 0, credits: 0, }, round: 0, settingsVisible: false, }; // Load monster data from localStorage try { STATE.monsterData = JSON.parse(localStorage[SP + 'monsters'] || '{}'); } catch (e) { STATE.monsterData = {}; } // Load max buff durations from localStorage (learned across sessions) // Pre-seed with L150+ baseline values so fill-level formula works from first turn const DEFAULT_MAX_BUFF_DUR = { 'haste': 80, 'protection': 80, 'sparklife': 50, 'heartseeker': 120, 'regen': 50, 'absorb': 75, 'shadowveil': 75, }; STATE.maxBuffDur = { ...DEFAULT_MAX_BUFF_DUR }; try { const saved = JSON.parse(localStorage[SP + 'maxBuffDur'] || '{}'); for (const [k, v] of Object.entries(saved)) { STATE.maxBuffDur[k] = v; } } catch (e) {} // ── helpers ── function loadConfig() { try { const saved = JSON.parse(localStorage[SP + 'cfg'] || '{}'); for (const [k, v] of Object.entries(saved)) { if (CFG[k] !== undefined) CFG[k] = v; } } catch (e) {} } function saveConfig() { try { localStorage[SP + 'cfg'] = JSON.stringify(CFG); } catch (e) {} } function setConfig(key, value) { if (CFG[key] !== undefined) { CFG[key] = value; saveConfig(); } } function readCSSDigits(container) { if (!container) return null; const digits = []; container.querySelectorAll('div').forEach(c => { const m = (c.className || '').match(/c4(\d)\b/); if (m) digits.push(m[1]); }); if (digits.length === 0) return null; const parsed = parseInt(digits.join('')); return isNaN(parsed) ? null : parsed; } // CSS font character map: c5a=a, c5b=b, ..., c5z=z // c59 = space, c4a = period, c40-c49 = 0-9 // Note: no \\b word boundary — JS handles boundaries differently in class names function readCSSText(container) { if (!container) return ''; let text = ''; container.querySelectorAll('div').forEach(c => { const cls = c.className || ''; // c5a-c5z → letters a-z const letterMatch = cls.match(/c5([a-z])\b/); if (letterMatch) { text += letterMatch[1]; return; } // c59 → space if (/c59\b/.test(cls)) { text += ' '; return; } // c4a → period if (/c4a\b/.test(cls)) { text += '.'; return; } // c40-c49 → digits 0-9 const digitMatch = cls.match(/c4([0-9])\b/); if (digitMatch) { text += digitMatch[1]; return; } }); return text; } // Save difficulty from last overworld page read function cacheDifficulty() { if (STATE.difficulty && STATE.difficulty !== 'Normal') { try { localStorage[SP + 'difficulty'] = STATE.difficulty; } catch (e) {} } } // Load cached difficulty (for battle pages where difficulty isn't in DOM) function restoreCachedDifficulty() { if (STATE.difficulty === 'Normal' || !STATE.difficulty) { try { const cached = localStorage[SP + 'difficulty']; if (cached) STATE.difficulty = cached; } catch (e) {} } } // Save max buff durations to localStorage (persist learned values across restarts) function saveMaxBuffDur() { try { localStorage[SP + 'maxBuffDur'] = JSON.stringify(STATE.maxBuffDur); } catch (e) {} } // ═══════════════════════════════════════════════════════════════════════ // UTILS — DOM shortcuts, constants, helpers // ═══════════════════════════════════════════════════════════════════════ const $ = (s, c) => (c || document).querySelector(s); const $$ = (s, c) => [...(c || document).querySelectorAll(s)]; const clamp = (v, l, h) => Math.max(l, Math.min(h, v)); const dummy = document.createElement('div'); const KEYS = { A: 65, B: 66, C: 67, D: 68, E: 69, F: 70, G: 71, H: 72, I: 73, J: 74, K: 75, L: 76, M: 77, N: 78, O: 79, P: 80, Q: 81, R: 82, S: 83, T: 84, U: 85, V: 86, W: 87, X: 88, Y: 89, Z: 90, D0: 48, D1: 49, D2: 50, D3: 51, D4: 52, D5: 53, D6: 54, D7: 55, D8: 56, D9: 57, SPACE: 32, RETURN: 13, ESCAPE: 27, COMMA: 188, PERIOD: 190, UP: 38, DOWN: 40, }; function isInputFocused() { const el = document.activeElement; if (!el) return false; const t = el.tagName; return t === 'INPUT' || t === 'TEXTAREA' || t === 'SELECT' || el.isContentEditable; } // ── CSS style builder shorthand ── function css(styles) { return Object.entries(styles) .map(([k, v]) => `${k.replace(/([A-Z])/g, '-$1').toLowerCase()}:${v}`) .join(';'); } // ═══════════════════════════════════════════════════════════════════════ // PAGE DETECTOR — detect current page and player level // ═══════════════════════════════════════════════════════════════════════ function detectPage() { // Battle page detection by DOM elements (most reliable) if (document.getElementById('textlog') || document.getElementById('riddlemaster') || document.getElementById('pane_vitals') || document.getElementById('battle_root')) { return 'battle'; } // URL-based page detection const url = window.location.href || ''; const pages = { 'ss=ch': 'character', 'ss=eq': 'equipshop', 'ss=is': 'itemshop', 'ss=am': 'armory', 'ss=ar': 'arena', 'ss=gr': 'grindfest', 'ss=iw': 'itemworld', 'ss=ml': 'monsterlab', 'ss=sh': 'shrine', 'ss=mm': 'mooglemail', 'ss=tr': 'training', 'ss=rb': 'ring', 'ss=re': 'repair', 'ss=up': 'upgrade', 'ss=en': 'enchant', 'ss=sv': 'salvage', 'ss=rf': 'reforge', 'ss=sf': 'soulfuse', 'ss=ab': 'abilities', 'ss=ml': 'monster', 'ss=it': 'invitems', 'ss=se': 'settings', 'ss=ss': 'spiritshop', 'ss=mk': 'market', 'ss=lt': 'lottery', 'ss=la': 'lastarena', }; for (const [param, page] of Object.entries(pages)) { if (url.includes(param)) return page; } return 'bazaar'; } function isBattlePage() { return !!(document.getElementById('textlog') || document.getElementById('riddlemaster') || document.getElementById('pane_vitals')); } function detectLevel() { const container = document.querySelector('#level_readout > div'); if (!container) { try { const s = parseInt(localStorage[SP + 'playerLevel']); if (s > 0) STATE.level = s; } catch (e) {} return; } // Battle page format: innerText = "Normal Lv.10" const text = (container.innerText || container.textContent || '').trim(); const textMatch = text.match(/(\w+)\s+Lv\.?\s*(\d+)/); if (textMatch) { STATE.difficulty = textMatch[1]; STATE.level = parseInt(textMatch[2]) || 1; updateTier(); return; } // CSS-font rendering (overworld page): "Nightmare Lv.52" const cssText = readCSSText(container); const cssMatch = cssText.match(/(\w+)\s+lv\.\s*(\d+)/i); if (cssMatch) { STATE.difficulty = cssMatch[1].charAt(0).toUpperCase() + cssMatch[1].slice(1); cacheDifficulty(); } // CSS-digit rendering for level number const digits = readCSSDigits(container); if (digits !== null && digits > 0) { STATE.level = digits; updateTier(); } if (STATE.level > 1) { try { localStorage[SP + 'playerLevel'] = STATE.level; } catch (e) {} } } function updateTier() { const lv = STATE.level || 1; STATE.tier = lv >= 300 ? 'master' : lv >= 150 ? 'veteran' : lv >= 50 ? 'adept' : 'novice'; } // ═══════════════════════════════════════════════════════════════════════ // BATTLE PARSER — read game state from the battle DOM // ═══════════════════════════════════════════════════════════════════════ function parseBarRatio(sel, base, ctx) { const e = (ctx || document).querySelector(sel); return e ? clamp(parseInt(e.style.width || 0) / base, 0, 1) : 1; } function parseBattleState() { STATE.inBattle = true; STATE.isekai = !!document.getElementById('vcp'); // ── Parse monster names from battle log (plain text) ── STATE.battleMonsterNames = []; // Also track channeling status from log STATE.channeling = false; const log = document.getElementById('textlog'); if (log) { log.querySelectorAll('tr').forEach(row => { const text = (row.textContent || ''); const m = text.match(/Spawned Monster \w: MID=\d+ \(([^)]+)\)/); if (m) STATE.battleMonsterNames.push(m[1].toLowerCase()); // Detect channeling status from log messages if (text.includes('The effect Channeling')) { STATE.channeling = text.includes('gains the effect'); } }); } // Also check the effects pane for channeling (more reliable — log entries scroll off) if ($('#pane_effects img[src$="channeling.png"]')) { STATE.channeling = true; } // ── Level & difficulty ── const container = document.querySelector('#level_readout > div'); if (container) { const text = (container.innerText || container.textContent || '').trim(); const textMatch = text.match(/(\w+)\s+Lv\.?\s*(\d+)/); if (textMatch) { STATE.difficulty = textMatch[1]; STATE.level = parseInt(textMatch[2]) || 1; } else { // CSS-font rendering for overworld/battle font const cssText = readCSSText(container); const cssMatch = cssText.match(/(\w+)\s+lv\.\s*(\d+)/i); if (cssMatch) { STATE.difficulty = cssMatch[1].charAt(0).toUpperCase() + cssMatch[1].slice(1); cacheDifficulty(); } const d = readCSSDigits(container); if (d !== null && d > 0) STATE.level = d; } } if (!STATE.level || STATE.level < 1) { try { const s = parseInt(localStorage[SP + 'playerLevel']); if (s > 0) STATE.level = s; } catch (e) {} } if (!STATE.level || STATE.level < 1) STATE.level = 1; try { localStorage[SP + 'playerLevel'] = STATE.level; } catch (e) {} updateTier(); restoreCachedDifficulty(); // ── Vitals ── const vitalsPane = document.getElementById('pane_vitals'); const isk = STATE.isekai; STATE.hp = parseBarRatio('img[src$="green.png"]', isk ? 496 : 414, vitalsPane); STATE.mp = parseBarRatio('img[src$="bar_blue.png"]', isk ? 207 : 414, vitalsPane); STATE.sp = parseBarRatio('img[src$="bar_red.png"]', isk ? 207 : 414, vitalsPane); // ── Overcharge ── const vcp = document.getElementById('vcp'); STATE.oc = vcp ? clamp(parseInt((vcp.querySelector('div') || {}).style?.width || 0) / 190, 0, 1) * 100 : 0; // ── Spirit Stance ── STATE.spiritStance = ((document.getElementById('ckey_spirit') || {}).src || '').includes('_s.png'); // ── Monsters ── STATE.monsters = $$('.btm1[onclick]'); // Parse each monster's SP/OC bar level (the red bar = special attack charge) STATE.monsterSp = []; $$('.btm1').forEach(m => { const spBar = m.querySelector('.btm5 img[src$="barred.png"]'); const spPct = spBar ? (parseInt(spBar.style.width) || 0) : 0; STATE.monsterSp.push(spPct); }); // ── Spells from spell pane ── STATE.spellsKnown = []; const magicPane = document.getElementById('pane_magic'); if (magicPane) { // Read all btsd elements with onmouseover (including on-cooldown spells) $$('.btsd', magicPane).forEach(el => { const omo = el.getAttribute('onmouseover') || ''; if (!omo) return; const m = omo.match(/battle\.set_infopane_spell\('([^']+)',\s*'[^']*',\s*'[^']*',\s*(\d+),\s*(\d+),\s*(\d+)\)/); if (m) { STATE.spellsKnown.push({ n: m[1], mp: parseInt(m[2]), chr: parseInt(m[3]), cd: parseInt(m[4]) }); // Cache the base MP cost (from magic pane, unaffected by channeling/Conservation) if (!STATE._baseMpCosts[m[1]]) { STATE._baseMpCosts[m[1]] = parseInt(m[2]); } } }); } // ── Skills from skill pane (Flee, Scan, etc.) ── const skillPane = document.getElementById('pane_skill'); if (skillPane) { $$('.btsd[onclick]', skillPane).forEach(el => { const omo = el.getAttribute('onmouseover') || ''; const m = omo.match(/battle\.set_infopane_spell\('([^']+)'/); if (m) STATE.spellsKnown.push({ n: m[1], mp: 0, chr: 0, cd: 0 }); }); } // ── Skills/spells from quickbar ── const WEAPON_SKILLS = [ 'Great Cleave', 'Frenzied Blows', 'Shield Bash', 'Iris Strike', 'Skyward Sword', 'Shatter Strike', 'Rending Blow', 'Backstab', 'Merciful Blow', 'Vital Strike', 'Concussive Strike', ]; STATE.skillsKnown = []; $$('#quickbar > .btqs[onclick]').forEach(el => { const omo = el.getAttribute('onmouseover') || ''; const m = omo.match(/battle\.set_infopane_spell\('([^']+)'/); if (m) { const name = m[1]; if (WEAPON_SKILLS.includes(name)) { STATE.skillsKnown.push(name); } else if (!STATE.spellsKnown.some(s => s.n === name)) { const costMatch = omo.match(/battle\.set_infopane_spell\('([^']+)',\s*'[^']*',\s*'[^']*',\s*(\d+),\s*(\d+),\s*(\d+)\)/); STATE.spellsKnown.push({ n: name, mp: costMatch ? parseInt(costMatch[2]) : 0, chr: costMatch ? parseInt(costMatch[3]) : 0, cd: costMatch ? parseInt(costMatch[4]) : 0, }); } } }); // ── Items ── STATE.itemsKnown = {}; // Read all item slots, including on-cooldown ones (which lose their id) const itemPane = document.getElementById('pane_item'); if (itemPane) { $$('.bti3 > div[onmouseover], .bti3 div[id^="ikey_"]', itemPane).forEach(el => { const omo = el.getAttribute('onmouseover') || ''; const m = omo.match(/set_infopane_item\((\d+)\)/); if (m) { const slot = el.id ? el.id.replace('ikey_', '') : ('auto_' + m[1]); STATE.itemsKnown[slot] = m[1]; } }); } // Buffs STATE.buffs = {}; const pane = document.getElementById('pane_effects'); if (pane) { $$('img[onmouseover]', pane).forEach(img => { const omo = img.getAttribute('onmouseover') || ''; const dur = omo.match(/(\d+)\s*turns?\s*rem/); // Also try to get turn count from the last parameter of set_infopane_effect const rawDur = omo.match(/set_infopane_effect\([^,]+,\s*'[^']*',\s*(\d+)\s*\)/); // 'permanent' means the buff lasts indefinitely (Absorb, autocast effects) const isPermanent = omo.includes("'permanent'"); const name = (img.src || '').split('/').pop().replace('.png', ''); const turns = isPermanent ? 999 : (dur ? parseInt(dur[1]) : (rawDur ? parseInt(rawDur[1]) : 50)); STATE.buffs[name] = turns; // Track the max duration seen for this buff (for fill-level calculation) if (turns < 999 && turns > (STATE.maxBuffDur[name] || 0)) { STATE.maxBuffDur[name] = turns; saveMaxBuffDur(); // persist across page loads } }); } // Spark of Life check if ($('img[src$="fallenshield.png"]') && !$('img[src$="bar_dgreen.png"]')) STATE.buffs['spark_of_life'] = 0; // ── Cooldowns ── STATE.cooldowns = {}; $$('.btqb').forEach(el => { const txt = (el.getAttribute('onmouseover') || el.getAttribute('title') || ''); const cd = txt.match(/Cooldown:\s*(\d+)/); if (cd) { const key = (el.querySelector('img')?.src || '').split('/').pop()?.replace('.png', '') || '?'; STATE.cooldowns[key] = parseInt(cd[1]); } }); STATE.difficulty = STATE.difficulty || 'Normal'; STATE.battleInitialized = true; } // ═══════════════════════════════════════════════════════════════════════ // ITEMS — item ID mapping // ═══════════════════════════════════════════════════════════════════════ const ITEMS = { // Gems 10005: { n: 'Health Gem', t: 'heal' }, 10006: { n: 'Mana Gem', t: 'mana' }, 10007: { n: 'Spirit Gem', t: 'spirit' }, 10008: { n: 'Mystic Gem', t: 'channel' }, // Health potions 11191: { n: 'Health Draught', t: 'heal', cost: 25 }, 11195: { n: 'Health Potion', t: 'heal', cost: 50 }, 11199: { n: 'Health Elixir', t: 'heal', cost: 500 }, // Mana potions 11291: { n: 'Mana Draught', t: 'mana', cost: 50 }, 11295: { n: 'Mana Potion', t: 'mana', cost: 100 }, 11299: { n: 'Mana Elixir', t: 'mana', cost: 1000 }, // Spirit potions 11391: { n: 'Spirit Draught', t: 'spirit', cost: 50 }, 11395: { n: 'Spirit Potion', t: 'spirit', cost: 100 }, 11399: { n: 'Spirit Elixir', t: 'spirit', cost: 1000 }, // Crystals 50001: { n: 'Crystal of Vigor', s: 'STR' }, 50002: { n: 'Crystal of Finesse', s: 'DEX' }, 50003: { n: 'Crystal of Swiftness', s: 'AGI' }, 50004: { n: 'Crystal of Fortitude', s: 'END' }, 50005: { n: 'Crystal of Cunning', s: 'INT' }, 50006: { n: 'Crystal of Knowledge', s: 'WIS' }, }; function getItemType(id) { const item = ITEMS[parseInt(id)]; return item ? item.t : null; } function hasUsableGem(type) { for (const [id, info] of Object.entries(STATE.itemsKnown)) { const d = ITEMS[parseInt(info)]; if (!d || d.t !== type) continue; // P slot (gem) only valid if it has content inside it if (id === 'p') { const p = document.getElementById('ikey_p'); if (!p || !p.querySelector('div')) continue; } return { id, item: d }; } return null; } // ═══════════════════════════════════════════════════════════════════════ // KNOWLEDGE BASE — game data, spell unlocks, milestones, stat advice // ═══════════════════════════════════════════════════════════════════════ // Base MP costs for buff spells (used for channeling value calculation when // the DOM shows Mana Conservation-reduced costs like 1 MP) const SPELL_COSTS = { 'Absorb': 40, 'Haste': 51, 'Heartseeker': 141, 'Protection': 32, 'Regen': 71, 'Shadow Veil': 52, 'Spark of Life': 70, }; const KB = { qualities: ['Crude', 'Fair', 'Average', 'Superior', 'Exquisite', 'Magnificent', 'Legendary', 'Peerless'], // Stat priority per weapon type (order = importance) statPriority: { '1H': ['STR', 'END', 'DEX', 'AGI', 'WIS', 'INT'], '2H': ['STR', 'DEX', 'END', 'AGI', 'WIS', 'INT'], 'DW': ['STR', 'DEX', 'AGI', 'END', 'WIS', 'INT'], 'Niten': ['STR', 'DEX', 'AGI', 'END', 'WIS', 'INT'], 'Staff': ['INT', 'WIS', 'END', 'AGI', 'DEX', 'STR'], }, // Forum note: stats "barely even matter". These are rough guidelines, not precise. statAllocation: { novice: { '1H': { STR: 30, END: 25, DEX: 20, AGI: 10, WIS: 10, INT: 5 }, 'Staff': { INT: 30, WIS: 25, END: 25, AGI: 10, DEX: 5, STR: 5 }, }, adept: { '1H': { STR: 35, END: 20, DEX: 20, AGI: 10, WIS: 10, INT: 5 }, 'Staff': { INT: 35, WIS: 25, END: 20, AGI: 10, DEX: 5, STR: 5 }, }, veteran: { '1H': { STR: 40, DEX: 25, END: 15, AGI: 10, WIS: 5, INT: 5 }, 'Staff': { INT: 40, WIS: 30, END: 15, AGI: 10, DEX: 3, STR: 2 }, }, master: { '1H': { STR: 45, DEX: 30, END: 10, AGI: 10, WIS: 3, INT: 2 }, 'Staff': { INT: 45, WIS: 35, END: 10, AGI: 5, DEX: 3, STR: 2 }, }, }, // Spell unlock levels (forum-corrected: no MagNet) spellUnlocks: [ { lvl: 5, name: 'Cure' }, { lvl: 10, name: 'Protection' }, { lvl: 15, name: 'Fiery Blast' }, { lvl: 25, name: 'Freeze' }, { lvl: 50, name: 'Regen' }, { lvl: 60, name: 'Haste' }, { lvl: 70, name: 'Weaken' }, { lvl: 130, name: 'Imperil' }, { lvl: 140, name: 'Heartseeker' }, { lvl: 175, name: 'Arcane Focus' }, { lvl: 220, name: 'Full-Cure' }, ], // IW Potency rankings (forum research data) iwPotency: { '1H': ['Butcher', 'Fatality', 'Overpower'], '2H': ['Overpower', 'Butcher', 'Fatality'], 'DW': ['Overpower', 'Fatality', 'Butcher'], 'Niten': ['Overpower', 'Fatality', 'Butcher'], 'Staff': ['Economizer', 'Aether', 'Juggernaut'], }, // Difficulty EXP multipliers difficultyMult: { 'Normal': 1, 'Hard': 2, 'Nightmare': 4, 'Hell': 7, 'Nintendo': 10, 'IWBTH': 15, 'PFUDOR': 20, }, // Milestone tips milestones: [ { lvl: 1, tip: 'Do Arena "First Blood". Use items before spells.' }, { lvl: 5, tip: 'Cure unlocked! Keep Health Draughts.' }, { lvl: 10, tip: 'Protection unlocked — set as autocast.' }, { lvl: 15, tip: 'First damage spell: Fiery Blast.' }, { lvl: 50, tip: 'Regen + Adept tier. Train Adept Learner.' }, { lvl: 60, tip: 'Haste unlocked — +50% action speed.' }, { lvl: 70, tip: 'Weaken: -50% enemy damage. Use items, then Cure.' }, { lvl: 100, tip: 'Level 100! T2 spells available. Accuracy target: 150%.' }, { lvl: 130, tip: 'Imperil — THE most important debuff. Always cast first.' }, { lvl: 140, tip: 'Heartseeker — +25% physical damage, +10% crit. Self-buff, priority over Arcane Focus for 2H.' }, { lvl: 300, tip: 'Master tier. Optimize for speed. Run PFUDOR.' }, ], }; // ═══════════════════════════════════════════════════════════════════════ // STRATEGY ENGINE — tier-based action recommendation // ═══════════════════════════════════════════════════════════════════════ // ── Spell helpers ── function hasSpell(name) { return STATE.spellsKnown.some(s => s.n === name); } // Check if a spell is not on cooldown (has onclick in the DOM AND inner img isn't dimmed) function hasReadySpell(name) { const el = $$('.btsd, .btqs').find(e => (e.getAttribute('onmouseover') || '').includes(`set_infopane_spell('${name}'`)); if (!el) return false; if (!el.hasAttribute('onclick')) return false; // Double-check: the inner img might have opacity:0.5 (cooldown tint) // even if the parent has onclick from a previous parse const img = el.querySelector('img.btqi, img'); if (img && img.style.opacity === '0.5') return false; return true; } function findSpell(name) { return STATE.spellsKnown.find(s => s.n === name); } function findDmgSpell(list) { const s = STATE.spellsKnown.find(sp => list.includes(sp.n)); return s ? s.n : null; } // ── Buff helpers ── // Returns the buff duration from STATE.buffs, or 0 if not present function buffDuration(name) { return STATE.buffs[name] || 0; } // Should we cast this buff? Only if missing OR about to expire (< threshold turns) function shouldBuff(name, minTurns) { const dur = buffDuration(name); return dur === 0 || dur < minTurns; } // Known buffs with their priority, icon name, spell name, and refresh threshold // Threat detection: SP bar max is 120px, monsters >70% are dangerous const THREAT_PX = Math.round(120 * 70 / 100); // ~84px — triggers earlier on IWBTH // NOTE: Heartseeker and Arcane Focus are mutually exclusive. For a 2H (physical) build, // Heartseeker is preferred (+25% phys dmg, +10% crit). Arcane Focus is for magic builds. const BUFF_PRIORITY = [ { icon: 'haste', spell: 'Haste', minTurns: 4 }, // 100% uptime: refresh well before expiry { icon: 'protection', spell: 'Protection', minTurns: 4 }, { icon: 'sparklife', spell: 'Spark of Life', minTurns: 3 }, // icon: sparklife.png { icon: 'heartseeker', spell: 'Heartseeker', minTurns: 6 }, // Long duration, refresh at 6 to avoid gap { icon: 'regen', spell: 'Regen', minTurns: 4 }, { icon: 'absorb', spell: 'Absorb', minTurns: 4 }, { icon: 'shadowveil', spell: 'Shadow Veil', minTurns: 4 }, ]; // Known important monster names (bosses, legendaries, ultimates) const RARE_MONSTERS = [ 'manbearpig', 'white bunneh', 'mithra', 'dalek', 'konata', 'mikuru asahina', 'ryouko asakura', 'yuki nagato', 'skuld', 'urd', 'verdandi', 'yggdrasil', 'rhaegal', 'viserion', 'drogon', 'real life', 'invisible pink unicorn', 'flying spaghetti monster', 'recycled boss rush', 'bottomless dungeon', 'new game +', 'achievement grind', 'time trial mode', 'hardcore mode', ]; function isRareMonster(idx) { const m = STATE.monsters[idx]; if (!m) { // Fallback: check battle log names return STATE.battleMonsterNames.some(name => RARE_MONSTERS.some(r => name.includes(r)) ); } // Boss/rare monsters have distinct visual cues: // 1. Gold border: style="border-color:#BD7400" // 2. Gold background on label: style="background:#E6CCA3" // NOTE: At high levels/difficulties, normal monsters also get SP bars, // so we can't use nbarred.png as a boss indicator anymore. const style = m.getAttribute('style') || ''; const inner = m.innerHTML || ''; // Check for gold border (boss indicator — still reliable) if (style.includes('BD7400') || style.includes('E6CCA3')) return true; // Fallback: check name from DOM const n = m.querySelector('.btm3'); if (!n) return false; const name = (n.textContent || '').replace(/^\d+\s*/, '').trim().toLowerCase(); // Use CSS text parser for boss names rendered in font const cssName = readCSSText(n); return RARE_MONSTERS.some(r => name.includes(r) || cssName.includes(r)); } function anyRareMonster() { return STATE.monsters.some((m, i) => isRareMonster(i)); } function findWeakestMonster() { let best = -1, bestW = Infinity; STATE.monsters.forEach((m, i) => { if (!m || !m.hasAttribute || !m.hasAttribute('onclick')) return; const hp = m.querySelector('img[src$="nbargreen.png"]'); const w = hp ? parseInt(hp.style.width || '') : 120; if (w < bestW && w > 0) { bestW = w; best = i; } }); return best >= 0 ? best : 0; } function findStrongestMonster() { let best = -1, bestW = -1; STATE.monsters.forEach((m, i) => { if (!m || !m.hasAttribute || !m.hasAttribute('onclick')) return; const hp = m.querySelector('img[src$="nbargreen.png"]'); const w = hp ? parseInt(hp.style.width || '') : 120; if (w > bestW) { bestW = w; best = i; } }); return best >= 0 ? best : 0; } // Find the monster with the highest SP/OC bar (most dangerous — about to special) // The red bar (nbarred.png) has a max width of 120px // Returns the index, or 0 if none found function findDangerousMonster() { let best = -1, bestSP = -1; STATE.monsters.forEach((m, i) => { if (!m || !m.hasAttribute || !m.hasAttribute('onclick')) return; const sp = STATE.monsterSp[i] || 0; if (sp > bestSP) { bestSP = sp; best = i; } }); return best >= 0 ? best : 0; } // Check if there are 2+ monsters with SP bar > threshold (imminent special attacks) function hasHighThreat(threshold) { let count = 0; STATE.monsters.forEach((m, i) => { if (!m || !m.hasAttribute || !m.hasAttribute('onclick')) return; const sp = STATE.monsterSp[i] || 0; if (sp > threshold) count++; }); return count >= 2; } // Find optimal target for Domino Strike splash (2H passive) — center-aligned // For 2H builds, Domino Strike splashes up to 2 enemies on each side of the target. // Attacking edge monsters wastes 50% of the splash potential. function findOptimalDominoTarget() { const total = STATE.monsters.length; if (total <= 2) return findWeakestMonster(); let best = -1; let bestScore = -1; STATE.monsters.forEach((m, i) => { if (!m || !m.hasAttribute || !m.hasAttribute('onclick')) return; let splash = 0; if (i - 1 >= 0 && STATE.monsters[i - 1] && STATE.monsters[i - 1].hasAttribute('onclick')) splash++; if (i - 2 >= 0 && STATE.monsters[i - 2] && STATE.monsters[i - 2].hasAttribute('onclick')) splash++; if (i + 1 < total && STATE.monsters[i + 1] && STATE.monsters[i + 1].hasAttribute('onclick')) splash++; if (i + 2 < total && STATE.monsters[i + 2] && STATE.monsters[i + 2].hasAttribute('onclick')) splash++; if (splash > bestScore) { bestScore = splash; best = i; } }); return best >= 0 ? best : 0; } function checkMonsterDebuff(idx, db) { const m = STATE.monsters[idx]; if (!m) return false; const s = m.querySelector('.btm6'); if (!s) return false; return s.innerHTML.toLowerCase().includes(db.toLowerCase() + '.png') || s.innerHTML.toLowerCase().includes('wpn_' + db.toLowerCase()); } // ── Damage spell tier list ── const SPELL_T3 = ['Ragnarok', 'Paradise Lost', 'Flames of Loki', 'Fimbulvetr', 'Wrath of Thor', 'Storms of Njord']; const SPELL_T2 = ['Disintegrate', 'Banishment', 'Inferno', 'Blizzard', 'Chained Lightning', 'Downburst']; const SPELL_T1 = ['Corruption', 'Smite', 'Fiery Blast', 'Freeze', 'Shockblast', 'Gale']; function getBestDamageSpell() { if (STATE.monsters.length >= 2) { const aoe = findDmgSpell(SPELL_T3.concat(SPELL_T2)); if (aoe) return aoe; } return findDmgSpell(SPELL_T3.concat(SPELL_T2, SPELL_T1)); } // ── Channeling maintenance ── // // Channeling: procs randomly when casting any mana-costing spell. // Proc chance = spell_cost / (base_mana * 1.2) // Cannot proc from spells cast while already Channeling. // Effect: next spell costs 1 MP and is 50% stronger (or 50% longer for buffs) // Duration: 5 ticks (15 with Mystic Gem in P-slot) // // Best trigger spells: Regen/Absorb (17 MP = ~6% proc chance each cast) // Cheaper spells have proportionally lower proc chance. // Checks if we're in the initial buff-up phase (most buffs are missing) function isFirstRoundBuffs() { let missing = 0, total = 0; for (const b of BUFF_PRIORITY) { if (!hasSpell(b.spell)) continue; total++; if (buffDuration(b.icon) === 0) missing++; } return total > 0 && missing >= total * 0.6; // 60%+ of our buffs are down } // Round 1 strategy: cast buffs from cheapest to most expensive. // - Cheaper spells first = more casts before channeling = more proc chances // - If channeling procs mid-sequence, switch to most expensive remaining buff // Returns the next buff to cast, or null if all buffs are up. function castInitialBuffs() { if (!isFirstRoundBuffs()) return null; if (STATE.mp < 0.20) return null; // Collect all missing/expiring buffs with their MP cost const candidates = []; for (const b of BUFF_PRIORITY) { if (!hasReadySpell(b.spell)) continue; const dur = buffDuration(b.icon); if (dur === 0 || dur < 3) { if (b.icon === 'regen' && STATE.hp >= CFG.cureRegenHP) continue; const sp = findSpell(b.spell); candidates.push({ ...b, mpCost: sp ? sp.mp : 999, dur }); } } if (candidates.length === 0) return null; // Log which mode we're in if (STATE.channeling) { // Channeling is charged — cast the MOST expensive buff for best value candidates.sort((a, b) => b.mpCost - a.mpCost); return { type: 'spell', name: candidates[0].spell, selfTarget: true, _reason: 'initCh' }; } else { // No channeling — cast the CHEAPEST buff first for more proc attempts candidates.sort((a, b) => a.mpCost - b.mpCost); return { type: 'spell', name: candidates[0].spell, selfTarget: true, _reason: 'init' }; } } function kickstartChanneling() { if (STATE.channeling) return null; // Priority: cast or refresh a buff with a good MP cost for proc chance. // Higher MP cost = higher channeling proc chance. // Regen/Absorb/Heartseeker have the best cost/proc ratio among buffs. if (STATE.mp > 0.20) { // Collect all buffs that need refreshing, sorted by MP cost descending const candidates = []; for (const b of BUFF_PRIORITY) { const dur = buffDuration(b.icon); if ((dur === 0 || dur < 5) && STATE.mp > 0.15 && hasSpell(b.spell)) { if (b.icon === 'regen' && STATE.hp >= CFG.cureRegenHP) continue; const sp = findSpell(b.spell); candidates.push({ ...b, mpCost: sp ? sp.mp : 0 }); } } if (candidates.length > 0) { // Cheapest first to maximize channeling proc chance candidates.sort((a, b) => a.mpCost - b.mpCost); return { type: 'spell', name: candidates[0].spell, selfTarget: true }; } } return null; } // ── Channeling consumption — pick the best value from fill level × cost ── // Channeling gives: 1 MP cost + 50% longer duration. // The best target is the buff where: // - It's nearly empty (close to expiring relative to its max duration) // - It costs a lot of MP (more savings from the free cast) // // Score = emptiess_ratio × mp_cost // = (max_dur - current) / max_dur × mp_cost // // A 100-MP buff with 90 turns max at 1 turn remaining: (90-1)/90 * 100 = 98.9 // A 40-MP buff with 50 turns max at 25 remaining: (50-25)/50 * 40 = 20.0 // A 140-MP buff with 80 turns max at 71 remaining: (80-71)/80 * 140 = 15.75 // A freshly cast buff always scores near 0. // // max_dur is tracked dynamically per buff in STATE.maxBuffDur. // It updates each time we see a new high, learning your actual duration. function findBestChannelingTarget() { if (!STATE.channeling || STATE.mp < 0.10) return null; const candidates = []; for (const b of BUFF_PRIORITY) { if (!hasReadySpell(b.spell)) continue; const dur = buffDuration(b.icon); if (b.icon === 'regen' && STATE.hp >= CFG.cureRegenHP) continue; const sp = findSpell(b.spell); // Use cached base MP cost (snapshotted at battle start from the magic pane) // This avoids the channeling 1-MP display issue and Mana Conservation fluctuation let mpCost = STATE._baseMpCosts[b.spell] || 0; if (mpCost === 0 && sp) { // Not cached yet — read from magic pane directly const paneEl = $$('.btsd[onmouseover*="' + b.spell.replace(/'/g, "\\'") + '"]', document.getElementById('pane_magic'))[0]; if (paneEl) { const costM = (paneEl.getAttribute('onmouseover') || '') .match(/set_infopane_spell\('[^']+',\s*'[^']*',\s*'[^']*',\s*(\d+)/); if (costM) mpCost = parseInt(costM[1]); } if (mpCost === 0) mpCost = sp.mp; // last resort: use what parseBattleState gave us STATE._baseMpCosts[b.spell] = mpCost; } // Skip if we can't afford the base cost — game pre-checks even when // channeling makes the effective cost 1 MP const curMp = parseInt((document.getElementById('vrm') || {}).textContent) || 0; const estMaxMp = (STATE.mp > 0 && curMp > 0) ? Math.round(curMp / STATE.mp) : 414; if (mpCost > 0 && curMp > 0 && mpCost > curMp) continue; // Fill level: how empty is this buff relative to its max observed duration let maxDur = STATE.maxBuffDur[b.icon] || 0; // If max matches current (first observation, no learning yet), assume min 30 turns if (maxDur <= dur) maxDur = Math.max(dur + 1, 30); const emptiness = maxDur > 0 ? Math.min(1, (maxDur - dur) / maxDur) : 1; // Score: emptiness × mp_cost — an empty expensive buff is best const score = emptiness * mpCost; candidates.push({ ...b, mpCost, dur, score, emptiness, maxDur }); } if (candidates.length > 0) { candidates.sort((a, b) => b.score - a.score); console.log(`%c[HV] ch score: ${candidates[0].spell}=${candidates[0].score.toFixed(1)} (dur=${candidates[0].dur}, max=${candidates[0].maxDur}, mp=${candidates[0].mpCost}, empty=${(candidates[0].emptiness*100).toFixed(0)}%)`, 'color:#bb0'); // Only use a buff if it actually needs refreshing (score >= 30 means // e.g. 30% emptiness on a 100-MP spell, or 60% on a 50-MP spell) if (candidates[0].score >= 30) { return { type: 'spell', name: candidates[0].spell, selfTarget: true, _reason: `ch score ${candidates[0].score.toFixed(0)}` }; } } // Fallback: for physical 2H builds, don't waste channeling on weak damage spells. // Channeling improves the next spell, but Fiery Blast does negligible damage at IWBTH. // Better to use the charge on a basic attack that procs Domino Strike and Penetrated Armor. const isPhysical2H = STATE.skillsKnown.includes('Great Cleave') || STATE.skillsKnown.includes('Rending Blow'); if (isPhysical2H) { return null; // Let channeling expire naturally — basic attacks do more than Fiery Blast } // Mage fallback: use any cheap spell for mage builds const cheap = findDmgSpell(['Fiery Blast', 'Freeze', 'Shockblast', 'Gale', 'Smite', 'Corruption', 'Inferno', 'Blizzard', 'Chained Lightning', 'Downburst', 'Banishment', 'Disintegrate']); if (cheap) { const t = findWeakestMonster(); if (t >= 0 && STATE.monsters[t] && STATE.monsters[t].hasAttribute('onclick')) return { type: 'spell', name: cheap, target: t }; } // Last resort: any spell we know that costs MP for (const sp of STATE.spellsKnown) { if (sp.mp > 0 && sp.mp < (STATE.mp * 100)) { const t = findWeakestMonster(); if (t >= 0 && STATE.monsters[t] && STATE.monsters[t].hasAttribute('onclick')) return { type: 'spell', name: sp.n, target: t }; } } return null; } // ── Core strategy: forum-corrected item-before-spell priority ── // // Priority order: // 1. Mystic Gem if channeling is down (free OC gen) // 2. Health/Mana/Spirit gems proactively (don't hoard) // 3. Cure if HP critical // 4. Buffs (Protection, Regen, Haste) // 5. Debuffs (Imperil, Weaken) // 6. Spirit Stance at OC 60-80% (don't waste OC on skills before stance) // 7. Weapon skills only at high OC (80+) to let OC build // 8. Damage spells // 9. Basic attack builds OC naturally function getRecommendedAction() { parseBattleState(); if (STATE.tier === 'novice') return strategyNovice(); if (STATE.tier === 'adept') return strategyAdept(); return strategyVeteran(); // Veteran+ use the same engine } // Returns non-null ONLY when there's something smarter than basic attack function getSmartAction() { const a = getRecommendedAction(); if (!a || a.type === 'attack') return null; return a; } // ── Novice (1-50): survival first ── function strategyNovice() { // 0. Mystic Gem for channeling — only use once per battle // (channeling status is tracked from the battle log) const gem = hasUsableGem('channel'); if (gem && !STATE.channeling && !STATE._mysticUsed) return { type: 'item', id: gem.id, selfTarget: true }; // 1. Health items — safe to use early if (STATE.hp < CFG.cureItemHP) { const gem = hasUsableGem('heal'); if (gem) return { type: 'item', id: gem.id, selfTarget: true }; } // 2. Cure if (STATE.hp < CFG.cureHP) { const c = hasReadySpell('Full-Cure') ? 'Full-Cure' : hasReadySpell('Cure') ? 'Cure' : null; if (c) return { type: 'spell', name: c, selfTarget: true }; } // 3. Buffs — cast if missing or about to expire // On first round, cast cheapest-first to proc channeling { const ib = castInitialBuffs(); if (ib) return ib; } // If channeling is active, prioritize most expensive buff for best value if (STATE.channeling && STATE.mp > 0.10) { const ch = findBestChannelingTarget(); if (ch) return ch; } // Collect available buff candidates and sort by cost const buffCandidates = []; for (const b of BUFF_PRIORITY) { if (shouldBuff(b.icon, b.minTurns) && STATE.mp > 0.10 && hasReadySpell(b.spell)) { if (b.icon === 'regen' && STATE.hp >= CFG.cureRegenHP) continue; const sp = findSpell(b.spell); buffCandidates.push({ ...b, mpCost: sp ? sp.mp : 0 }); } } if (buffCandidates.length > 0) { buffCandidates.sort((a, b) => STATE.channeling ? b.mpCost - a.mpCost : a.mpCost - b.mpCost); return { type: 'spell', name: buffCandidates[0].spell, selfTarget: true, _reason: STATE.channeling ? 'chBuff' : 'buff' }; } // 4. Mana/spirit items — AFTER buffs (Novice) if (STATE.mp < CFG.manaGemMP) { const gem = hasUsableGem('mana'); if (gem) return { type: 'item', id: gem.id, selfTarget: true }; } // Spirit gem (P-slot) — auto-consume when available const pGem = document.getElementById('ikey_p'); const pGemId = pGem ? (pGem.getAttribute('onmouseover') || '').match(/set_infopane_item\((\d+)\)/) : null; if (pGemId && pGemId[1] === '10007') { if (hasUsableGem('spirit')) return { type: 'item', id: 'p', selfTarget: true }; } // Spirit draughts/potions — only when SP drops below threshold if (STATE.sp < CFG.spiritPotionSP) { // Check non-P-slot spirit items only for (const [slot, info] of Object.entries(STATE.itemsKnown)) { if (slot === 'p') continue; const def = ITEMS[parseInt(info)]; if (def && def.t === 'spirit') { return { type: 'item', id: slot, selfTarget: true }; } } } // 5. Weapon skills — these are better than basic attacks const skillOC = CFG.skillOC || 80; if (STATE.oc >= skillOC) { // Great Cleave: boss/rare fights only if (anyRareMonster() && STATE.skillsKnown.includes('Great Cleave')) { const t = findStrongestMonster(); if (t >= 0) return { type: 'skill', name: 'Great Cleave', target: t }; } // Rending Blow: AoE armor pen vs 5+ enemies if (STATE.monsters.length >= 5 && STATE.skillsKnown.includes('Rending Blow')) { const t = findStrongestMonster(); if (t >= 0) return { type: 'skill', name: 'Rending Blow', target: t }; } // Shatter Strike: AoE stun vs 3+ enemies (needs Penetrated Armor from Rending Blow) if (STATE.monsters.length >= 3 && STATE.skillsKnown.includes('Shatter Strike')) { const hasArmorBreak = STATE.monsters.some((m, i) => checkMonsterDebuff(i, 'penetrated_armor')); if (hasArmorBreak) { const t = findStrongestMonster(); if (t >= 0) return { type: 'skill', name: 'Shatter Strike', target: t }; } } } // 6. Damage spells (reserve MP for Cure) const dmg = CFG.useAttackSpells ? findDmgSpell(SPELL_T1) : null; if (dmg && STATE.mp > 0.25) { const cure = findSpell('Cure') || findSpell('Full-Cure'); const cureCost = cure ? (cure.mp / 100) * (STATE.level || 1) : 4; const mpMax = STATE.mp * 100; const reserve = Math.max(0.15, cureCost / mpMax); if (STATE.mp - reserve > 0.25) { const t = findWeakestMonster(); if (t >= 0) return { type: 'spell', name: dmg, target: t }; } } // 7. Channeling kickstart or basic attack { const k = kickstartChanneling(); if (k) return k; } // If channeling is charged, consume it on the highest-MP buff that needs refreshing { const ch = findBestChannelingTarget(); if (ch) return ch; } const t = hasHighThreat(THREAT_PX) ? findDangerousMonster() : findWeakestMonster(); if (t >= 0 && STATE.monsters[t] && STATE.monsters[t].hasAttribute('onclick')) return { type: 'attack', target: t }; return null; } // ── Adept (50-150): building power ── function strategyAdept() { // 0. Mystic Gem for channeling — only use once per battle const gem = hasUsableGem('channel'); if (gem && !STATE.channeling && !STATE._mysticUsed) return { type: 'item', id: gem.id, selfTarget: true, _reason: 'mystic' }; // 0b. Spark of Life SP safety if (STATE.sp < 0.55) { for (const [slot, info] of Object.entries(STATE.itemsKnown)) { if (slot === 'p') continue; const def = ITEMS[parseInt(info)]; if (def && def.t === 'spirit') return { type: 'item', id: slot, selfTarget: true, _reason: `sp${(STATE.sp*100).toFixed(0)}` }; } } // 0c. Spirit Stance safety auto-disable if (STATE.spiritStance && STATE.sp < 0.60) { return { type: 'toggle_spirit', _reason: 'sp_safety' }; } // 1. Health items — safe to use early if (STATE.hp < CFG.cureItemHP) { const gem = hasUsableGem('heal'); if (gem) return { type: 'item', id: gem.id, selfTarget: true }; } // 2. Cure if (STATE.hp < CFG.cureHP) { const c = hasReadySpell('Full-Cure') ? 'Full-Cure' : hasReadySpell('Cure') ? 'Cure' : null; if (c) return { type: 'spell', name: c, selfTarget: true }; } // 2b. Spirit items — Spark of Life costs 50% SP. Keep SP above 55% so // Spark can actually save us. if (STATE.sp < 0.55) { for (const [slot, info] of Object.entries(STATE.itemsKnown)) { if (slot === 'p') continue; const def = ITEMS[parseInt(info)]; if (def && def.t === 'spirit') return { type: 'item', id: slot, selfTarget: true }; } } // 3. Buffs // On first round, cast cheapest-first to proc channeling { const ib = castInitialBuffs(); if (ib) return ib; } // If channeling is active, prioritize most expensive buff for best value // Note: channeling reduces cost to ~1, but the game pre-checks base MP, // If channeling is active, prioritize most expensive buff for best value if (STATE.channeling && STATE.mp > 0.10) { const ch = findBestChannelingTarget(); if (ch) return ch; } // Collect available buff candidates and sort by cost const buffCandidates = []; for (const b of BUFF_PRIORITY) { if (shouldBuff(b.icon, b.minTurns) && STATE.mp > 0.10 && hasReadySpell(b.spell)) { if (b.icon === 'regen' && STATE.hp >= CFG.cureRegenHP) continue; const sp = findSpell(b.spell); buffCandidates.push({ ...b, mpCost: sp ? sp.mp : 0 }); } } if (buffCandidates.length > 0) { buffCandidates.sort((a, b) => STATE.channeling ? b.mpCost - a.mpCost : a.mpCost - b.mpCost); return { type: 'spell', name: buffCandidates[0].spell, selfTarget: true, _reason: STATE.channeling ? 'chBuff' : 'buff' }; } // 4. Mana/spirit items — AFTER buffs (Adept) if (STATE.mp < CFG.manaGemMP) { const gem = hasUsableGem('mana'); if (gem) return { type: 'item', id: gem.id, selfTarget: true }; } // Spirit gem (P-slot) — auto-consume when available const apGem = document.getElementById('ikey_p'); const apGemId = apGem ? (apGem.getAttribute('onmouseover') || '').match(/set_infopane_item\((\d+)\)/) : null; if (apGemId && apGemId[1] === '10007') { if (hasUsableGem('spirit')) return { type: 'item', id: 'p', selfTarget: true }; } // Spirit draughts/potions — only at SP < threshold if (STATE.sp < CFG.spiritPotionSP) { for (const [slot, info] of Object.entries(STATE.itemsKnown)) { if (slot === 'p') continue; const def = ITEMS[parseInt(info)]; if (def && def.t === 'spirit') return { type: 'item', id: slot, selfTarget: true }; } } // 4. Debuffs — conservative: Imperil on bosses/rares or 5+ mobs // Weaken only on high-threat or bosses. Estoc handles <5. if (CFG.autoDebuff && STATE.mp > 0.35) { if (hasReadySpell('Imperil') && (anyRareMonster() || STATE.monsters.length >= 5)) { const b = findStrongestMonster(); if (b >= 0 && !checkMonsterDebuff(b, 'imperil')) return { type: 'spell', name: 'Imperil', target: b, _reason: 'imperil' }; } if (hasReadySpell('Weaken') && (anyRareMonster() || hasHighThreat(THREAT_PX))) { const b = findDangerousMonster(); if (b >= 0 && !checkMonsterDebuff(b, 'weaken')) return { type: 'spell', name: 'Weaken', target: b, _reason: 'weaken' }; } } // 5. Weapon skills — prioritize high-threat monsters (high SP/OC bar) const isHighThreat = hasHighThreat(THREAT_PX); if (isHighThreat) console.log('%c[HV] ⚠ HIGH THREAT (Adept): 2+ monsters with SP >85%', 'color:#f44'); const skillOC_N = CFG.skillOC || 75; if (STATE.oc >= skillOC_N || isHighThreat) { if (isHighThreat && STATE.oc < skillOC_N) console.log('%c[HV] ⚠ emergency skill at OC=' + STATE.oc.toFixed(0), 'color:#f80'); // Rending Blow: AoE armor pen vs 3+ enemies (reduced from 5) if (STATE.monsters.length >= 3 && STATE.skillsKnown.includes('Rending Blow')) { const t = isHighThreat ? findDangerousMonster() : findStrongestMonster(); if (t >= 0) return { type: 'skill', name: 'Rending Blow', target: t }; } // Shatter Strike: AoE stun vs 3+ enemies (needs Penetrated Armor from Rending Blow) if (STATE.monsters.length >= 3 && STATE.skillsKnown.includes('Shatter Strike')) { const hasArmorBreak = STATE.monsters.some((m, i) => checkMonsterDebuff(i, 'penetrated_armor')); if (hasArmorBreak) { const t = isHighThreat ? findDangerousMonster() : findStrongestMonster(); if (t >= 0) return { type: 'skill', name: 'Shatter Strike', target: t }; } } // Great Cleave: boss/rare fights only (single target, lower priority than AoE) if (anyRareMonster() && STATE.skillsKnown.includes('Great Cleave')) { const t = isHighThreat ? findDangerousMonster() : findStrongestMonster(); if (t >= 0) return { type: 'skill', name: 'Great Cleave', target: t }; } } // 5. Damage spells const dmg = CFG.useAttackSpells ? getBestDamageSpell() : null; if (dmg && STATE.mp > 0.2) { const t = STATE.monsters.length > 1 ? findWeakestMonster() : findStrongestMonster(); if (t >= 0 && STATE.monsters[t] && STATE.monsters[t].hasAttribute('onclick')) return { type: 'spell', name: dmg, target: t }; } // 8. Channeling kickstart or basic attack { const k = kickstartChanneling(); if (k) return k; } // Use channeling charge on the highest-MP buff that needs refreshing { const ch = findBestChannelingTarget(); if (ch) return ch; } const t = hasHighThreat(THREAT_PX) ? findDangerousMonster() : (STATE.monsters.length > 2 ? findOptimalDominoTarget() : findWeakestMonster()); if (t >= 0 && STATE.monsters[t] && STATE.monsters[t].hasAttribute('onclick')) return { type: 'attack', target: t, _reason: hasHighThreat(THREAT_PX) ? 'threat' : 'fallback' }; return null; } // ── Veteran (150-300) / Master (300+): full rotation ── function strategyVeteran() { // 1. Health items — ALWAYS BEFORE ATTACKING OR SKILLS! const reqHpItem = (STATE.monsters && STATE.monsters.length >= 7) ? 0.60 : CFG.cureItemHP; if (STATE.hp < reqHpItem) { const gem = hasUsableGem('heal'); if (gem) return { type: 'item', id: gem.id, selfTarget: true, _reason: `hp${(STATE.hp*100).toFixed(0)}` }; // Check non-gem health items for (const [slot, info] of Object.entries(STATE.itemsKnown)) { if (slot === 'p') continue; const def = ITEMS[parseInt(info)]; if (def && def.t === 'heal') return { type: 'item', id: slot, selfTarget: true, _reason: `hp${(STATE.hp*100).toFixed(0)}` }; } } // 2. Cure / Full-Cure spell if (STATE.hp < Math.max(0.55, CFG.cureHP)) { const c = hasReadySpell('Full-Cure') ? 'Full-Cure' : hasReadySpell('Cure') ? 'Cure' : null; if (c) return { type: 'spell', name: c, selfTarget: true, _reason: `hp${(STATE.hp*100).toFixed(0)}` }; } // 0. Mystic Gem for channeling — only use once per battle const gem = hasUsableGem('channel'); if (gem && !STATE.channeling && !STATE._mysticUsed) return { type: 'item', id: gem.id, selfTarget: true, _reason: 'mystic' }; // 0b. Spark of Life SP safety — Spark costs 50% SP when triggered. // If SP < 60%, consume a spirit item before anything else. if (STATE.sp < 0.60) { for (const [slot, info] of Object.entries(STATE.itemsKnown)) { if (slot === 'p') continue; const def = ITEMS[parseInt(info)]; if (def && def.t === 'spirit') return { type: 'item', id: slot, selfTarget: true, _reason: `sp${(STATE.sp*100).toFixed(0)}` }; } } // 0c. Spirit Stance safety auto-disable — if left on, drains 10% SP/turn if (STATE.spiritStance && STATE.sp < 0.60) { return { type: 'toggle_spirit', _reason: 'sp_safety' }; } // 0d. Spirit Stance for burst clear — toggle on for 7+ mob, off after one skill const is2H = STATE.skillsKnown.includes('Great Cleave') || STATE.skillsKnown.includes('Rending Blow'); if (is2H && STATE.monsters && STATE.monsters.length >= 7 && STATE.oc >= (CFG.skillOC || 60)) { if (STATE._spiritForSkill >= 1 && STATE.spiritStance) { if (STATE._spiritForSkill === 1) { STATE._spiritForSkill = 2; } else if (STATE._spiritForSkill === 2) { STATE._spiritForSkill = 0; return { type: 'toggle_spirit', _reason: 'spirit_off_7' }; } } else if (!STATE.spiritStance && STATE._spiritForSkill === 0) { STATE._spiritForSkill = 1; return { type: 'toggle_spirit', _reason: 'spirit_on_7' }; } } else { STATE._spiritForSkill = 0; } // 0e. HIGH-THREAT WEAPON SKILLS — after survival items/cure const SINGLE_THREAT = Math.round(120 * 90 / 100); const anyImminent = STATE.monsters.some((m, i) => (STATE.monsterSp[i] || 0) > SINGLE_THREAT); const isHighThreatEarly = hasHighThreat(THREAT_PX); if ((isHighThreatEarly || anyImminent) && STATE.oc >= 20) { if (STATE.monsters.length >= 3 && STATE.skillsKnown.includes('Rending Blow')) { const t = findDangerousMonster(); if (t >= 0) return { type: 'skill', name: 'Rending Blow', target: t, _reason: 'threat_early' }; } if (STATE.monsters.length >= 3 && STATE.skillsKnown.includes('Shatter Strike')) { const hasArmorBreak = STATE.monsters.some((m, i) => checkMonsterDebuff(i, 'penetrated_armor')); if (hasArmorBreak) { const t = findDangerousMonster(); if (t >= 0) return { type: 'skill', name: 'Shatter Strike', target: t, _reason: 'stun_early' }; } } if (STATE.skillsKnown.includes('Great Cleave')) { const t = findDangerousMonster(); if (t >= 0) return { type: 'skill', name: 'Great Cleave', target: t, _reason: 'cleave_early' }; } } // 2b. Spirit items — Spark of Life costs 50% SP. Keep SP above 55% so // Spark can actually save us. Use spirit draughts/potions proactively. if (STATE.sp < 0.55) { for (const [slot, info] of Object.entries(STATE.itemsKnown)) { if (slot === 'p') continue; const def = ITEMS[parseInt(info)]; if (def && def.t === 'spirit') return { type: 'item', id: slot, selfTarget: true, _reason: `sp${(STATE.sp*100).toFixed(0)}` }; } } // 3. Buffs // On first round, cast cheapest-first to proc channeling if (CFG.autoBuff) { { const ib = castInitialBuffs(); if (ib) return ib; } // If channeling is active, prioritize most expensive buff for best value if (STATE.channeling && STATE.mp > 0.10) { const ch = findBestChannelingTarget(); if (ch) return ch; } // Collect available buff candidates and sort by cost // No channeling → cheapest first (proc chance), channeling → most expensive (MP value) const buffCandidates = []; for (const b of BUFF_PRIORITY) { if (shouldBuff(b.icon, b.minTurns) && STATE.mp > 0.10 && hasReadySpell(b.spell)) { if (b.icon === 'regen' && STATE.hp >= CFG.cureRegenHP) continue; const sp = findSpell(b.spell); buffCandidates.push({ ...b, mpCost: sp ? sp.mp : 0 }); } } if (buffCandidates.length > 0) { buffCandidates.sort((a, b) => STATE.channeling ? b.mpCost - a.mpCost : a.mpCost - b.mpCost); return { type: 'spell', name: buffCandidates[0].spell, selfTarget: true, _reason: STATE.channeling ? 'chBuff' : 'buff' }; } } // 4. Mana/spirit items — AFTER buffs (Novice) if (STATE.mp < CFG.manaGemMP) { const gem = hasUsableGem('mana'); if (gem) return { type: 'item', id: gem.id, selfTarget: true }; } // Spirit gem (P-slot) — use immediately const vpGem = document.getElementById('ikey_p'); const vpGemId = vpGem ? (vpGem.getAttribute('onmouseover') || '').match(/set_infopane_item\((\d+)\)/) : null; if (vpGemId && vpGemId[1] === '10007') { if (hasUsableGem('spirit')) return { type: 'item', id: 'p', selfTarget: true }; } // Spirit draughts/potions — only at SP < threshold if (STATE.sp < CFG.spiritPotionSP) { for (const [slot, info] of Object.entries(STATE.itemsKnown)) { if (slot === 'p') continue; const def = ITEMS[parseInt(info)]; if (def && def.t === 'spirit') return { type: 'item', id: slot, selfTarget: true }; } } // 4. Debuffs — conservative: Imperil only on bosses/rares or 5+ mobs (Grindfest) // Weaken only on high-threat (SP >85%) or bosses. Estoc already applies // Penetrated Armor natively, so Imperil on 2-mob waves is wasteful. if (CFG.autoDebuff && STATE.mp > 0.35) { // Imperil: bosses only, or 5+ mobs in Grindfest (Estoc handles <5) if (hasReadySpell('Imperil') && (anyRareMonster() || STATE.monsters.length >= 5)) { const b = findStrongestMonster(); if (b >= 0 && !checkMonsterDebuff(b, 'imperil')) return { type: 'spell', name: 'Imperil', target: b, _reason: 'imperil' }; } // Weaken: only on monsters about to use special attacks (high SP) or bosses if (hasReadySpell('Weaken') && (anyRareMonster() || hasHighThreat(THREAT_PX))) { const b = findDangerousMonster(); if (b >= 0 && !checkMonsterDebuff(b, 'weaken')) return { type: 'spell', name: 'Weaken', target: b, _reason: 'weaken' }; } } // 5. Weapon skills — prioritize high-threat monsters (high SP/OC bar) // If 2+ enemies have >85% SP bar, they're about to special — emergency const isHighThreat = hasHighThreat(THREAT_PX); if (isHighThreat) console.log('%c[HV] ⚠ HIGH THREAT: 2+ monsters with SP >85%', 'color:#f44'); const askillOC3 = CFG.skillOC || 80; if (STATE.oc >= askillOC3 || isHighThreat) { if (isHighThreat && STATE.oc < askillOC3) console.log('%c[HV] ⚠ emergency: using skill at OC=' + STATE.oc.toFixed(0), 'color:#f80'); // Emergency: 2+ monsters about to special — spend OC to kill them fast // Rending Blow: AoE armor pen vs 3+ enemies (reduced from 5 for IWBTH survivability) if (STATE.monsters.length >= 3 && STATE.skillsKnown.includes('Rending Blow')) { const t = isHighThreat ? findDangerousMonster() : findStrongestMonster(); if (t >= 0) return { type: 'skill', name: 'Rending Blow', target: t, _reason: isHighThreat ? 'threat' : 'oc' }; } // Shatter Strike: AoE stun vs 3+ enemies with armor break if (STATE.monsters.length >= 3 && STATE.skillsKnown.includes('Shatter Strike')) { const hasArmorBreak = STATE.monsters.some((m, i) => checkMonsterDebuff(i, 'penetrated_armor')); if (hasArmorBreak) { const t = isHighThreat ? findDangerousMonster() : findStrongestMonster(); if (t >= 0) return { type: 'skill', name: 'Shatter Strike', target: t, _reason: 'stun' }; } } // Great Cleave: boss/rare fights or single-target threat if (anyRareMonster() && STATE.skillsKnown.includes('Great Cleave')) { const t = isHighThreat ? findDangerousMonster() : findStrongestMonster(); if (t >= 0) return { type: 'skill', name: 'Great Cleave', target: t, _reason: isHighThreat ? 'threat' : 'boss' }; } // If high threat and no AoE skill available, use any weapon skill on the most dangerous if (isHighThreat && STATE.oc >= (CFG.skillOC || 80)) { const ps = ['Frenzied Blows', 'Skyward Sword', 'Iris Strike', 'Merciful Blow', 'Vital Strike', 'Shield Bash', 'Concussive Strike']; for (const sk of ps) { if (STATE.skillsKnown.includes(sk)) { const t = findDangerousMonster(); if (t >= 0) return { type: 'skill', name: sk, target: t, _reason: 'threat' }; } } } } // 5. Spirit gem auto-consume const spGem = document.getElementById('ikey_p'); const spGemId = spGem ? (spGem.getAttribute('onmouseover') || '').match(/set_infopane_item\((\d+)\)/) : null; if (spGemId && spGemId[1] === '10007') { if (hasUsableGem('spirit')) return { type: 'item', id: 'p', selfTarget: true, _reason: 'gem' }; } // Spirit potions — only at SP < threshold (Spark needs 50%) if (STATE.sp < CFG.spiritPotionSP) { for (const [slot, info] of Object.entries(STATE.itemsKnown)) { if (slot === 'p') continue; const def = ITEMS[parseInt(info)]; if (def && def.t === 'spirit') return { type: 'item', id: slot, selfTarget: true, _reason: `sp${(STATE.sp*100).toFixed(0)}` }; } } // 6. Damage spells const dmg = CFG.useAttackSpells ? getBestDamageSpell() : null; if (dmg && STATE.mp > 0.15) { const t = STATE.monsters.length > 1 ? findWeakestMonster() : 0; if (t >= 0 && STATE.monsters[t] && STATE.monsters[t].hasAttribute('onclick')) return { type: 'spell', name: dmg, target: t, _reason: 'dmg' }; } // 7. Channeling kickstart or basic attack { const k = kickstartChanneling(); if (k) return k; } // Consume channeling on the highest-MP buff that needs refreshing { const ch = findBestChannelingTarget(); if (ch) return ch; } const t = hasHighThreat(THREAT_PX) ? findDangerousMonster() : (STATE.monsters.length > 2 ? findOptimalDominoTarget() : findWeakestMonster()); if (t >= 0 && STATE.monsters[t] && STATE.monsters[t].hasAttribute('onclick')) return { type: 'attack', target: t, _reason: hasHighThreat(THREAT_PX) ? 'threat' : 'fallback' }; return null; } // ═══════════════════════════════════════════════════════════════════════ // ACTION EXECUTOR — carry out recommended actions // ═══════════════════════════════════════════════════════════════════════ function executeAction(a) { if (!a) return false; let result = false; switch (a.type) { case 'attack': result = attackMonster(a.target); break; case 'spell': result = a.selfTarget ? castSelfSpell(a.name) : castTargetSpell(a.name, a.target); break; case 'skill': result = useSkill(a.name, a.target); break; case 'item': result = useItem(a.id); break; case 'toggle_spirit': result = toggleSpiritStance(); break; } if (result) { // After dispatching an action, stagger the debounce so we don't queue // another action while the game processes this one (typically ~500-1000ms) STATE._lastActionTime = Date.now(); } return result; } function attackMonster(i) { if (i < 0 || i >= STATE.monsters.length) return false; const m = STATE.monsters[i]; if (!m || !m.hasAttribute || !m.hasAttribute('onclick')) return false; m.click(); return true; } function castSelfSpell(n) { const s = $$('.btsd[onclick]').find(el => (el.getAttribute('onmouseover') || '').includes(`set_infopane_spell('${n}'`)); if (!s) return false; s.click(); return true; } function castTargetSpell(n, i) { const s = $$('.btsd[onclick]').find(el => (el.getAttribute('onmouseover') || '').includes(`set_infopane_spell('${n}'`)); if (!s) return false; s.click(); // Target selection: click immediately, no setTimeout delay needed. // HV's native lock_action handles the state transition synchronously. if (i >= 0 && i < STATE.monsters.length) { const m = STATE.monsters[i]; if (m && m.hasAttribute && m.hasAttribute('onclick')) m.click(); } return true; } function useItem(id) { let it = document.getElementById('ikey_' + id); // Fallback for auto_ slot IDs (on-cooldown items without explicit DOM id): // search for element with matching onmouseover item ID if (!it && typeof id === 'string' && id.startsWith('auto_')) { const rawId = id.replace('auto_', ''); const itemPane = document.getElementById('pane_item'); if (itemPane) { it = $$('div[onmouseover*="set_infopane_item(' + rawId + ')"]', itemPane)[0]; } } if (!it) return false; // Track that we used the P-slot gem so we don't retry stale state if (id === 'p') STATE._mysticUsed = true; dummy.setAttribute('onclick', it.getAttribute('onmouseover')); dummy.click(); it.click(); return true; } function useSkill(n, i) { let el = null; // Try quickbar first for (const e of $$('#quickbar > .btqs[onclick]')) { if ((e.getAttribute('onmouseover') || '').includes(`set_infopane_spell('${n}'`)) { el = e; break; } } // Try spellbook if (!el) { el = $$('.btsd[onclick]').find(e => (e.getAttribute('onmouseover') || '').includes(`set_infopane_spell('${n}'`)); } // Fallback: onclick match if (!el) { for (const e of $$('.btqb[onclick]')) { if ((e.getAttribute('onclick') || '').includes(n)) { el = e; break; } } } // Fallback: image match if (!el) { for (const e of $$('.btqb img')) { if ((e.src || '').toLowerCase().includes(n.toLowerCase().replace(/\s+/g, '_'))) { el = e.parentElement; break; } } } if (!el) return false; el.click(); // Click target immediately — no setTimeout needed if (i >= 0 && i < STATE.monsters.length) { const m = STATE.monsters[i]; if (m && m.hasAttribute && m.hasAttribute('onclick')) m.click(); } return true; } function toggleSpiritStance() { const t = document.getElementById('ckey_spirit'); if (!t) return false; t.click(); return true; } // ═══════════════════════════════════════════════════════════════════════ // HOVER SYSTEM — mouse-over monster actions // ═══════════════════════════════════════════════════════════════════════ function setupHover() { if (!CFG.hoverEnabled) return; STATE.monsters.forEach((m, i) => { if (!m || m.dataset.hvHover) return; m.dataset.hvHover = '1'; const area = m.querySelector('.btm6') || m; area.addEventListener('mouseenter', () => { STATE.hoverTarget = i; if (!STATE.interruptHover && !STATE.interruptAlert) { const ac = getSmartAction(); if (ac) executeAction(ac); } }); area.addEventListener('mouseleave', () => { STATE.hoverTarget = -1; }); }); // RiddleMaster blocks hover if (document.getElementById('riddlemaster')) { STATE.interruptHover = true; } } // ═══════════════════════════════════════════════════════════════════════ // KEYBINDINGS — keyboard shortcuts for battle // ═══════════════════════════════════════════════════════════════════════ let keybindingsSetup = false; const Q_DEBOUNCE_MS = 300; // Ignore Q repeats faster than this function setupKeybindings() { if (keybindingsSetup) return; keybindingsSetup = true; document.addEventListener('keydown', function(e) { // Settings — comma key if (e.keyCode === KEYS.COMMA) { if (isBattlePage()) { e.preventDefault(); STATE.settingsVisible = !STATE.settingsVisible; toggleSettings(); return; } } // Main action hotkey (default: Q) if (e.code === CFG.hotkey && !e.ctrlKey && !e.altKey && !e.metaKey) { if (!isInputFocused() && isBattlePage()) { // Debounce: ignore key-repeats until game processes the action const now = Date.now(); if (now - (STATE._lastActionTime || 0) < Q_DEBOUNCE_MS) return; STATE._lastActionTime = now; console.log('%c[HV] Q pressed — checking action...', 'color:#888'); parseBattleState(); // Debug: show full battle state const activeBuffs = Object.entries(STATE.buffs) .filter(([k, v]) => v > 0 && k !== 'regen' || v > 0) .map(([k, v]) => `${k}=${v}`).join(' '); // Monster SP bars (threat levels) const threatLevels = STATE.monsters.map((m, i) => { const sp = STATE.monsterSp[i] || 0; return `${i}:${sp}`; }).join(' '); const curMp = parseInt((document.getElementById('vrm') || {}).textContent) || 0; const curHp = parseInt((document.getElementById('vrhd') || {}).textContent) || 0; console.log( `%c[HV] ch=${STATE.channeling} hp=${curHp} mp=${curMp}(${(STATE.mp*100).toFixed(0)}%) ` + `sp=${(STATE.sp*100).toFixed(0)}% oc=${STATE.oc.toFixed(0)} ` + `mon:${STATE.monsters.length} ` + `buffs: ${activeBuffs} | spBars: ${threatLevels}`, 'color:#888' ); const a = getRecommendedAction(); if (a) { e.preventDefault(); // Show explicit action details let label = ''; if (a.type === 'spell') { label = a.name + (a.target >= 0 ? ' → monster ' + a.target : ' (self)'); } else if (a.type === 'skill') { label = a.name + ' → monster ' + a.target; } else if (a.type === 'item') { const itemDef = ITEMS[parseInt(STATE.itemsKnown[a.id] || '0')]; label = (itemDef ? itemDef.n : a.id) + (a.selfTarget ? ' (self)' : ''); } else if (a.type === 'attack') { label = 'monster ' + a.target; } else { label = a.target >= 0 ? 'monster ' + a.target : a.name || a.id; } console.log(`%c[HV] ▶ ${a.type} → ${label}${a._reason ? ' (' + a._reason + ')' : ''}`, 'color:#0f0'); executeAction(a); } } } // Hover toggle (H) if (e.code === 'KeyH' && !e.ctrlKey && !e.altKey && !e.metaKey && !isInputFocused()) { STATE.interruptHover = !STATE.interruptHover; console.log(`%c[HV] Hover ${STATE.interruptHover ? 'OFF' : 'ON'}`, 'color:#f80'); } // Emergency heal (C) — always cast Cure/Full-Cure regardless of strategy if (e.code === 'KeyC' && !e.ctrlKey && !e.altKey && !e.metaKey && !isInputFocused()) { const c = hasSpell('Full-Cure') ? 'Full-Cure' : hasSpell('Cure') ? 'Cure' : null; if (c) { console.log(`%c[HV] 🚑 Emergency: casting ${c}`, 'color:#f44'); castSelfSpell(c); } } }); console.log('%c⌨ [HV] Keys: Q=action H=hover C=cure ,=settings', 'color:#0f0;font-size:11px'); } // ═══════════════════════════════════════════════════════════════════════ // UI OVERLAYS — cooldowns, durations, alerts, monster numbers, monster HP // ═══════════════════════════════════════════════════════════════════════ function updateCooldownDisplay() { if (!CFG.showCooldowns) return; $$('.hv-cd-overlay').forEach(e => e.remove()); $$('.btqb').forEach(el => { const img = el.querySelector('img'); if (!img) return; const src = (img.src || '').toLowerCase(); for (const [k, v] of Object.entries(STATE.cooldowns)) { if (v <= 0) continue; if (src.includes(k.toLowerCase()) || src.includes(k.replace(/_/g, ''))) { const o = document.createElement('div'); o.className = 'hv-cd-overlay'; o.style.cssText = 'position:absolute;top:0;right:0;background:rgba(0,0,0,0.7);color:#f00;font-size:9px;font-weight:bold;padding:0 2px;border-radius:2px;pointer-events:none'; o.textContent = v; el.style.position = 'relative'; el.appendChild(o); break; } } }); } function updateDurationDisplay() { if (!CFG.showDurations) return; $$('.hv-dur-overlay').forEach(e => e.remove()); const pane = document.getElementById('pane_effects'); if (!pane) return; $$('img[onmouseover]', pane).forEach(img => { const omo = img.getAttribute('onmouseover') || ''; const dur = omo.match(/(\d+)\s*turns?\s*rem/); if (!dur) return; const t = parseInt(dur[1]); const st = omo.match(/(\d+)\s*stacks?/i); const o = document.createElement('div'); o.className = 'hv-dur-overlay'; o.style.cssText = `position:absolute;bottom:-2px;left:50%;transform:translateX(-50%);background:${t < 3 ? '#f44' : '#44f'};color:#fff;font-size:8px;font-weight:bold;padding:0 2px;border-radius:2px;pointer-events:none;z-index:1`; o.textContent = st ? `${t}x${parseInt(st[1])}` : t; img.parentElement.style.position = 'relative'; img.parentElement.appendChild(o); }); } function updateAlertColours() { if (!CFG.alertColours) return; let bg = '#EDEBDF'; STATE.interruptAlert = false; if (!$('img[src$="bar_dgreen.png"]') && $('img[src$="fallenshield.png"]')) { bg = 'magenta'; STATE.interruptAlert = true; } else if (STATE.hp < 0.25) { bg = '#ff4488'; STATE.interruptAlert = true; } else if (STATE.mp < 0.15) { bg = '#4444aa'; } else if (Object.values(STATE.buffs).some(d => d < 2 && d > 0)) { bg = '#88ccff'; } const v = document.getElementById('pane_vitals'); if (v) v.style.background = bg; } function addMonsterNumbers() { if (!CFG.showMonsterNumbers) return; STATE.monsters.forEach((m, i) => { if (!m || !m.querySelector || m.querySelector('.hv-monster-num')) return; const b = m.querySelector('.btm1'); if (!b) return; const s = document.createElement('span'); s.className = 'hv-monster-num'; s.style.cssText = 'font-weight:bold;margin-right:3px;color:#999'; s.textContent = (i + 1); b.insertBefore(s, b.firstChild); }); } function updateMonsterHPDisplay() { if (!CFG.showMonsterHP) return; STATE.monsters.forEach((m, i) => { if (!m || !m.hasAttribute || !m.hasAttribute('onclick')) return; const n = m.querySelector('.btm1'); if (!n) return; const nm = (n.textContent || '').replace(/^\d+\s*/, '').trim(); const md = STATE.monsterData[nm]; if (!md || !md.hp || md.seen < 3) return; const hpBar = m.querySelector('img[src$="nbargreen.png"]'); if (!hpBar) return; const r = clamp(parseInt(hpBar.style.width || '') / 120, 0.01, 1); const txt = `HP: ${Math.max(1, Math.round(r * md.hp)).toLocaleString()} / ${md.hp.toLocaleString()}`; const ex = m.querySelector('.hv-monster-hp'); if (ex) { ex.textContent = txt; return; } const d = document.createElement('div'); d.className = 'hv-monster-hp'; d.style.cssText = 'display:inline-block;position:relative;left:204px;top:-20px;font-size:9px;color:#888'; d.textContent = txt; m.appendChild(d); }); } function saveMonsterData() { STATE.monsters.forEach((m, i) => { if (!m || !m.hasAttribute || !m.hasAttribute('onclick')) return; const n = m.querySelector('.btm1'); if (!n) return; const nm = (n.textContent || '').replace(/^\d+\s*/, '').trim(); if (!nm) return; const hpBar = m.querySelector('img[src$="nbargreen.png"]'); if (hpBar) { const r = clamp(parseInt(hpBar.style.width || '') / 120, 0.01, 1); if (!STATE.monsterData[nm]) STATE.monsterData[nm] = { hp: 0, seen: 0 }; STATE.monsterData[nm].hp = Math.max( STATE.monsterData[nm].hp, Math.round(STATE.monsterData[nm].hp * 0.7 + 1000 / r * 0.3) ); STATE.monsterData[nm].seen++; } }); try { localStorage[SP + 'monsters'] = JSON.stringify(STATE.monsterData); } catch (e) {} } function refreshUI() { if (CFG.showDurations) updateDurationDisplay(); if (CFG.showCooldowns) updateCooldownDisplay(); if (CFG.alertColours) updateAlertColours(); if (CFG.showMonsterNumbers) addMonsterNumbers(); if (CFG.showMonsterHP) updateMonsterHPDisplay(); } // ═══════════════════════════════════════════════════════════════════════ // SETTINGS PANEL — in-battle configuration UI // ═══════════════════════════════════════════════════════════════════════ function toggleSettings() { if (STATE.settingsVisible) { closeSettings(); } else { openSettings(); } } function closeSettings() { const p = document.getElementById('hv-settings-panel'); if (p) p.remove(); STATE.settingsVisible = false; } function openSettings() { if (document.getElementById('hv-settings-panel')) return; STATE.settingsVisible = true; const p = document.createElement('div'); p.id = 'hv-settings-panel'; p.style.cssText = css({ position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: '520px', maxHeight: '80vh', overflowY: 'auto', background: '#1a1a2e', color: '#ccc', zIndex: '99999', borderRadius: '8px', padding: '16px', fontSize: '12px', fontFamily: 'monospace', boxShadow: '0 0 30px rgba(0,0,0,0.8)', }); const mkTog = (l, k) => ``; const mkNum = (l, k, st) => `
${getAttrAdvice(style)}
${getSpellAdvice()}
| Ability | AP | Lv | Status |
|---|---|---|---|
| ${a.name} | ${a.apCost} | ${a.lvlReq} | ${lbl} |