Level Progress Estimation

Adds a fractional level pill to the PDA header tray with full estimation logic.

2026/04/13のページです。最新版はこちら

スクリプトをインストールするには、Tampermonkey, GreasemonkeyViolentmonkey のような拡張機能のインストールが必要です。

You will need to install an extension such as Tampermonkey to install this script.

スクリプトをインストールするには、TampermonkeyViolentmonkey のような拡張機能のインストールが必要です。

スクリプトをインストールするには、TampermonkeyUserscripts のような拡張機能のインストールが必要です。

このスクリプトをインストールするには、Tampermonkeyなどの拡張機能をインストールする必要があります。

このスクリプトをインストールするには、ユーザースクリプト管理ツールの拡張機能をインストールする必要があります。

(ユーザースクリプト管理ツールは設定済みなのでインストール!)

このスタイルをインストールするには、Stylusなどの拡張機能をインストールする必要があります。

このスタイルをインストールするには、Stylus などの拡張機能をインストールする必要があります。

このスタイルをインストールするには、Stylus tなどの拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

(ユーザースタイル管理ツールは設定済みなのでインストール!)

このスクリプトの質問や評価の投稿はこちら通報はこちらへお寄せください
// ==UserScript==
// @name         Level Progress Estimation 
// @namespace    http://tampermonkey.net/
// @version      1.2.0
// @description  Adds a fractional level pill to the PDA header tray with full estimation logic.
// @author       Pint-Shot-Riot 
// @match        https://www.torn.com/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_xmlhttpRequest
// @connect      api.torn.com
// @license MIT
// ==/UserScript==

(function () {
  "use strict";

  const INACTIVE_THRESHOLD = 365 * 24 * 60 * 60; // 1 year in seconds
  const PAGE_SIZE = 100;

  // --- API KEY HANDLING ---
  async function getApiKey() {
    let key = localStorage.getItem("APIKey");
    if (!key || key.length < 10) key = await GM_getValue("torn_api_key", "");
    
    if (!key || key.length < 10) {
      key = prompt("Please enter your Torn API Key to enable fractional level estimation:");
      if (key) await GM_setValue("torn_api_key", key.trim());
    }
    return key ? key.trim() : null;
  }

  async function fetchTorn(url) {
    return new Promise((resolve, reject) => {
      GM_xmlhttpRequest({
        method: "GET",
        url: url,
        onload: (res) => {
          try {
            const data = JSON.parse(res.responseText);
            if (data.error) reject(data.error.error);
            else resolve(data);
          } catch (e) { reject("JSON Error"); }
        },
        onerror: (err) => reject(err)
      });
    });
  }

  // --- FRACTIONAL ESTIMATION LOGIC ---
  async function getAccurateLevel() {
    const key = await getApiKey();
    if (!key) return null;

    try {
      // 1. Get your current Level and HOF Rank
      const user = await fetchTorn(`https://api.torn.com/v2/user/hof?key=${key}`);
      const { value: level, rank } = user.hof.level;
      
      if (level >= 100) return "100.00";
      if (level <= 1) return level.toString();

      // 2. Fetch HOF pages near your rank to find "anchors"
      const offset = Math.max(0, Math.floor((rank - 50) / PAGE_SIZE) * PAGE_SIZE);
      const hofData = await fetchTorn(`https://api.torn.com/v2/torn/hof?limit=${PAGE_SIZE}&offset=${offset}&cat=level&key=${key}`);
      const players = hofData.hof || [];
      
      // Find the inactive player at YOUR level with the best rank (Current Anchor)
      const currentAnchor = players
        .filter(p => p.level === level && (Date.now()/1000 - p.last_action) > INACTIVE_THRESHOLD && p.position < rank)
        .sort((a, b) => b.position - a.position)[0];

      // Find the inactive player at LEVEL-1 with the best rank (Lower Anchor)
      // If not on this page, we fetch the next page to find the transition
      let lowerAnchor = players
        .filter(p => p.level === (level - 1) && (Date.now()/1000 - p.last_action) > INACTIVE_THRESHOLD && p.position > rank)
        .sort((a, b) => a.position - b.position)[0];

      // If lower anchor wasn't on the first page, grab the next page
      if (!lowerAnchor) {
          const nextHof = await fetchTorn(`https://api.torn.com/v2/torn/hof?limit=${PAGE_SIZE}&offset=${offset + PAGE_SIZE}&cat=level&key=${key}`);
          const players2 = nextHof.hof || [];
          lowerAnchor = players2
            .filter(p => p.level === (level - 1) && (Date.now()/1000 - p.last_action) > INACTIVE_THRESHOLD)
            .sort((a, b) => a.position - b.position)[0];
      }

      if (!currentAnchor || !lowerAnchor) return level.toFixed(2);

      // 3. Calculate the fraction
      // Progress = (Lower Anchor Rank - Your Rank) / (Lower Anchor Rank - Current Anchor Rank)
      const range = lowerAnchor.position - currentAnchor.position;
      const yourProgress = lowerAnchor.position - rank;
      const fraction = Math.max(0, Math.min(0.99, yourProgress / range));
      
      return (level + fraction).toFixed(2);
    } catch (e) {
      console.error("Accurate Level Error:", e);
      return null;
    }
  }

  // --- UI INJECTION ---
  function injectIcon(val) {
    if (document.getElementById('acc-lvl-pill')) {
      document.getElementById('acc-lvl-val').textContent = val;
      return;
    }

    // Target PDA Header Tray
    const tray = document.querySelector('[class*="right_"]') || 
                 document.querySelector('[class*="header-buttons"]') ||
                 document.querySelector('.header-navigation');

    if (!tray) return;

    const pill = document.createElement('div');
    pill.id = 'acc-lvl-pill';
    // Style matches Torn dark theme
    pill.style = "display: inline-flex; align-items: center; background: #333; border: 1px solid #444; border-radius: 10px; padding: 2px 8px; margin: 0 4px; height: 22px; vertical-align: middle; cursor: pointer; box-shadow: 0 1px 3px rgba(0,0,0,0.5);";
    pill.innerHTML = `
      <span style="color: #85b200; font-size: 10px; font-weight: bold; margin-right: 4px; font-family: sans-serif;">LV</span>
      <span id="acc-lvl-val" style="color: #fff; font-size: 11px; font-family: 'Courier New', monospace; font-weight: bold;">${val}</span>
    `;

    pill.onclick = () => window.location.href = "/halloffame.php#/type=level";
    tray.prepend(pill);
  }

  async function run() {
    const level = await getAccurateLevel();
    if (level) {
      injectIcon(level);
      // Update the estimation every 10 minutes to save API calls
      setInterval(async () => {
        const updated = await getAccurateLevel();
        if (updated) injectIcon(updated);
      }, 600000);
      
      // Ensure the icon persists if PDA refreshes the header
      setInterval(() => injectIcon(level), 2000);
    }
  }

  if (document.readyState === "complete") run();
  else window.addEventListener("load", run);

})();