GGsimida / EasyExchangeCredit

// ==UserScript==
// @name         EasyExchangeCredit
// @namespace    http://tampermonkey.net/
// @version      0.24
// @description  简单兑换积分成体力
// @license      MIT
// @author       Wentao MA
// @copyright    2019, Wentao MA (https://openuserjs.org//users/GGsimida)
// @updateURL    https://openuserjs.org/meta/GGsimida/EasyExchangeCredit.meta.js
// @match        http*://steamcn.com/home.php?mod=spacecp&ac=credit&op=exchange
// @match        http*://keylol.com/home.php?mod=spacecp&ac=credit&op=exchange
// @run-at       document-idle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_deleteValue
// ==/UserScript==

var PWDNAME = "steamcn"; //使用此NAME保存密码
var FIRSTRUN = "firstrun"; //使用此检测是否第一次运行,并存储结束蒸汽数量
var stopBalance;
var pwd = "";
var stopButton;

(function() {
    'use strict';

    if(getPassword()){
        if(!GM_getValue(FIRSTRUN)){
            if(!getStopBalance()){
                return;
            }
            GM_setValue(FIRSTRUN,stopBalance);
        }
        document.body.addEventListener("keypress", pressToStop);
        stopBalance = GM_getValue(FIRSTRUN);
        if(checkCredit()){
            exchangeCredit();
        }
    }
})();

function exchangeCredit(){
    document.getElementById("exchangeamount").value = 3;//每次兑换3蒸汽
    exchangecalcredit();
    document.querySelector("input[type=\"password\"]").value = pwd;
    document.getElementById("exchangeform").submit();
}

function getPassword(){
    if(!GM_getValue(PWDNAME)){
        pwd = prompt("请输入你的密码(当兑换结束时会自动删除密码):", "");
        if (pwd !== null && pwd !== "") {
            GM_setValue(PWDNAME, pwd);
            return true;
        }else{
            alert("没有输密码 怎么种庄稼");
            return false;
        }
    }else{
        pwd = GM_getValue(PWDNAME);
        return true;
    }
}

function getStopBalance(){
    stopBalance = prompt("请输入结束时蒸汽数量(至少50哦):", "50");
    stopBalance = parseInt(stopBalance);
    if((!stopBalance)|| stopBalance<50){
        alert("哎呀,输入的数字不太对...");
        stopExchange();
        return false;
    }
    return true;
}

function checkCredit(){
    //获取蒸汽数量,<=stopBalance自动停止
    var balance =  parseInt(document.querySelectorAll(".creditl.mtm.bbda.cl li")[1].lastChild.textContent);
    if(balance <= stopBalance){
        alert("蒸汽兑换结束\n剩余蒸汽:"+balance);
        stopExchange();
        return false;
    }
    return true;
}

function pressToStop(event){
    document.body.removeEventListener("keydown", pressToStop);
    var kCode = event.which || event.keyCode;
    if (kCode == 83 || kCode == 115) {
        stopExchange();
    }
}

function stopExchange(){
    if(GM_getValue(PWDNAME)){
        GM_deleteValue(PWDNAME);
    }
    if(GM_getValue(FIRSTRUN)){
        GM_deleteValue(FIRSTRUN);
    }
    alert("已经停止自动兑换并删除保存密码\n\n重新开始请刷新页面");
}