사용자:Hsl0/common.js: 두 판 사이의 차이

리버티게임, 모두가 만들어가는 자유로운 게임
imported>Hsl0
(플러그인 test설치)
(플러그인 Slideable, RankingSystem설치)
 
(사용자 2명의 중간 판 410개는 보이지 않습니다)
1번째 줄: 1번째 줄:
/* [[틀:JSON수정]] 차단 시작 */
/* [[틀:JSON수정]] 차단 시작 */
$('.uncy-jsonedit').remove();
function kill_uncy_jsonEdit() {
delete window.uncy_jsonEdit;
$('.uncy-jsonedit').remove();
}
kill_uncy_jsonEdit();
/* [[틀:JSON수정]] 차단 끝 */
/* [[틀:JSON수정]] 차단 끝 */


/**
/* 모바일용 개발자 도구 실행 버튼 만들기 */
* punycode.js - 퓨니코드 처리 라이브러리
// function startFirebug() {
* DB2에서 미디어위키 옵션 저장소 키의 문자열 제한 우회를 위해 사용중
// mw.loader.load('/index.php?title=사용자:hsl0/firebug.js&action=raw&ctype=text/javascript');
* 제작자: bestiejs - https://github.com/bestiejs/punycode.js
// }
* 출처: CDNJS - https://cdnjs.cloudflare.com/ajax/libs/punycode/1.4.1/punycode.min.js
// function startEruda() {
**/
// mw.loader.load('/index.php?title=사용자:hsl0/eruda.js&action=raw&ctype=text/javascript');
!function(e){function o(e){throw new RangeError(T[e])}function n(e,o){for(var n=e.length,r=[];n--;)r[n]=o(e[n]);return r}function r(e,o){var r=e.split("@"),t="";r.length>1&&(t=r[0]+"@",e=r[1]),e=e.replace(S,".");var u=e.split("."),i=n(u,o).join(".");return t+i}function t(e){for(var o,n,r=[],t=0,u=e.length;u>t;)o=e.charCodeAt(t++),o>=55296&&56319>=o&&u>t?(n=e.charCodeAt(t++),56320==(64512&n)?r.push(((1023&o)<<10)+(1023&n)+65536):(r.push(o),t--)):r.push(o);return r}function u(e){return n(e,function(e){var o="";return e>65535&&(e-=65536,o+=P(e>>>10&1023|55296),e=56320|1023&e),o+=P(e)}).join("")}function i(e){return 10>e-48?e-22:26>e-65?e-65:26>e-97?e-97:b}function f(e,o){return e+22+75*(26>e)-((0!=o)<<5)}function c(e,o,n){var r=0;for(e=n?M(e/j):e>>1,e+=M(e/o);e>L*C>>1;r+=b)e=M(e/L);return M(r+(L+1)*e/(e+m))}function l(e){var n,r,t,f,l,s,d,a,p,h,v=[],g=e.length,w=0,m=I,j=A;for(r=e.lastIndexOf(E),0>r&&(r=0),t=0;r>t;++t)e.charCodeAt(t)>=128&&o("not-basic"),v.push(e.charCodeAt(t));for(f=r>0?r+1:0;g>f;){for(l=w,s=1,d=b;f>=g&&o("invalid-input"),a=i(e.charCodeAt(f++)),(a>=b||a>M((x-w)/s))&&o("overflow"),w+=a*s,p=j>=d?y:d>=j+C?C:d-j,!(p>a);d+=b)h=b-p,s>M(x/h)&&o("overflow"),s*=h;n=v.length+1,j=c(w-l,n,0==l),M(w/n)>x-m&&o("overflow"),m+=M(w/n),w%=n,v.splice(w++,0,m)}return u(v)}function s(e){var n,r,u,i,l,s,d,a,p,h,v,g,w,m,j,F=[];for(e=t(e),g=e.length,n=I,r=0,l=A,s=0;g>s;++s)v=e[s],128>v&&F.push(P(v));for(u=i=F.length,i&&F.push(E);g>u;){for(d=x,s=0;g>s;++s)v=e[s],v>=n&&d>v&&(d=v);for(w=u+1,d-n>M((x-r)/w)&&o("overflow"),r+=(d-n)*w,n=d,s=0;g>s;++s)if(v=e[s],n>v&&++r>x&&o("overflow"),v==n){for(a=r,p=b;h=l>=p?y:p>=l+C?C:p-l,!(h>a);p+=b)j=a-h,m=b-h,F.push(P(f(h+j%m,0))),a=M(j/m);F.push(P(f(a,0))),l=c(r,w,u==i),r=0,++u}++r,++n}return F.join("")}function d(e){return r(e,function(e){return F.test(e)?l(e.slice(4).toLowerCase()):e})}function a(e){return r(e,function(e){return O.test(e)?"xn--"+s(e):e})}var p="object"==typeof exports&&exports&&!exports.nodeType&&exports,h="object"==typeof module&&module&&!module.nodeType&&module,v="object"==typeof global&&global;v.global!==v&&v.window!==v&&v.self!==v||(e=v);var g,w,x=2147483647,b=36,y=1,C=26,m=38,j=700,A=72,I=128,E="-",F=/^xn--/,O=/[^\x20-\x7E]/,S=/[\x2E\u3002\uFF0E\uFF61]/g,T={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},L=b-y,M=Math.floor,P=String.fromCharCode;if(g={version:"1.4.1",ucs2:{decode:t,encode:u},decode:l,encode:s,toASCII:a,toUnicode:d},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return g});else if(p&&h)if(module.exports==p)h.exports=g;else for(w in g)g.hasOwnProperty(w)&&(p[w]=g[w]);else e.punycode=g}(this);
// }
//# sourceMappingURL=./punycode.min.js.map
// function createDevToolsButton() {
/* punycode.js 끝 */
// $('#footer-places')
// //.append($('<li id="footer-places-devtools-firebug" />').append($('<a>개발자 도구(Firebug)</a>').click(startFirebug)))
// .append($('<li id="footer-places-devtools-eruda" />').append($('<a>개발자 도구</a>').click(startEruda)));
// }
// $(createDevToolsButton);
 
function testHook(name) {
mw.hook(name).add(function() {
logStack.push([name].concat(arguments));
console.log.apply(null, [name].concat(arguments));
});
}
 
var logStack = [];
 
testHook('postEdit');
testHook('postEdit.afterRemoval');
testHook('structuredChangeFilters.ui.initialized');
testHook('wikipage.categories');
testHook('wikipage.collapsibleContent');
testHook('wikipage.content');
testHook('wikipage.diff');
testHook('wikipage.editform');
testHook('wikipage.indicators');
 
 
 
/** 플러그인 p21***************************
* 블랙잭
* 버전 => 0.840a4
* 작성자 : [[사용자:Riemann|Riemann]]
* JSON => p21 = {"name":"p21","descript":"블랙잭","version":"0.840a4","local":true,"creat":"Riemann","state":"사용자:Riemann/p21","executable":true};  
*/
function plugin_p21(){
  if($("[data-name='p21']").length >= 1){
var title = mw.config.get('wgPageName');
if (title.slice( 1, 2 ) == "라") {
    var blind = true;
    var defa = 20;
} else {
    var blind = false;
    var defa = 10;
}
var mult = defa;
$("#multiplier").text(mult);


var fetchScript = fetch? function fetchScript(url, integrity) {
var coins = 100;
    return fetch(url, {
var wincount = 0;
        header: {
var losecount = 0;
            Accept: [
//$("#console").text("스코어: " + coins + "점");
                'application/javascript',
$("#console").text("스코어: " + wincount + "승 " + losecount + "패");
                'application/ecmascript',
$("#console").append("\n블랙잭에 오신 것을 환영합니다.");
                'text/javascript',
                'application/x-javascript',
                '*/*'
            ]
        },
        integrity: integrity
    }).then(function(res) {
        return res.text().then(function(text) {
        new Function(text)();
        return new $.Deferred().resolve(text, res.statusText, res).promise();
        });
    });
} : $.getScript;


mw.loader.using([
const pcLst = [
     'mediawiki.notification',
0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAD,0xAE,
     'oojs-ui-core'
0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBD,0xBE,
]).then(function() {
0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCD,0xCE,
     var title = mw.config.get('wgPageName').split('/')[0];
0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDD,0xDE];
     var noti;
const pointData = {a1:1,a2:2,a3:3,a4:4,a5:5,a6:6,a7:7,a8:8,a9:9,aa:10,ab:10,ad:10,ae:10,b1:1,b2:2,b3:3,b4:4,b5:5,b6:6,b7:7,b8:8,b9:9,ba:10,bb:10,bd:10,be:10,c1:1,c2:2,c3:3,c4:4,c5:5,c6:6,c7:7,c8:8,c9:9,ca:10,cb:10,cd:10,ce:10,d1:1,d2:2,d3:3,d4:4,d5:5,d6:6,d7:7,d8:8,d9:9,da:10,db:10,dd:10,de:10};
     var currentSearch = searchParamToString(geturlSearch());
var pcSet = [];
function hexToChar(x) {
    return String.fromCharCode(0xD83C) +String.fromCharCode(x + 0xDC00);
}
function hexToStr(x) {
    return x.toString(16);
}
var dealerD, guestD;
$("#deal").click(function(){
    //$("#console").text("스코어: " + coins + "점");
    $("#console").text("스코어: " + wincount + "승 " + losecount + "패");
    $("#console").append("\n새 판을 엽니다.");
     $("#deal").css("display", "none");
    $("#dealerDeck").text("");
    $("#guestDeck").text("");
    pcSet = Object.create(pcLst);
     deal();
    return 0;
});
$("#hit").click(function(){
     hit();
    return 0;
});
$("#stand").click(function(){
    stand();
    return 0;
});
$("#surrender").click(function(){
    surrender();
    return 0;
});
$("#plus").click(function(){
    inc();
    return 0;
});
$("#minus").click(function(){
    dec();
    return 0;
});
$("#reset").click(function(){
    reset();
     return 0;
});
function reset() {
     mult = defa;
    $("#multiplier").text(mult);
}


    /* option key 인코딩
/*
        퓨니코드 + url인코딩
function inc() {
        % = _
    if (mult < 100) {
        _ = __
         mult += 2;
    */
    } else {
    function encode(key) {
         alert("최대 100 코인까지만 걸 수 있습니다.");
        return encodeURIComponent(punycode.toASCII(key))
         .replace(/\./g, '%2E')
        .replace(/!/g, '%21')
        .replace(/~/g, '%7E')
        .replace(/\*/g, '%2A')
        .replace(/'/g, '%27')
        .replace(/\(/g, '%28')
         .replace(/\)/g, '%29')
        .replace(/_/g, '__')
        .replace(/%/g, '_');
     }
     }
     function decode(key) {
     $("#multiplier").text(mult);
         return punycode.toUnicode(decodeURIComponent(key.replace(/_(?=[a-zA-Z0-9]{2})/g, '%').replace(/__/g, '_')));
}
 
function dec() {
    if (mult > 2) {
         mult -= 2;
    } else {
        alert("설마 빚을 판돈으로 거시려고요?");
     }
     }
    $("#multiplier").text(mult);
}
*/


     function parseJSON(json) {
function deal() {
         try {
    dealerD = [];
             return JSON.parse(json);
    guestD = [];
         } catch(e) {
    dealerD.push(cardPop());
             return;
    guestD.push(cardPop());
    dealerD.push(cardPop());
    guestD.push(cardPop());
    if (blind == true) {
        $("#dealerDeck").text("\u{1F0A0}\u{1F0A0}");
    } else {
        $("#dealerDeck").text(hexToChar(dealerD[0]) + "\u{1F0A0}");
    }
    $("#dealerS").text("?");
     if (blind == true) {
        $("#guestDeck").text("\u{1F0A0}\u{1F0A0}");
    } else {
        $("#guestDeck").text(hexToChar(guestD[0]) + hexToChar(guestD[1]));
    }
    var guestScore = [];
    var score = pointData[hexToStr(guestD[0])] + pointData[hexToStr(guestD[1])];
    $("#guestS").text(score);
    if ((pointData[hexToStr(guestD[0])] == 1 && pointData[hexToStr(guestD[1])] == 10) || (pointData[hexToStr(guestD[0])] == 10 && pointData[hexToStr(guestD[1])] == 1)) {
        $("#guestS").text(21);
        jack();
    } else {
        $("#hit").css("display", "inline-flex");
        $("#stand").css("display", "inline-flex");
        $("#surrender").css("display", "inline-flex");
    }
};
function hit() {
    $("#hit").css("display", "none");
    $("#stand").css("display", "none");
    $("#surrender").css("display", "none");
    guestD.push(cardPop());
    var guestDeq = "";
    for (i = 0; i < guestD.length; i++) {
         guestDeq += hexToChar(guestD[i]);
    }
    if (blind == true) {
        $("#guestDeck").text("\u{1F0A0}".repeat(guestDeq.length / 2));
    } else {
        $("#guestDeck").text(guestDeq);
    }
    var guestScore = [];
    var score = 0;
    for (i = 0; i < guestD.length; i++) {
        guestScore.push(pointData[hexToStr(guestD[i])]);
        score += guestScore[i];
    }
    $("#guestS").text(score);
    if (score == 21 || (score == 11 && guestScore.includes(1))) {
        $("#console").append("\n21점이므로 자동으로 스탠드를 외쳤습니다.")
        stand(dealerD,guestD);
    } else if (score > 21) {
        bust();
    } else  {
        $("#hit").css("display", "inline-flex");
        $("#stand").css("display", "inline-flex");
    }
    return 0;
}
function stand() {
    $("#hit").css("display", "none");
    $("#stand").css("display", "none");
    $("#surrender").css("display", "none");
    var dScore = 0;
    var dealerScore = []
    for (i = 0; i < dealerD.length; i++) {
        dealerScore.push(pointData[hexToStr(dealerD[i])]);
        dScore += dealerScore[i];
    }
    while (dScore < 17) {
        dealerD.push(cardPop());
        $("#console").append("\n딜러가 카드를 뽑았습니다.")
        dealerScore = [];
        dScore = 0;
        for (i = 0; i < dealerD.length; i++) {
             dealerScore.push(pointData[hexToStr(dealerD[i])]);
            dScore += dealerScore[i];
            dealerDeq += hexToChar(dealerD[i]);
         }
    }
    var dealerDeq = "";
    for (i = 0; i < dealerD.length; i++) {
             dealerDeq += hexToChar(dealerD[i]);
         }
         }
    $("#dealerS").text(dScore);
    $("#dealerDeck").text(dealerDeq);
    guestScore = [];
    score = 0;
    for (i = 0; i < guestD.length; i++) {
        guestScore.push(pointData[hexToStr(guestD[i])]);
        score += guestScore[i];
    }
    $("#guestS").text(score);
    if (score > 21) {
        bust()
    } else if (dScore > 21) {
        $("#console").append("\n딜러의 버스트.")
        win()
    } else {
        $("#console").append("\n딜러의 스탠드.")
        compare(dealerD,guestD);
    }
    return 0;
}
function compare() {
    var dealerScore = [];
    var dScore = 0;
    for (i = 0; i < dealerD.length; i++) {
        dealerScore.push(pointData[hexToStr(dealerD[i])]);
        dScore += dealerScore[i];
    }
    var guestScore = [];
    var score = 0;
    for (i = 0; i < guestD.length; i++) {
        guestScore.push(pointData[hexToStr(guestD[i])]);
        score += guestScore[i];
    }
    if (dScore < 12 && dealerScore.includes(1)) {
        dScore += 10
    }
    if (score < 12 && guestScore.includes(1)) {
        score += 10
    }
    $("#dealerS").text(dScore);
    $("#guestS").text(score);
    if (dScore > score) {
        lose()
    } else if (dScore == score) {
        push()
    } else {
        win()
    }
    return 0;
}
function win() {
    $("#console").append("\n축하합니다! 이겼습니다.")
    //$("#console").append("\n" + mult + "점을 얻었습니다.")
    //coins += mult;
    wincount += 1;
    $("#deal").css("display", "inline-flex");
    return 0;
}
function lose() {
    $("#console").append("\n졌습니다...")
    //$("#console").append("\n" + mult + "점을 잃었습니다.")
    //coins -= mult;
    losecount += 1;
    $("#deal").css("display", "inline-flex");
    publicAd();
    return 0;
}
function push() {
    $("#console").append("\n비겼습니다.")
    $("#deal").css("display", "inline-flex");
    return 0;
}
function surrender() {
    $("#hit").css("display", "none");
    $("#stand").css("display", "none");
    $("#surrender").css("display", "none");
    $("#console").append("\n이번 판을 포기하셨습니다 (패배로 처리됩니다).")
    //$("#console").append("\n" + (0.5 * mult) + "점을 잃었습니다.")
    //coins -= 0.5 * mult;
    losecount += 1;
    $("#deal").css("display", "inline-flex");
    publicAd();
    return 0;
}
function bust() {
    $("#console").append("\n버스트! 유감입니다. 졌습니다...")
    //$("#console").append("\n" + mult + "점을 잃었습니다.")
    //coins -= mult;
    losecount += 1;
    $("#hit").css("display", "none");
    $("#stand").css("display", "none");
    $("#deal").css("display", "inline-flex");
    publicAd();
    return 0;
}
function jack() {
    $("#console").append("\n블랙잭 달성! 축하합니다. 이겼습니다!")
    //$("#console").append("\n" + (1.5 * mult) + "점을 획득했습니다.")
    //coins += 1.5 * mult;
    wincount += 1;
    $("#deal").css("display", "inline-flex");
    return 0;
}
function publicAd() {
    if (coins < 0) {
        $("#notice").text("땀 흘려 번 돈이 아름답습니다.");
     }
     }
    return 0;
}
function cardPop() {
    var j, ret;
    j = Math.floor(Math.random() * pcSet.length);
    ret = pcSet[j];
    pcSet.splice(j,1);
    return ret;
}
  }


    // hybridStorage 서브셋 생성
}
    window.setStoragePrefix = function(storage, prefix, except, needEncode) {
$( plugin_p21 );
        if(mw.user.isAnon()) needEncode = false;
/* p21 끝 */


         var spp = new Proxy(storage, {
/** 플러그인 real369***************************
             get: function(target, prop, receiver) {
* real369 플레이
                 function keys() {
* 버전 => 1.1.7
                    return Object.keys(target).filter(function(key) {
* 작성자 : [[사용자:BANIP|BANIP]]
                        return key.startsWith(prefix);
* JSON => real369 = {"name":"real369","descript":"real369 플레이","version":"1.1.7","local":true,"creat":"BANIP","state":"Real 369/플러그인","executable":true};
                     });
*/
function plugin_real369(){
  if($("[data-name='real369']").length >= 1){
/**
* 지금 박수를 쳐야되는지 숫자를 외쳐야 하는지 알아 냅니다
* @param {number} number 지금 순서가 몇번째인지 넣는 칸.
* @return {number|Array[number]} 박수를 쳐야되는 상황이면 배열 안에 숫자를 담아 반환하고 아니면 파라미터를 반환.
*/
function getAnswer(number) {
    var rawNumber = number + "";
    var targetNumber = rawNumber.replace(/3|6|9/g, "");
    var diff = rawNumber.length - targetNumber.length;
    if (diff === 0)
        return number + "";
    else
        return "짝!".repeat(diff);
}
function isMobile() {
    return !(navigator.userAgent.match(/Android|iPhone|iPad|iPod/i) === null);
}
var GUI = /** @class */ (function () {
    function GUI() {
        this.domList = {
            retry: document.querySelector("#gamewrap .gamelink .retry"),
            answer: document.querySelector("#gamewrap .answer"),
            dialog: document.querySelector("#gamewrap .dialog"),
            progress: document.querySelector("#gamewrap .progress"),
            gamelink: document.querySelector("#gamewrap .gamelink")
        };
        this.bindOtherEvent();
        //this.start();
    }
    GUI.prototype.start = function () {
        this.domList.answer.innerHTML = "시작!";
        this.domList.dialog.innerHTML = "";
        this.domList.gamelink.style.display = "none";
        createGame(gui);
        input.setGame(game);
    };
    GUI.prototype.bindOtherEvent = function () {
         var _this = this;
        this.domList.retry.addEventListener("click", function () {
            if (game !== null)
                game.gameOver();
            _this.start();
        });
    };
    GUI.prototype.message = function (message) {
        var dialogNode = this.domList.dialog;
        var messageNode = document.createElement("li");
        messageNode.innerHTML = message;
        dialogNode.appendChild(messageNode);
        dialogNode.scrollTop = dialogNode.scrollHeight;
    };
    GUI.prototype.initOrder = function (userCount, startUser) {
        var orderStringCount = 8;
        var orderString = new Array(orderStringCount).fill("1")
            .map(function (v, i) { return (startUser + i) % userCount === 0 ? username : "COM" + (startUser + i) % userCount; })
             .join(" => ");
        this.message("게임이 시작되었습니다!!!");
        this.message("게임순서 : " + orderString + "...");
    };
    GUI.prototype.getProgressColor = function (progress) {
        var interval = [30, 60, 100];
        var color = ["green", "yellow", "red"];
        var index = interval.indexOf(interval.filter(function (v) { return v > progress; })[0]);
        return color[index];
    };
    GUI.prototype.resetTime = function (duration) {
        var _this = this;
        clearInterval(this.timerInterval);
        var startTime = Date.now();
        this.timerInterval = setInterval(function () {
            var now = Date.now();
            var progress = (now - startTime) / duration * 100 - 1;
            var progressColor = _this.getProgressColor(progress);
            _this.domList.progress.style.background = "linear-gradient(to right," + progressColor + " " + (100 - progress) + "%,white " + (100 - progress + 0.1) + "%)";
        }, 10);
    };
    GUI.prototype.setEnemyTurn = function (order) {
        this.nextUser = "COM" + order;
    };
    GUI.prototype.setMyTurn = function () {
        this.nextUser = username;
    };
    GUI.prototype.gameOver = function (reason, lastCount) {
        this.domList.answer.innerHTML = reason;
        this.message("게임이 끝났습니다!!");
        this.message("최종 카운트: " + lastCount);
        input.setGame(null);
        this.domList.gamelink.style.display = "block";
        clearInterval(this.timerInterval);
    };
    GUI.prototype.setNumber = function (number) {
        this.domList.answer.innerHTML = number;
    };
    GUI.prototype.sayNumber = function (number, name) {
        if (name === void 0) { name = this.nextUser; }
        this.message(name + " : " + number);
    };
    GUI.prototype.setHandClab = function (clab) {
        this.domList.answer.innerHTML = clab;
    };
    return GUI;
}());
var Game = /** @class */ (function () {
    function Game(gui, playerCount, time) {
        if (playerCount === void 0) { playerCount = 3; }
        if (time === void 0) { time = 1000; }
        this.gui = gui;
        this.playerCount = playerCount;
        this.time = time;
        this.order = Math.floor(Math.random() * playerCount);
        this.number = 1;
        gui.initOrder(playerCount, this.order);
        this.turnStart();
    }
    Game.prototype.next = function () {
        var prevNumber = getAnswer(Number(this.number));
        this.gui.sayNumber(prevNumber);
        this.order = (this.order + 1) % this.playerCount;
        this.handClab = "";
        this.number++;
        this.turnStart();
    };
    Game.prototype.turnStart = function () {
        this.gui.resetTime(this.time);
        if (this.order === 0)
            this.myTurn();
        else
            this.enemyTurn();
    };
    Game.prototype.enemyTurn = function () {
        var _this = this;
        this.gui.setEnemyTurn(this.order);
        this.turnTimeout = setTimeout(function () {
            _this.shortenTime();
            _this.next();
        }, this.time * Math.random());
    };
    Game.prototype.myTurn = function () {
        var _this = this;
        this.gui.setMyTurn();
        this.turnTimeout = setTimeout(function () {
            if (getAnswer(_this.number) === _this.handClab)
                 _this.next();
            else
                _this.gameOver("시간 초과!");
        }, this.time);
    };
    Game.prototype.sayNumber = function (answer) {
        clearTimeout(this.turnTimeout);
        var reasonGameOver = null;
        if (this.order > 0)
            reasonGameOver = "내 차례가 아닌데 말해버림!";
        else if (getAnswer(this.number) === answer)
            null;
        else
            reasonGameOver = "오답!";
        if (reasonGameOver === null)
            this.next();
        else {
            gui.sayNumber(answer, username);
            this.gameOver(reasonGameOver);
        }
    };
    Game.prototype.setHandClab = function (clab) {
        this.handClab = clab;
    };
    Game.prototype.gameOver = function (reason) {
        clearTimeout(this.turnTimeout);
        this.gui.gameOver(reason, this.number);
        game = null;
    };
    Game.prototype.shortenTime = function () {
        this.time *= 0.94;
    };
    return Game;
}());
var Input = /** @class */ (function () {
    function Input(game, gui) {
        this.game = game;
        this.gui = gui;
        this.clickEventType = isMobile() ? "touchstart" : "click";
        this.resetNumber();
        this.bindKeyBoardEvent();
        this.bindKeyPadEvent();
    }
    Input.prototype.setGame = function (game) {
        this.game = game;
    };
    Input.prototype.bindKeyBoardEvent = function () {
        var _this = this;
        document.addEventListener("keydown", function (e) {
            var key = e.key;
            if (["Enter", "Space"].some(function (v) { return v === key; }))
                return _this.pressEnter();
            else if (key === "BackSpace")
                _this.number = _this.number.slice(0, -1);
            else if (isNaN(parseInt(key)))
                return;
            else
                _this.number += key;
            _this.gui.setNumber(_this.number);
        });
    };
    Input.prototype.bindKeyPadEvent = function () {
        var _this = this;
        document.querySelectorAll(".keypad .key").forEach(function (node) {
            node.addEventListener(_this.clickEventType, function (e) {
                e.preventDefault();
                _this.number += e.target.dataset.num;
                _this.gui.setNumber(_this.number);
            });
        });
        document.querySelector(".keypad .enter").addEventListener(this.clickEventType, function (e) {
            e.preventDefault();
            _this.pressEnter();
        });
        document.querySelector(".keypad .reset").addEventListener(this.clickEventType, function (e) {
            e.preventDefault();
            _this.resetNumber();
            _this.gui.setNumber(_this.number);
        });
    };
    Input.prototype.pressEnter = function () {
        var _this = this;
        if (game == null || game == undefined)
            this.gui.message("아직 게임이 시작되지 않았어요.");
        clearTimeout(this.enterTimeout);
        if (this.number == "") {
            this.enterCount++;
            var answer_1 = "짝!".repeat(this.enterCount);
            this.gui.setHandClab(answer_1);
            this.game.setHandClab(answer_1);
            this.enterTimeout = setTimeout(function () {
                if (_this.game.order === 0) {
                     _this.game.sayNumber(answer_1);
                 }
                 }
                  
                 _this.resetNumber();
                return Reflect.get(Object.assign({
            }, 800);
                    length: (prop === 'length') && keys().length,
        }
                    getItem: function getItem(key) {
        else {
                        return target.getItem(prefix + (needEncode? encode(key) : key));
            this.game.sayNumber(this.number);
                    },
            this.resetNumber();
                    key: function key(index) {
        }
                        return decode(keys()[index].slice(prefix.length));
    };
                    },
    ;
                    removeItem: function removeItem(key) {
    Input.prototype.resetNumber = function () {
                        return target.removeItem(prefix + (needEncode? encode(key) : key)).then(function() {
        this.number = "";
                            return spp;
        this.enterCount = 0;
                        });
        this.gui.setNumber(this.number);
                    },
                    setItem: function setItem(key, value) {
                        return target.setItem(prefix + (needEncode? encode(key) : key), value).then(function() {
                            return spp;
                        });
                    }
                }, except), prop, receiver) || target.getItem(prefix + (needEncode? encode(prop) : prop));
            },
            set: function(target, prop, value) {
                return target.setItem(prefix + (needEncode? encode(prop) : prop), value);
            },
            deleteProperty: function(target, prop) {
                return target.removeItem(prefix + (needEncode? encode(prop) : prop));
            },
            has: function(target, prop) {
                Reflect.has(target, prefix + (needEncode? encode(prop) : prop));
            },
            ownKeys: function(target) {
                return Reflect.ownKeys(target).filter(function(key) {
                    return key.startsWith(prefix);
                }).map(function(key) {
                    return decode(key.slice(prefix.length));
                });
            }
        });
        return spp;
     };
     };
    return Input;
}());
var game = null;
var createGame = function (gui) { return game = new Game(gui, 4, 5000); };
var username = mw.config.values.wgUserName;
var gui = new GUI();
//createGame(gui);
var input = new Input(game, gui);


    /*
        anon = localStorage[*]
  }
        user = mw.user.options[userjs-*]
 
     */
}
     window.hybridStorage = (function() {
$( plugin_real369 );
        var action;
/* real369 끝 */
        var api = new mw.Api();
 
        var storage, action;
/** 플러그인 msgame***************************
        var saveOption = (function() {
* 스톱워치 게임
            var options = {};
* 버전 => 0.950
            var deferred = new $.Deferred();
* 작성자 : [[사용자:Riemann|Riemann]]  
            var timeout = null;
* JSON => msgame = {"name":"msgame","descript":"스톱워치 게임","version":"0.950","local":true,"creat":"Riemann","state":"사용자:Riemann/msgame","executable":true};
           
*/
            return function saveOption(key, value) {
function plugin_msgame(){
                if(timeout) clearTimeout(timeout);
  if($("[data-name='msgame']").length >= 1){
                options[key] = value;
  // 이부분에 코드 입력 //
                timeout = setTimeout(function() {
sc = 0
                    deferred.resolve(api.saveOptions(options));
cb = 0
                   
 
                    options = {};
bl = false;
                    timeout = null;
$(document.body).on("keydown", function(ev) {
                    deferred = new $.Deferred();
  if(ev.which == 13) {
                }, 100);
     if (bl == false) {
                return deferred.promise();
    bl = true
            };
      startF();
        })();
    } else {
        if(mw.user.isAnon()) {
      bl = false
            storage = new Proxy(localStorage, {
      stopF();
                get: function(target, prop, receiver) {
     }
                    var value = Reflect.get({
  }
                        length: target.length,
});
                        getItem: target.getItem,
 
                        key: target.key,
$("#msgame-start").on("click", function() {
                        removeItem: function removeItem(key) {
  bl = true
                            return Promise.resolve(target.removeItem(key));
startF();
                        },
});
                        setItem: function setItem(key, value) {
 
                            return Promise.resolve(target.setItem(key, value));
$("#msgame-stop").on("click", function() {
                        },
  bl = false
                        refresh: function refresh() {
stopF();
                            return Promise.resolve(storage);
});
                        },
 
                        needRefresh: false
function startF() {
                    }, prop, receiver) || target.getItem(prop);
  obj = Math.floor(Math.random() * 10) + 5;
                    return (value === null)? undefined : value;
  $("#msgame-start").css("display", "none");
                },
  $("#msgame-stop").css("display", "block");
                set: function(target, prop, value, receiver) {
  it = new Date();
                    return Promise.resolve(target.setItem(prop, value));
  si = setInterval(clockUpdate, 20)
                },
  $("#msgame-console").text(obj + " 초를 세세요.");
                deleteProperty: function(target, prop) {
}
                    return Promise.resolve(target.removeItem(prop));
 
function stopF() {
  $("#msgame-clockText").css("display", "inline");
  $("#msgame-stop").css("display", "none");
  $("#msgame-start").css("display", "block");
  clearInterval(si);
  ie = new Date();
  ifin = ie - it;
  $("#msgame-clockText").text(toMilliSec(ifin));
  finished(obj, ifin);
}
 
function clockUpdate() {
  ic = new Date();
  id = ic - it;
  ii = toMilliSec(id);
  $("#msgame-clockText").text(ii);
  if (obj * 1000 - id < 500 * cb && cb > 4 ) {
    $("#msgame-clockText").fadeOut();
  }
}
 
function toMilliSec(d) {
  return (Math.floor(d / 1000) + "\"" + ("" + d % 1000).padStart(3, "0")).padStart(6, "0");
}
 
function finished(a, b) {
  ath = a * 1000
  if (ath == b) {
    cbm = Math.floor(Math.pow(800, (1 + cb / 10)))
    $("#msgame-console").text("정확하시군요. " + cbm + " 점 드리겠습니다.");
    sc += cbm
    cb += 1
  } else if (Math.abs(ath - b) < 100) {
    cbm = Math.floor(Math.pow((500 / Math.abs(ath - b)), (1 + cb / 10)))
    $("#msgame-console").text("정확하시군요. " + cbm + " 점 드리겠습니다.");
    sc += cbm
    cb += 1
  } else {
    $("#msgame-console").text("안타깝습니다. 조금 더 노력해 보세요!");
    cb = 0
  }
  $("#msgame-score").text(sc);
  $("#msgame-combo").text(cb);
}
// 여기까지 코드 입력 //
 
  }
 
}
$( plugin_msgame );
/* msgame 끝 */
 
/** 플러그인 numbase***************************
* 숫자야구 remake
* 버전 => 1.41
* 작성자 : [[사용자:Riemann|Riemann]]
* JSON => numbase = {"name":"numbase","descript":"숫자야구 remake","version":"1.41","local":true,"creat":"Riemann","state":"사용자:Riemann/numbase","executable":true};  
*/
function plugin_numbase(){
  if($("[data-name='numbase']").length >= 1){
var title = mw.config.get('wgPageName');
if (title.slice( -1 ) == "4") {
    var no = 4
    }
else {
    var no = 3
}
 
var trial = 0;
var d = new Date();
$("#sBtn").click(function(){
    $("#description").css("display", "none");
    $("#sBtn").css("display", "none");
    $("#res").css("display", "table");
    cpuNum = initNumbase();
    document.getElementById('count').innerHTML = "시도 횟수: " + trial;
    var bDate = d.getTime();
    numGuess(bDate);
});
 
function initNumbase() {
var choice = "";
var initArray = [0,1,2,3,4,5,6,7,8,9];
var i, j;
for (i = 0; i < no; i++) {
    j = Math.floor(Math.random() * initArray.length);
    choice += initArray[j];
    initArray.splice(j,1);
}
return choice;
}
 
function numGuess(bDate) {
document.getElementById('disp').style.display = 'table';
document.getElementById('numList').style.display = 'block';
var numb = document.getElementById('numList');
var numBlocks = "";
var disp = "";
document.getElementById('disp').innerHTML = disp;
for (i = 0; i < 10; i++) {
    numBlocks += "" + i + "";
}
numBlocks += "C";
numBlocks += "입력";
numb.innerHTML = numBlocks;
 
function restrictLen(l,n) {
  if (l.length < no) {
        l += n;
  } else {
        alert(no + " 자리로 입력하세요.");
  }
  return l;
}
 
$("#numBlock0").click(function(){
    disp = restrictLen(disp,0);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock0").css("display", "none");
});
$("#numBlock1").click(function(){
    disp = restrictLen(disp,1);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock1").css("display", "none");
});
$("#numBlock2").click(function(){
    disp = restrictLen(disp,2);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock2").css("display", "none");
});
$("#numBlock3").click(function(){
    disp = restrictLen(disp,3);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock3").css("display", "none");
});
$("#numBlock4").click(function(){
    disp = restrictLen(disp,4);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock4").css("display", "none");
});
$("#numBlock5").click(function(){
    disp = restrictLen(disp,5);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock5").css("display", "none");
});
$("#numBlock6").click(function(){
    disp = restrictLen(disp,6);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock6").css("display", "none");
});
$("#numBlock7").click(function(){
    disp = restrictLen(disp,7);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock7").css("display", "none");
});
$("#numBlock8").click(function(){
    disp = restrictLen(disp,8);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock8").css("display", "none");
});
$("#numBlock9").click(function(){
    disp = restrictLen(disp,9);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock9").css("display", "none");
});
$("#numBlockC").click(function(){
    disp = "";
    document.getElementById('disp').innerHTML = disp;
    $(".numBlock").css("display", "inline-flex");
});
$("#numBlockX").click(function(){
    if (disp.length < no) {
        alert(no + " 자리로 입력하세요.")
    } else {
        trial += 1
        document.getElementById('count').innerHTML = "시도 횟수: " + trial;
        v = valid(disp,cpuNum);
        $("#res").append("" + trial + "" + disp + "" + v + "");
        disp = "";
        document.getElementById('disp').innerHTML = disp;
        $(".numBlock").css("display", "inline-flex");
        if ((v == "0B 3S" && no == 3) || (v == "0B 4S" && no == 4)) {
            var dd = new Date();
            var duration = Math.floor((dd.getTime() - bDate) / 1000);
            document.getElementById('end').innerHTML = "축하합니다. 정수를 맞히셨습니다. " + trial + "회, " + duration + "초가 소비되었습니다. 이용해주셔서 감사합니다.";
            $("#disp").css("display", "none");
            $("#numList").css("display", "none");
            $("#end").css("display", "inline");
            return 0;
        }
    }
});
}
 
function valid(u,c) {
    var b = 0;
    var s = 0;
    var bs;
    for (i = 0; i < no; i++) {
        for (j = 0; j < no; j++) {
            if (u[i] == c[j]) {
                if (i == j) {
                    s += 1;
                 }
                 }
            });
                 else {
        } else {
                     b += 1;
            action = {
                 removeItem: function removeItem(key) {
                    if(key) return saveOption("userjs-" + key, null).then(action.refresh);
                    else throw new TypeError("Failed to execute 'removeItem' on 'Storage': 1 argument required, but only 0 present.");
                },
                setItem: function setItem(key, value) {
                     if(key) return saveOption("userjs-" + key, value).then(action.refresh);
                    else throw new TypeError("Failed to execute 'removeItem' on 'Storage': 1 argument required, but only 0 present.");
                },
                refresh: (function() {
                    var deferred = new $.Deferred();
                    var timeout = null;
                   
                    return function refresh() {
                        if(timeout) clearTimeout(timeout);
                        timeout = setTimeout(function() {
                            setTimeout(function() {
                                deferred.resolve(api.get({
                                    action: 'query',
                                    meta: 'userinfo',
                                    uiprop: 'options'
                                }, {
                                    cache: false
                                }).then(function(response) {
                                    mw.user.options.values = response.query.userinfo.options;
                                    return storage;
                                }));
                               
                                timeout = null;
                                deferred = new $.Deferred();
                            }, 300);
                        }, 100);
                        return deferred.promise();
                    };
                })()
            };
            storage = new Proxy(mw.user.options, {
                get: function(target, prop, receiver) {
                    function keys() {
                        return Object.keys(target.values).filter(function(key) {
                            return key.startsWith('userjs-');
                        });
                    }
                   
                    return Reflect.get({
                        length: prop === 'length' && keys().length,
                        getItem: function getItem(key) {
                            if(key) return target.get("userjs-" + key);
                            else throw new TypeError("Failed to execute 'getItem' on 'Storage': 1 argument required, but only 0 present.");
                        },
                        key: function key(index) {
                            return keys()[index].slice(7);
                        },
                        removeItem: function removeItem(key) {
                            key = key;
                            Reflect.deleteProperty(target.values, key);
                            return action.removeItem(key);
                        },
                        setItem: function setItem(key, value) {
                            key = key;
                            target.set(key, value);
                            return action.setItem(key, value);
                        },
                        refresh: action.refresh,
                        needRefresh: true
                    }, prop, receiver) || Reflect.get(target.values, "userjs-" + prop, receiver);
                },
                set: function(target, prop, value, receiver) {
                    prop = prop;
                    Reflect.set(target.values, prop, value, receiver);
                    return action.setItem(prop, value);
                },
                deleteProperty: function(target, prop) {
                    Reflect.deleteProperty(target.values, prop);
                    return action.removeItem(prop);
                },
                has: function(target, prop) {
                    return Reflect.has(target.values, "userjs-" + prop);
                },
                ownKeys: function(target) {
                    return Reflect.ownKeys(target.values).filter(function(key) {
                        return key.startsWith("userjs-");
                    }).map(function(key) {
                        return key.slice(7);
                    });
                 }
                 }
             });
             }
         }
         }
        return storage;
    }
    })();
    bs = "" + b + "B " + s + "S"
    // local + global 슈퍼셋 (hybridStorage[gamedb-*])
    return bs;
    var rootGameDB = setStoragePrefix(hybridStorage, 'gamedb-', {
}
         refresh: function() {
 
             return hybridStorage.refresh().then(function() {
                return rootGameDB;
  }
             });
 
}
$( plugin_numbase );
/* numbase 끝 */
 
/** 플러그인 uncyslide***************************
* 백괴슬라이드 실행
* 버전 => 1.1.02
* 작성자 : [[사용자:BANIP|BANIP]]
* JSON => uncyslide = {"name":"uncyslide","descript":"백괴슬라이드 실행","version":"1.1.02","local":true,"creat":"BANIP","state":"백괴슬라이드/플러그인","executable":true};
*/
function plugin_uncyslide(){
  if($("[data-name='uncyslide']").length >= 1){
// 이부부분에 코드 입력 //
var slideable = plugin_Slideable();
var create = slideable.create;
var execute = slideable.execute;
var dispose = slideable.dispose;
 
var rankingSystem = plugin_RankingSystem()("백괴슬라이드/랭킹", function(prev,next){ return Number(prev.time) - Number(next.time)});
var outputKeys = {time:"소요시간"};
var startMap = localStorage.getItem("uncySlide/startmap") || 0;
var game = {
    0: {
        center: "아래로 밀어주세요.",
        bottom: 1
    },
    1: {
        center: "오른쪽으로 밀어보세요.",
        right: 2
    },
    2: {
        center: "어디로 밀어보실래요?",
        top: 3,
        bottom: 3,
    },
    3: {
        center: "반갑습니다. 백괴슬라이드입니다.",
        bottom: 4,
    },
    4: {
        center: "어디로 당기고 미느냐에 따라, 게임의 결과가 달라집니다.",
        bottom: 5,
    },
    5: {
        center: "는 개뿔 이겜 시스템만든다고 그런 장황한거 만들 정신머리는 없었습니다",
        bottom: 5.1,
    },
    5.1: {
        center: "진심 힘들었습니다.",
        bottom: 5.2,
    },
    5.2: {
        center: "잘했죠?",
        bottom: 5.3,
    },
    5.3: {
        center: "위로 밀어서 칭찬하거나 아래로 밀어서 욕해주세요.",
        top: 5.4,
        bottom: 5.5,
    },
    5.4: {
        center: "감사합니다. 헤헤",
        bottom: 6,
    },
    5.5: {
        center: "흑흑.. 힘들었는데..",
        bottom: 6,
    },
    6: {
         center: "그래도 미디어위키의 틀에서 벗어난 겜인만큼 최대한 나은 경험을 선사하고자 노력했습니다. 잘부탁드립니다.",
        bottom: function(){
             localStorage.setItem("uncySlide/startmap","main");
             execute("main");
         },
         },
         needRefresh: hybridStorage.needRefresh
    },
     }, true);
    main: {
     // 게임별로 할당되는 영역 (rootGameDB[{게임}/*])
         center: "아래: 게임시작토론: 위설명: 오른쪽",
     window.localGameDB = setStoragePrefix(rootGameDB, mw.config.get('wgPageName').split('/')[0] + '/', {
        bottom: function(){ execute("start",{count:100,time:Date.now()}) },
         refresh: function() {
        top: "debate",
             return rootGameDB.refresh().then(function() {
        right: "i0",
                 return localGameDB;
     },
             });
     i0: {
         },
        center:"가장자리에 화살표 보이죠?",
         needRefresh: rootGameDB.needRefresh
        bottom:"i1"
    });
    },
    // 모든 게임이 공유하는 영역 (rootGameDB[#*])
    i1: {
    window.globalGameDB = setStoragePrefix(rootGameDB, '#', {
        center:"화면을 넘겨서 드래그해서 진행하는 게임이에요.",
        refresh: function() {
        bottom:"i2"
            return rootGameDB.refresh().then(function() {
    },
                return globalGameDB;
     i2: {
             });
        center:"원래라면 좀 큰 스케일의 게임으로 만들고 싶었는데..",
         },
        bottom:"i3"
         needRefresh: rootGameDB.needRefresh
    },
    });
    i3: {
        center:"제 역량이 겜 크기에서 다 드러나네요...",
        bottom:"i4"
    },
    i4: {
        center:"아무쪼록 힘들게 만들었으니 재밌게 즐겨주세요.",
        right:"main"
    },
    debate: function(){
        location.href = "https://libertyga.me/wiki/%ED%86%A0%EB%A1%A0:%EB%B0%B1%EA%B4%B4%EC%8A%AC%EB%9D%BC%EC%9D%B4%EB%93%9C";
    },
    start: function(arg){
         function getRandomDirection(){
             switch( Math.ceil(Math.random() * 4) ){
                 case 1: return "top"; break;
                case 2: return "bottom"; break;
                case 3: return "left"; break;
                case 4: return "right"; break;
             }
        }
        function getColorCode(count,maxcount){
            var code = "hsl(" + count / maxcount * 360 +",100%,70%)";
            return code
         }
          
        var count = arg.count;
        var maxcount = arg.maxcount || count;
        var time = arg.time;
        var $this = $(this);
        var timerInterval;
        var slideableItem = {
            center: function(){
                var $this = $(this);
                $this.css({
                    "background": getColorCode(count,maxcount)
                });
               
                timerInterval = setInterval(function(){
                    var overtime = (Date.now() - time) * 0.001;
                    var printableTime = overtime.toFixed(2);
                    $this.find(".counter").html(printableTime + "초");
                },5)
               
                return "" + count + "";
            }
        };
 
        slideableItem[getRandomDirection()] = function(){
            clearInterval(timerInterval);
            if(count === 1) return execute("result",{count:count - 1,time:time,maxcount:maxcount});
             execute("start",{count:count - 1,time:time,maxcount:maxcount})  
        };
 
         create(slideableItem);
    },
    result: function(arg){
        var maxcount = arg.maxcount || count;
        var time = ( (Date.now() - arg.time) / 1000 ).toFixed(2);
         var updateParam = {
        time: time,
        name: mw.config.get("wgUserName")
        };
        rankingSystem.update(updateParam,function(rankingScore,thisScore){ return rankingScore.time > thisScore.time},outputKeys);


    function DataChange(href) {
        create({
        this.params = geturlSearch(new URL(href));
            center: "갯수: " + maxcount + " 시간: " + time + "왼쪽: 메인으로오른쪽: 토론으로",
        this.local = {};
            left:"main",
        this.global = {};
            right:"debate",
         this.root = {};
         });
        this.refresh = false;
     }
     }
    DataChange.prototype.control = function control(element) {
}
        var base, key, storage, params;
dispose(game, startMap, {});
        var data = element.dataset;
       
  }
        /* 저장할 키
 
            local: 키 지정
}
            global: 전역 키 지정
$( plugin_uncyslide );
            local global: 키 지정
/* uncyslide 끝 */
            (없음): 기본 키
 
        */
/** 플러그인 Slideable***************************
        if('local' in data) {
* 슬라이드 플러그인 라이브러리
            storage = localGameDB;
* 버전 => 1.0.21
            base = this.local;
* 작성자 : [[사용자:BANIP|BANIP]]
            key = data.local;
* JSON => Slideable = {"name":"Slideable","descript":"슬라이드 플러그인 라이브러리","version":"1.0.21","local":true,"creat":"BANIP","state":"사용자:BANIP/플러그인/슬라이드","executable":false};
         } else if('global' in data) {
*/  
             storage = globalGameDB;
function plugin_Slideable(){
            base = this.global;
  if($("[data-name='Slideable']").length >= 1){
            key = data.global;
// 이부부분에 코드 입력 //
        } else {
    //모든 키 순회
            storage = rootGameDB;
    function forEach(object, callback) {
            base = this.root;
         for (var key in object) {
             key = title;
             var variable = object[key];
             callback(variable, key);
         }
         }
       
    }
        switch(data.action) {
            // 호환
            case '저장':
            case 'save':
                /*
                    default: 새 키를 생성할 때만 저장
                    reset: 현재 사용하는 파라미터만 저장
                */
              if(!('default' in data && key in base) && location.search) base[key] = JSON.stringify('reset' in data? geturlSearch() : Object.assign(parseJSON(storage.getItem(key)) || {}, geturlSearch()));
            break;


            case '로드':
function create(directionData) {
            case 'load':
    function initClassName($target, data) {
                /*
        forEach(data, function(value, direction) {
                    reset: 파라미터 강제 교체
            $target.find("." + direction).addClass("on");
                */
        })
                if(!location.search || 'reset' in data) Object.assign(this.params, parseJSON(storage.getItem(key)));
    }
            break;


            // 기본
    function initDOM($target, data) {
            case '호출':
        $target[0].data = data;
            case 'get':
        $target.find(".center").html(data.center);
                this.params[data.arg] = storage.getItem(key);
        $target.find(".top.on").css("background","url('https://upload.wikimedia.org/wikipedia/commons/8/85/Arrow_top_svg.svg') no-repeat center");
            break;
        $target.find(".bottom.on").css("background","url('https://upload.wikimedia.org/wikipedia/commons/f/f2/Arrow_bottom_svg.svg') no-repeat center");
        $target.find(".left.on").css("background","url('https://upload.wikimedia.org/wikipedia/commons/4/40/Arrowleft_svg.svg') no-repeat center");
        $target.find(".right.on").css("background","url('https://upload.wikimedia.org/wikipedia/commons/e/ec/Arrow2right.svg') no-repeat center");
    }


            case '수정':
    var slideUtil = {
            case 'set':
        moveObject: function($this, axis) {
                /*
            var x = axis[0], y = axis[1];
                    default: 새 키를 생성할 때만 저장
                */
              if(!('default' in data && key in base)) base[key] = data.arg;
            break;


             case '삭제':
             var data = $this[0].data;
             case 'del':
            if (!data.right && x > 0) x = 0;
                delete base[key];
            if (!data.left && x < 0) x = 0;
             break;
            if (!data.top && y < 0) y = 0;
            if (!data.bottom && y > 0) y = 0;
            $this.css("transform", "translate(" + x + "px," + y + "px)");
        },
        isHideable: function($this, axis, limit) {
             var x = axis[0], y = axis[1];
            var data = $this[0].data;
            if (data.right && x > limit) return "right";
            if (data.left && x < limit * -1) return "left";
            if (data.bottom && y > limit) return "bottom";
             if (data.top && y < limit * -1) return "top";
        },
        hide: function(direction, $this) {
            function getCss(direction) {
                var css = {
                    opacity: 0.01
                };
                var interval = 50;
                switch (direction) {
                    case "left":
                        css.left = -1 * interval + "vw";
                        break;
                    case "right":
                        css.left = interval + "vw";
                        break;
                    case "bottom":
                        css.top = interval + "vh";
                        break;
                    case "top":
                        css.top = -1 * interval + "vh";
                        break;
                }


            // JSON
                 return css;
            case 'JSON':
            }
            case 'json':
                /*
                    reset: 파라미터 초기화
                    delete: 데이터 초기화
                */
                 if('reset' in data) this.params = {};
                if('delete' in data) base[key] = '';
                params = this.params;
                base[key] = JSON.stringify(new CGI2Parser({
                    get: function(args) {
                        if(typeof args === 'object') Object.pairs(args).forEach(function(pair) {
                            params[pair[0]] = this[pair[1]];
                        });
                        else Array.from(arguments).forEach(function(key) {
                            params[key] = this[key];
                        });
                    },
                    set: function(args) {
                        Object.pairs(args).forEach(function(pair) {
                            this[pair[0]] = pair[1];
                        });
                    },
                    del: function() {
                        Array.from(arguments).forEach(function(key) {
                            delete this[key];
                        });
                    },
                    def: function(args) {
                        Object.pairs(args).forEach(function(pair) {
                            if(!(pair[0] in params)) params[pair[0]] = this[pair[1]];
                        });
                    },
                    sav: function(args) {
                        if(typeof args === 'object') Object.pairs(args).forEach(function(pair) {
                            this[pair[0]] = params[pair[1]];
                        });
                        else Array.from(arguments).forEach(function(key) {
                            this[key] = params[key];
                        });
                    }
                }).parse(parseJSON(base.getItem(key)), data.arg));
                Object.assign(this.params, params);
            break;


             default:
             var self = $this[0];
                 $(element).addClass('error').text(data.action? "'" + data.action + "'은() 올바른 동작이 아닙니다" : '올바른 동작을 입력하지 않았습니다');
            var data = self.data;
            if (self.isHide === true) {
                 return;
            }
            self.isHide = true;
            $this.animate(getCss(direction), {
                duration: 300,
                easing: "swing",
                start: data[direction],
                complete: function() {
                    $this.remove();
                }
            });
         }
         }
     };
     }
 
    function setEvent($target, data) {
        var util = slideUtil;
        var moveLimit = 50;
 
        $(".slideable").mousedown(function(e) {
            this.isMouseDown = true;
            this.startAxis = [e.clientX, e.clientY];
        })
 
        $(".slideable").mousemove(function(e) {
            if (this.isMouseDown) {
                event.preventDefault()
                var axis = [e.clientX, e.clientY];
                var startAxis = this.startAxis;
                var moveInterval = [axis[0] - startAxis[0], axis[1] - startAxis[1]]
                util.moveObject($(this), moveInterval);
                var hideDirection = util.isHideable($(this), moveInterval, moveLimit);
                if (hideDirection) util.hide(hideDirection, $(this));
            }
        })


    // TODO: .gameDB-control, .gameDB-container, .gameDB-link click 이벤트 리스너 구현
        $(".slideable").mouseup(function(e) {
    /**
            this.isMouseDown = false;
    * DB 저장
         })
    * @function
    * @param {DataChange} change
    */
    function save(change) {
        var key;
         var promises = [];


         if(title in change.root) {
         function getTouchEvent(e) {
            promises.push(rootGameDB.setItem(title, change.root[title]));
             return e.originalEvent.touches[0]
        }
        for(key in change.local) {
            promises.push(localGameDB.setItem(key, change.local[key]));
        }
        for(key in change.global) {
             promises.push(globalGameDB.setItem(key, change.global[key]));
         }
         }


         if(promises.length && !mw.user.isAnon()) noti = mw.notification.notify('데이터를 저장하는 중입니다...', {
         $(".slideable").on("touchstart", function(e) {
             autoHide: false,
            var touch = getTouchEvent(e);
             tag: 'gameDB',
 
            type: 'pending'
            this.isMouseDown = true;
        });
            this.startAxis = [touch.clientX, touch.clientY];
        })
 
        $(".slideable").on("touchmove", function(e) {
            event.preventDefault()
            if (this.isMouseDown) {
                event.preventDefault()
                var touch = getTouchEvent(e);
                var axis = [touch.clientX, touch.clientY];
                var startAxis = this.startAxis;
                var moveInterval = [axis[0] - startAxis[0], axis[1] - startAxis[1]]
                util.moveObject($(this), moveInterval);
                var hideDirection = util.isHideable($(this), moveInterval, moveLimit);
                if (hideDirection) util.hide(hideDirection, $(this));
            }
        })
 
        $(".slideable").on("touchend", function(e) {
             this.isMouseDown = false;
        })
 
    }
 
    //슬라이드아이템의 방향키로 숫자 혹은 문자로 지정된 경우
    //함수로 변환
    function setExecutable(target, item){
        forEach(item,function(value,direction){
             new Promise(function(resolve, reject){
                if(direction === "center"){
                    switch( typeof value ){
                    case "function":
                        resolve( value.bind(target)() );
                    break;
                  }
              } else {
                switch( typeof value ){
                    case "string": case "number":
                        resolve(function(){ execute(value); }.bind(target));
                    break;
                }
              }
            }).then(function(result){
                item[direction] = result;
            })


         return Promise.all(promises);
         })
     }
     }
   
    var $target = $(".slideable.cloneable").clone().removeClass("cloneable");
    $("body").prepend($target);
    setExecutable($target[0], directionData);
    initClassName($target, directionData);
    initDOM($target, directionData);
    setEvent($target, directionData);
}
// create는 다른 함수들에 의존하지 않음 //
var game;
function execute(number, argument) {
    dispose(game, number, argument);
}


    function handleError(code, object) {
function dispose(slideableArray, start, argument) {
        mw.notification.notify(
    game = slideableArray;
            code === 'http'?
   
                $('<span />')
    var slideableItem = slideableArray[start];
                    .append($('<p />', {class: 'gameDB-noti-errmsg'}).text(object.xhr.responseText))
    switch (typeof slideableItem) {
                    .append($('<code />', {class: 'gameDB-noti-errcode'}).text('HTTP ' + object.xhr.status)) :
        case "function":
                $('<span />')
            slideableItem(argument);
                    .append($('<p />', {class: 'gameDB-noti-errmsg'}).text(object.error.info))
            break;
                    .append($('<code />', {class: 'gameDB-noti-errcode'}).text(code)),
        case "object":
            {
            create(slideableItem);
                title: '데이터 저장에 실패하였습니다.',
             break;
                type: 'error',
                tag: 'gameDB'
             }
        );
     }
     }
}


    // 즉시
//모바일 전체화면으로 수정
    (function() {
var setFullScreen = (function(){
        var instant = new DataChange(location.href);
    //window.scrollTo(0,1);
})();
 
return {
    create: create,
    execute: execute,
    dispose: dispose
}
  }
 
}
/* Slideable 끝 */


        $('.gameDB-control').each(function() {
            instant.control(this);
        });


        save(instant).then(function() {
            instant.params = searchParamToString(instant.params);


            if(currentSearch !== instant.params) location.search = instant.params;
/** 플러그인 RankingSystem***************************
            else if(noti) noti.close();
* 랭킹시스템 라이브러리
        }, handleError);
* 버전 => 1.1.0
    })();
* 작성자 : [[사용자:BANIP|BANIP]]
* JSON => RankingSystem = {"name":"RankingSystem","descript":"랭킹시스템 라이브러리","version":"1.1.0","local":true,"creat":"BANIP","state":"사용자:BANIP/플러그인/랭킹시스템","executable":false};  
*/
function plugin_RankingSystem(){
  if($("[data-name='RankingSystem']").length >= 1){
// 이부부분에 코드 입력 //


    // 링크
/**
    (function() {
  * @param
        function process(link, controllers, change) {
  {string} documentTitle 랭킹정보가 있는 문서의 제목.
            var href = new URL(link.href, location);
  {function} sortCallback 랭킹을 정렬할때 기준으로 사용하는 함수
            var search;
      {any} prev 랭킹 정렬 기준으로 사용할 왼쪽의 값
    {any} next 랭킹 정렬 기준으로 사용할 오른쪽의 값
  {object} api MediaWikiapi의 인스턴스, 없어도 됨.


            controllers.each(function() {
  @return {Object}
                change.control(this);
  {function} get 랭킹정보를 object형태로 획득
            });
  {function} update 랭킹정보 업데이트
  {object} updateInfo 업데이트할 사용자 정보
  {function} updateCriteria 사용자정보의 업데이트 기준
  @param {any} rankingScore 랭킹에서 사용중인 스코어
    {any} thisScore 사용자 스코어
  @return{bool} true가 반환되면 업데이트
  {object} alternateKeys 랭킹에서 보여지는 대체 키
*/


            search = searchParamToString(change.params);
return function(documentTitle, sortCallback, api) {
             href.search = currentSearch === search? location.search : search;
    function forEach(object, callback) {
             link.href = href.href;
        for (var key in object) {
             var variable = object[key];
             callback(variable, key);
         }
         }
    }


         $('.gameDB-container').not(':has(a, .gameDB-container)').each(function() {
    function getRankingJSON(rankingDoc) {
            var href;
         if (!rankingDoc) return {};
        var includeOnlyString = "includeonly"
        var regexp = new RegExp("\<" + includeOnlyString + "\>(.*)\<\/" + includeOnlyString + "\>");
        var stringRanking = regexp.exec(rankingDoc)[1];
        return JSON.parse(stringRanking);
    }


            /*
    function updateDoc(rankingJSON, api, alternateKeys) {
                clear: 기존 파라미터 넘겨주지 않음
        //alternateKeys가 반영된 개개인의 랭킹정보 획득
            */
        function getOutputJSON(json) {
            if('clear' in this.dataset) {
            var result = {};
                href = new URL(location.href);
            forEach(json, function(value, key) {
                 href.search = '';
                 key = alternateKeys[key] || key;
                 href = href.href;
                 result[key] = value;
             } else href = location.href;
             })
            return result;
        }


            $(this).html($('<a />', {
        //보여지는 형태의 랭킹정보 획득
                href: href
         function getOutputString(json) {
            }).text(this.innerText));
             var name = json.name;
        });
             var result = "* '''" + name + "''' : ";
       
            forEach(json, function(value, key) {
         $('.gameDB-container a').each(function() {
                if (key === "name") return;
             var change = new DataChange(this.href);
                key = alternateKeys[key] || key;
             var controllers = $($(this).parents('.gameDB-container').get().reverse());
                result += key + ": " + value + ", ";
            })
            result += "\n"
            return result
        }


            process(this, controllers, change);
        var stringRanking = JSON.stringify(rankingJSON);
        var result = "<includ" + "eonly>" + stringRanking + "</inclu" + "deonly>\n";
        result += "<onlyin" + "clude>\n";


            $(this).data('change', change);
        var rankingList = Object.entries(rankingJSON).sort(function(prev,next){
            $(this).addClass('gameDB-link');
          return sortCallback(prev[1],next[1])
        }).map(function(value){
          return value[0]
         });
         });


         $('.gameDB-link').on('click', function handler(event) {
         rankingList.forEach(function(key) {
             var link = this;
             var json = rankingJSON[key];
            var outputJSON = getOutputJSON(json);
            result += getOutputString(outputJSON)
        });


            if(!('done' in this.dataset)) event.preventDefault();
        result += "</only" + "include>";
        var reply = documentTitle.replace(new RegExp("\/.*"),"") + " 점수 갱신";
        api.changeDocument(documentTitle, reply, result, true);
        return result;
    }


            save($(this).data('change')).then(function() {
    function updateUserScore(rankingJSON, thisScore, updateCriteria) {
                if(link.href !== location.href) {
        updateCriteria = updateCriteria || function(rankingScore, thisScore) {
                    link.dataset.done = '';
            return rankingScore.score < thisScore.score;
                    $(link).off('click', handler).click();
         }
                } else mw.notification.notify('데이터가 저장되었습니다.', {
                    tag: 'gameDB'
                });
            }, handleError);
         });
    })();
})['catch'](console.error);


        var userName = thisScore.name;
        var rankingScore = rankingJSON[userName];


/** 플러그인 test***************************
        if (!rankingScore || updateCriteria(rankingScore, thisScore)) {
* 테스트용 플러그인 입니다.
            rankingJSON[userName] = thisScore;
* 버전 => 0.1
        }
* 작성자 : [[사용자:Gustmd7410|Gustmd7410]]
    }
* JSON => test = {"name":"test","descript":"테스트용 플러그인 입니다.","version":"0.1","local":true,"creat":"Gustmd7410","state":"사용자:Gustmd7410/연구소/틀/플러그인","executable":true};
*/
function plugin_test(){
  if($("[data-name='test']").length >= 1){
function unSave() {
$.get({
url: '/w/index.php',
data: {
title: mw.config.values.wgPageName.split('/')[0] + '/' + unSave.config.gameConfig.path,
action: 'raw',
ctype: 'application/json'
}
}).then(function(config) {
return {
global: unSave.config,
local: config.gameData || unSave.config.gameConfig.default
};
}).then(function(config) {
// 사용자 문서 허용여부 확인후 비허용시 자동으로 변경
if(!config.global.enableUserBase) config.local.base = 'game';
// 경로 블랙리스트 / 화이트리스트 확인
(function(path) {
var list = this.global.pathList;
if(list) {
if(list.enable && !list.enable.has(path)) throw new Error(path + '은(는) 유효하지 않는 경로입니다');
if(list.block && list.block.has(path)) throw new Error(path + '은(는) 유효하지 않는 경로입니다');
}
})(config.local.path);
// IP 유저 사용가능 여부 확인
if(!mw.config.values.wgUserName && (!config.global.enableIP || !config.local.ipuser)) throw new Error('IP 사용자는 저장할 수 없습니다');
}).then(function(config) {
var api = new mw.Api({
parameters: {
formatversion: 2
}
});
var GameData = (function() {
var SaveWindow = (function() {
function SaveWindow() {
SaveWindow.super.call(this, config);
}
OO.inheritClass(SaveWindow, OO.ui.ProcessDialog);
SaveWindow.static.name = 'unSave';
SaveWindow.static.title = '데이터 저장';
SaveWindow.static.actions = [
{label: '저장', action: 'save', flags: ['primary', 'constructive']},
{label: '취소', action: 'cancel', flags: 'safe'},
{label: '기본 편집기 사용', action: 'open'}
];
return SaveWindow;
})();
function GameData(target, value) {
if(!(this instanceof GameData)) {
console.warn('GameData 생성자를 new 키워드 없이 실행했습니다');
return new GameData(title, value, model, schema);
}
if(typeof target !== 'string') throw new TypeError('target 파라미터가 문자열이 아닙니다');
if(typeof value !== 'string') throw new TypeError('value 파라미터가 문자열이 아닙니다');
if(!config.getTargetConfig(target)) throw new ReferenceError('올바르지 않은 target입니다.');
var targetConfig = config.local.getTargetConfig(target);
this.target = config.local.target + target;
this.value = value;
this.model = targetConfig.model || 'wikitext';
this.schema = targetConfig.schema || null;
this.exists = null;
this.validated = null;
this.diff = null;
this.syntax = null;
this.popup = null;
this.window = null;
}
GameData.prototype.prepare = function() {
var data = this;
return api.get({
action: 'query',
titles: this.title,
}).then(function(response) {
if(response.query.pages[0].invalid) throw new Error('잘못된 문서 제목입니다');
data.exists = !response.query.pages[0].missing;
return data;
});
};
GameData.prototype.validate = function() {
if(this.model !== 'json') throw new TypeError(this.model + '컨텐츠 모델은 스키마를 사용할 수 없습니다');
if(typeof this.schema !== 'string') throw new TypeError('검증할 스키마가 없습니다');
var data = this;
return Promise.resolve(Ajv || $.getScript('https://cdnjs.cloudflare.com/ajax/libs/ajv/6.5.5/ajv.min.js').promise())
.then(function() {
return $.get({
url: '/w/index.php',
data: {
title: data.schema,
action: 'raw',
ctype: 'application/json'
}
}).promise();
}).then(function(schema) {
var ajv = new Ajv();
if(ajv.validateSchema(schema)) {
data.validated = ajv.validate(JSON.parse(data.value), schema);
return data.validated;
} else throw new TypeError('스키마가 올바르지 않습니다');
});
};
GameData.prototype.highlight = function() {
var data = this;
if(this.syntax) return Promise.resolve(this.syntax);
switch(this.type) {
case 'wikitext':
this.syntax = $('<pre />').text(this.value)[0];
return Promise.resolve(this.syntax);
default: return api.get({
action: 'parse',
title: this.title,
text: $(new DOMParser().parseFromString('<source />', 'text/xml'))
.find('source')
.attr('id', 'highlight')
.attr('lang', this.type)
.text(this.value)[0]
.outerHTML,
disablelimitreport: true,
prop: 'text',
}).then(function(response) {
data.syntax = $(response.parse.text).find('#highlight')[0];
return data.syntax;
});
}
};
GameData.prototype.compare = function() {
var data = this;
return api.get({
action: 'compare',
fromtitle: this.title,
totext: this.value,
prop: 'diff',
}).then(function(response) {
data.diff = $(response.compare.body)[0];
return data.diff;
});
};
GameData.prototype.open = function() {};
GameData.prototype.save = function() {
var data = this;
return api.getToken('csrf').then(function(token) {
return api.post({
action: 'edit',
title: data.title,
text: data.value,
summary: '(unSave 0.0.1)',
/* tags: 'autosave', */
/* minor: ,*/
/* createonly: , */
/* nocreate: , */
contentmodel: data.model,
token: token
});
});
};
GameData.prototype.toString = function() {
return this.value.toString();
};
return GameData;
})();
var dataRegistry = new WeakMap();
});
}


unSave.config = {
    api = api || MediaWikiAPI();
    var userName = mw.config.get("wgUserName");
};
    var rankingDoc = api.getDocument(documentTitle);
    var rankingJSON = getRankingJSON(rankingDoc);


$(unSave);
    var actions = {
        get: function() {
            return rankingJSON;
        },
        update: function(updateInfo, updateCriteria, alternateKeys) {
            rankingJSON = actions.get();
            updateUserScore(rankingJSON, updateInfo, updateCriteria);
            updateDoc(rankingJSON, api, alternateKeys);
        }
    }
    return actions;
}


733번째 줄: 1,408번째 줄:


}
}
$( plugin_test );
/* RankingSystem 끝 */
/* test 끝 */

2024년 11월 15일 (금) 15:36 기준 최신판

/* [[틀:JSON수정]] 차단 시작 */
function kill_uncy_jsonEdit() {
	$('.uncy-jsonedit').remove();
}
kill_uncy_jsonEdit();
/* [[틀:JSON수정]] 차단 끝 */

/* 모바일용 개발자 도구 실행 버튼 만들기 */
// function startFirebug() {
// 	mw.loader.load('/index.php?title=사용자:hsl0/firebug.js&action=raw&ctype=text/javascript');
// }
// function startEruda() {
// 	mw.loader.load('/index.php?title=사용자:hsl0/eruda.js&action=raw&ctype=text/javascript');
// }
// function createDevToolsButton() {
// 	$('#footer-places')
// 		//.append($('<li id="footer-places-devtools-firebug" />').append($('<a>개발자 도구(Firebug)</a>').click(startFirebug)))
// 		.append($('<li id="footer-places-devtools-eruda" />').append($('<a>개발자 도구</a>').click(startEruda)));
// }
// $(createDevToolsButton);

function testHook(name) {
	mw.hook(name).add(function() {
		logStack.push([name].concat(arguments));
		console.log.apply(null, [name].concat(arguments));
	});
}

var logStack = [];

testHook('postEdit');
testHook('postEdit.afterRemoval');
testHook('structuredChangeFilters.ui.initialized');
testHook('wikipage.categories');
testHook('wikipage.collapsibleContent');
testHook('wikipage.content');
testHook('wikipage.diff');
testHook('wikipage.editform');
testHook('wikipage.indicators');



/** 플러그인 p21***************************
* 블랙잭
* 버전 => 0.840a4
* 작성자 : [[사용자:Riemann|Riemann]] 
* JSON => p21 = {"name":"p21","descript":"블랙잭","version":"0.840a4","local":true,"creat":"Riemann","state":"사용자:Riemann/p21","executable":true}; 
*/ 
function plugin_p21(){
  if($("[data-name='p21']").length >= 1){
		 var title = mw.config.get('wgPageName');
if (title.slice( 1, 2 ) == "라") {
    var blind = true;
    var defa = 20;
} else {
    var blind = false;
    var defa = 10;
}
var mult = defa;
$("#multiplier").text(mult);

var coins = 100;
var wincount = 0;
var losecount = 0;
//$("#console").text("스코어: " + coins + "점");
$("#console").text("스코어: " + wincount + "승 " + losecount + "패");
$("#console").append("\n블랙잭에 오신 것을 환영합니다.");

const pcLst = [
0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAD,0xAE,
0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBD,0xBE,
0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCD,0xCE,
0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDD,0xDE];
const pointData = {a1:1,a2:2,a3:3,a4:4,a5:5,a6:6,a7:7,a8:8,a9:9,aa:10,ab:10,ad:10,ae:10,b1:1,b2:2,b3:3,b4:4,b5:5,b6:6,b7:7,b8:8,b9:9,ba:10,bb:10,bd:10,be:10,c1:1,c2:2,c3:3,c4:4,c5:5,c6:6,c7:7,c8:8,c9:9,ca:10,cb:10,cd:10,ce:10,d1:1,d2:2,d3:3,d4:4,d5:5,d6:6,d7:7,d8:8,d9:9,da:10,db:10,dd:10,de:10};
var pcSet = [];
function hexToChar(x) {
    return String.fromCharCode(0xD83C) +String.fromCharCode(x + 0xDC00);
}
function hexToStr(x) {
    return x.toString(16);
}
var dealerD, guestD;
$("#deal").click(function(){
    //$("#console").text("스코어: " + coins + "점");
    $("#console").text("스코어: " + wincount + "승 " + losecount + "패");
    $("#console").append("\n새 판을 엽니다.");
    $("#deal").css("display", "none");
    $("#dealerDeck").text("");
    $("#guestDeck").text("");
    pcSet = Object.create(pcLst);
    deal();
    return 0;
});
$("#hit").click(function(){
    hit();
    return 0;
});
$("#stand").click(function(){
    stand();
    return 0;
});
$("#surrender").click(function(){
    surrender();
    return 0;
});
$("#plus").click(function(){
    inc();
    return 0;
});
$("#minus").click(function(){
    dec();
    return 0;
});
$("#reset").click(function(){
    reset();
    return 0;
});
function reset() {
    mult = defa;
    $("#multiplier").text(mult);
}

/*
function inc() {
    if (mult < 100) {
        mult += 2;
    } else {
        alert("최대 100 코인까지만 걸 수 있습니다.");
    }
    $("#multiplier").text(mult);
}

function dec() {
    if (mult > 2) {
        mult -= 2;
    } else {
        alert("설마 빚을 판돈으로 거시려고요?");
    }
    $("#multiplier").text(mult);
}
*/

function deal() {
    dealerD = [];
    guestD = [];
    dealerD.push(cardPop());
    guestD.push(cardPop());
    dealerD.push(cardPop());
    guestD.push(cardPop());
    if (blind == true) {
        $("#dealerDeck").text("\u{1F0A0}\u{1F0A0}");
    } else {
        $("#dealerDeck").text(hexToChar(dealerD[0]) + "\u{1F0A0}");
    }
    $("#dealerS").text("?");
    if (blind == true) {
        $("#guestDeck").text("\u{1F0A0}\u{1F0A0}");
    } else {
        $("#guestDeck").text(hexToChar(guestD[0]) + hexToChar(guestD[1]));
    }
    var guestScore = [];
    var score = pointData[hexToStr(guestD[0])] + pointData[hexToStr(guestD[1])];
    $("#guestS").text(score);
    if ((pointData[hexToStr(guestD[0])] == 1 && pointData[hexToStr(guestD[1])] == 10) || (pointData[hexToStr(guestD[0])] == 10 && pointData[hexToStr(guestD[1])] == 1)) {
        $("#guestS").text(21);
        jack();
    } else {
        $("#hit").css("display", "inline-flex");
        $("#stand").css("display", "inline-flex");
        $("#surrender").css("display", "inline-flex");
    }
};
function hit() {
    $("#hit").css("display", "none");
    $("#stand").css("display", "none");
    $("#surrender").css("display", "none");
    guestD.push(cardPop());
    var guestDeq = "";
    for (i = 0; i < guestD.length; i++) {
        guestDeq += hexToChar(guestD[i]);
    }
    if (blind == true) {
        $("#guestDeck").text("\u{1F0A0}".repeat(guestDeq.length / 2));
    } else {
        $("#guestDeck").text(guestDeq);
    }
    var guestScore = [];
    var score = 0;
    for (i = 0; i < guestD.length; i++) {
        guestScore.push(pointData[hexToStr(guestD[i])]);
        score += guestScore[i];
    }
    $("#guestS").text(score);
    if (score == 21 || (score == 11 && guestScore.includes(1))) {
        $("#console").append("\n21점이므로 자동으로 스탠드를 외쳤습니다.")
        stand(dealerD,guestD);
    } else if (score > 21) {
        bust();
    } else  {
        $("#hit").css("display", "inline-flex");
        $("#stand").css("display", "inline-flex");
    }
    return 0;
}
function stand() {
    $("#hit").css("display", "none");
    $("#stand").css("display", "none");
    $("#surrender").css("display", "none");
    var dScore = 0;
    var dealerScore = []
    for (i = 0; i < dealerD.length; i++) {
        dealerScore.push(pointData[hexToStr(dealerD[i])]);
        dScore += dealerScore[i];
    }
    while (dScore < 17) {
        dealerD.push(cardPop());
        $("#console").append("\n딜러가 카드를 뽑았습니다.")
        dealerScore = [];
        dScore = 0;
        for (i = 0; i < dealerD.length; i++) {
            dealerScore.push(pointData[hexToStr(dealerD[i])]);
            dScore += dealerScore[i];
            dealerDeq += hexToChar(dealerD[i]);
        }
    }
    var dealerDeq = "";
    for (i = 0; i < dealerD.length; i++) {
            dealerDeq += hexToChar(dealerD[i]);
        }
    $("#dealerS").text(dScore);
    $("#dealerDeck").text(dealerDeq);
    guestScore = [];
    score = 0;
    for (i = 0; i < guestD.length; i++) {
        guestScore.push(pointData[hexToStr(guestD[i])]);
        score += guestScore[i];
    }
    $("#guestS").text(score);
    if (score > 21) {
        bust()
    } else if (dScore > 21) {
        $("#console").append("\n딜러의 버스트.")
        win()
    } else {
        $("#console").append("\n딜러의 스탠드.")
        compare(dealerD,guestD);
    }
    return 0;
}
function compare() {
    var dealerScore = [];
    var dScore = 0;
    for (i = 0; i < dealerD.length; i++) {
        dealerScore.push(pointData[hexToStr(dealerD[i])]);
        dScore += dealerScore[i];
    }
    var guestScore = [];
    var score = 0;
    for (i = 0; i < guestD.length; i++) {
        guestScore.push(pointData[hexToStr(guestD[i])]);
        score += guestScore[i];
    }
    if (dScore < 12 && dealerScore.includes(1)) {
        dScore += 10
    }
    if (score < 12 && guestScore.includes(1)) {
        score += 10
    }
    $("#dealerS").text(dScore);
    $("#guestS").text(score);
    if (dScore > score) {
        lose()
    } else if (dScore == score) {
        push()
    } else {
        win()
    }
    return 0;
}
function win() {
    $("#console").append("\n축하합니다! 이겼습니다.")
    //$("#console").append("\n" + mult + "점을 얻었습니다.")
    //coins += mult;
    wincount += 1;
    $("#deal").css("display", "inline-flex");
    return 0;
}
function lose() {
    $("#console").append("\n졌습니다...")
    //$("#console").append("\n" + mult + "점을 잃었습니다.")
    //coins -= mult;
    losecount += 1;
    $("#deal").css("display", "inline-flex");
    publicAd();
    return 0;
}
function push() {
    $("#console").append("\n비겼습니다.")
    $("#deal").css("display", "inline-flex");
    return 0;
}
function surrender() {
    $("#hit").css("display", "none");
    $("#stand").css("display", "none");
    $("#surrender").css("display", "none");
    $("#console").append("\n이번 판을 포기하셨습니다 (패배로 처리됩니다).")
    //$("#console").append("\n" + (0.5 * mult) + "점을 잃었습니다.")
    //coins -= 0.5 * mult;
    losecount += 1;
    $("#deal").css("display", "inline-flex");
    publicAd();
    return 0;
}
function bust() {
    $("#console").append("\n버스트! 유감입니다. 졌습니다...")
    //$("#console").append("\n" + mult + "점을 잃었습니다.")
    //coins -= mult;
    losecount += 1;
    $("#hit").css("display", "none");
    $("#stand").css("display", "none");
    $("#deal").css("display", "inline-flex");
    publicAd();
    return 0;
}
function jack() {
    $("#console").append("\n블랙잭 달성! 축하합니다. 이겼습니다!")
    //$("#console").append("\n" + (1.5 * mult) + "점을 획득했습니다.")
    //coins += 1.5 * mult;
    wincount += 1;
    $("#deal").css("display", "inline-flex");
    return 0;
}
function publicAd() {
    if (coins < 0) {
        $("#notice").text("땀 흘려 번 돈이 아름답습니다.");
    }
    return 0;
}
function cardPop() {
    var j, ret;
    j = Math.floor(Math.random() * pcSet.length);
    ret = pcSet[j];
    pcSet.splice(j,1);
    return ret;
}

		
  }

}
$( plugin_p21 );
/* p21 끝 */

/** 플러그인 real369***************************
* real369 플레이
* 버전 => 1.1.7
* 작성자 : [[사용자:BANIP|BANIP]] 
* JSON => real369 = {"name":"real369","descript":"real369 플레이","version":"1.1.7","local":true,"creat":"BANIP","state":"Real 369/플러그인","executable":true}; 
*/ 
function plugin_real369(){
  if($("[data-name='real369']").length >= 1){
		 /**
 * 지금 박수를 쳐야되는지 숫자를 외쳐야 하는지 알아 냅니다
 * @param {number} number 지금 순서가 몇번째인지 넣는 칸.
 * @return {number|Array[number]} 박수를 쳐야되는 상황이면 배열 안에 숫자를 담아 반환하고 아니면 파라미터를 반환.
 */
function getAnswer(number) {
    var rawNumber = number + "";
    var targetNumber = rawNumber.replace(/3|6|9/g, "");
    var diff = rawNumber.length - targetNumber.length;
    if (diff === 0)
        return number + "";
    else
        return "짝!".repeat(diff);
}
function isMobile() {
    return !(navigator.userAgent.match(/Android|iPhone|iPad|iPod/i) === null);
}
var GUI = /** @class */ (function () {
    function GUI() {
        this.domList = {
            retry: document.querySelector("#gamewrap .gamelink .retry"),
            answer: document.querySelector("#gamewrap .answer"),
            dialog: document.querySelector("#gamewrap .dialog"),
            progress: document.querySelector("#gamewrap .progress"),
            gamelink: document.querySelector("#gamewrap .gamelink")
        };
        this.bindOtherEvent();
        //this.start();
    }
    GUI.prototype.start = function () {
        this.domList.answer.innerHTML = "시작!";
        this.domList.dialog.innerHTML = "";
        this.domList.gamelink.style.display = "none";
        createGame(gui);
        input.setGame(game);
    };
    GUI.prototype.bindOtherEvent = function () {
        var _this = this;
        this.domList.retry.addEventListener("click", function () {
            if (game !== null)
                game.gameOver();
            _this.start();
        });
    };
    GUI.prototype.message = function (message) {
        var dialogNode = this.domList.dialog;
        var messageNode = document.createElement("li");
        messageNode.innerHTML = message;
        dialogNode.appendChild(messageNode);
        dialogNode.scrollTop = dialogNode.scrollHeight;
    };
    GUI.prototype.initOrder = function (userCount, startUser) {
        var orderStringCount = 8;
        var orderString = new Array(orderStringCount).fill("1")
            .map(function (v, i) { return (startUser + i) % userCount === 0 ? username : "COM" + (startUser + i) % userCount; })
            .join(" => ");
        this.message("게임이 시작되었습니다!!!");
        this.message("게임순서 : " + orderString + "...");
    };
    GUI.prototype.getProgressColor = function (progress) {
        var interval = [30, 60, 100];
        var color = ["green", "yellow", "red"];
        var index = interval.indexOf(interval.filter(function (v) { return v > progress; })[0]);
        return color[index];
    };
    GUI.prototype.resetTime = function (duration) {
        var _this = this;
        clearInterval(this.timerInterval);
        var startTime = Date.now();
        this.timerInterval = setInterval(function () {
            var now = Date.now();
            var progress = (now - startTime) / duration * 100 - 1;
            var progressColor = _this.getProgressColor(progress);
            _this.domList.progress.style.background = "linear-gradient(to right," + progressColor + " " + (100 - progress) + "%,white " + (100 - progress + 0.1) + "%)";
        }, 10);
    };
    GUI.prototype.setEnemyTurn = function (order) {
        this.nextUser = "COM" + order;
    };
    GUI.prototype.setMyTurn = function () {
        this.nextUser = username;
    };
    GUI.prototype.gameOver = function (reason, lastCount) {
        this.domList.answer.innerHTML = reason;
        this.message("게임이 끝났습니다!!");
        this.message("최종 카운트: " + lastCount);
        input.setGame(null);
        this.domList.gamelink.style.display = "block";
        clearInterval(this.timerInterval);
    };
    GUI.prototype.setNumber = function (number) {
        this.domList.answer.innerHTML = number;
    };
    GUI.prototype.sayNumber = function (number, name) {
        if (name === void 0) { name = this.nextUser; }
        this.message(name + " : " + number);
    };
    GUI.prototype.setHandClab = function (clab) {
        this.domList.answer.innerHTML = clab;
    };
    return GUI;
}());
var Game = /** @class */ (function () {
    function Game(gui, playerCount, time) {
        if (playerCount === void 0) { playerCount = 3; }
        if (time === void 0) { time = 1000; }
        this.gui = gui;
        this.playerCount = playerCount;
        this.time = time;
        this.order = Math.floor(Math.random() * playerCount);
        this.number = 1;
        gui.initOrder(playerCount, this.order);
        this.turnStart();
    }
    Game.prototype.next = function () {
        var prevNumber = getAnswer(Number(this.number));
        this.gui.sayNumber(prevNumber);
        this.order = (this.order + 1) % this.playerCount;
        this.handClab = "";
        this.number++;
        this.turnStart();
    };
    Game.prototype.turnStart = function () {
        this.gui.resetTime(this.time);
        if (this.order === 0)
            this.myTurn();
        else
            this.enemyTurn();
    };
    Game.prototype.enemyTurn = function () {
        var _this = this;
        this.gui.setEnemyTurn(this.order);
        this.turnTimeout = setTimeout(function () {
            _this.shortenTime();
            _this.next();
        }, this.time * Math.random());
    };
    Game.prototype.myTurn = function () {
        var _this = this;
        this.gui.setMyTurn();
        this.turnTimeout = setTimeout(function () {
            if (getAnswer(_this.number) === _this.handClab)
                _this.next();
            else
                _this.gameOver("시간 초과!");
        }, this.time);
    };
    Game.prototype.sayNumber = function (answer) {
        clearTimeout(this.turnTimeout);
        var reasonGameOver = null;
        if (this.order > 0)
            reasonGameOver = "내 차례가 아닌데 말해버림!";
        else if (getAnswer(this.number) === answer)
            null;
        else
            reasonGameOver = "오답!";
        if (reasonGameOver === null)
            this.next();
        else {
            gui.sayNumber(answer, username);
            this.gameOver(reasonGameOver);
        }
    };
    Game.prototype.setHandClab = function (clab) {
        this.handClab = clab;
    };
    Game.prototype.gameOver = function (reason) {
        clearTimeout(this.turnTimeout);
        this.gui.gameOver(reason, this.number);
        game = null;
    };
    Game.prototype.shortenTime = function () {
        this.time *= 0.94;
    };
    return Game;
}());
var Input = /** @class */ (function () {
    function Input(game, gui) {
        this.game = game;
        this.gui = gui;
        this.clickEventType = isMobile() ? "touchstart" : "click";
        this.resetNumber();
        this.bindKeyBoardEvent();
        this.bindKeyPadEvent();
    }
    Input.prototype.setGame = function (game) {
        this.game = game;
    };
    Input.prototype.bindKeyBoardEvent = function () {
        var _this = this;
        document.addEventListener("keydown", function (e) {
            var key = e.key;
            if (["Enter", "Space"].some(function (v) { return v === key; }))
                return _this.pressEnter();
            else if (key === "BackSpace")
                _this.number = _this.number.slice(0, -1);
            else if (isNaN(parseInt(key)))
                return;
            else
                _this.number += key;
            _this.gui.setNumber(_this.number);
        });
    };
    Input.prototype.bindKeyPadEvent = function () {
        var _this = this;
        document.querySelectorAll(".keypad .key").forEach(function (node) {
            node.addEventListener(_this.clickEventType, function (e) {
                e.preventDefault();
                _this.number += e.target.dataset.num;
                _this.gui.setNumber(_this.number);
            });
        });
        document.querySelector(".keypad .enter").addEventListener(this.clickEventType, function (e) {
            e.preventDefault();
            _this.pressEnter();
        });
        document.querySelector(".keypad .reset").addEventListener(this.clickEventType, function (e) {
            e.preventDefault();
            _this.resetNumber();
            _this.gui.setNumber(_this.number);
        });
    };
    Input.prototype.pressEnter = function () {
        var _this = this;
        if (game == null || game == undefined)
            this.gui.message("아직 게임이 시작되지 않았어요.");
        clearTimeout(this.enterTimeout);
        if (this.number == "") {
            this.enterCount++;
            var answer_1 = "짝!".repeat(this.enterCount);
            this.gui.setHandClab(answer_1);
            this.game.setHandClab(answer_1);
            this.enterTimeout = setTimeout(function () {
                if (_this.game.order === 0) {
                    _this.game.sayNumber(answer_1);
                }
                _this.resetNumber();
            }, 800);
        }
        else {
            this.game.sayNumber(this.number);
            this.resetNumber();
        }
    };
    ;
    Input.prototype.resetNumber = function () {
        this.number = "";
        this.enterCount = 0;
        this.gui.setNumber(this.number);
    };
    return Input;
}());
var game = null;
var createGame = function (gui) { return game = new Game(gui, 4, 5000); };
var username = mw.config.values.wgUserName;
var gui = new GUI();
//createGame(gui);
var input = new Input(game, gui);

		
  }

}
$( plugin_real369 );
/* real369 끝 */

/** 플러그인 msgame***************************
* 스톱워치 게임
* 버전 => 0.950
* 작성자 : [[사용자:Riemann|Riemann]] 
* JSON => msgame = {"name":"msgame","descript":"스톱워치 게임","version":"0.950","local":true,"creat":"Riemann","state":"사용자:Riemann/msgame","executable":true}; 
*/ 
function plugin_msgame(){
  if($("[data-name='msgame']").length >= 1){
		  // 이부분에 코드 입력 //
sc = 0
cb = 0

bl = false;
$(document.body).on("keydown", function(ev) {
  if(ev.which == 13) {
    if (bl == false) {
  	  bl = true
      startF();
    } else {
      bl = false
      stopF();
    }
  }
});

$("#msgame-start").on("click", function() {
  bl = true
	startF();
});

$("#msgame-stop").on("click", function() {
  bl = false
	stopF();
});

function startF() {
  obj = Math.floor(Math.random() * 10) + 5;
  $("#msgame-start").css("display", "none");
  $("#msgame-stop").css("display", "block");
  it = new Date();
  si = setInterval(clockUpdate, 20)
  $("#msgame-console").text(obj + " 초를 세세요.");
}

function stopF() {
  $("#msgame-clockText").css("display", "inline");
  $("#msgame-stop").css("display", "none");
  $("#msgame-start").css("display", "block");
  clearInterval(si);
  ie = new Date();
  ifin = ie - it;
  $("#msgame-clockText").text(toMilliSec(ifin));
  finished(obj, ifin);
}

function clockUpdate() {
  ic = new Date();
  id = ic - it;
  ii = toMilliSec(id);
  $("#msgame-clockText").text(ii);
  if (obj * 1000 - id < 500 * cb && cb > 4 ) {
    $("#msgame-clockText").fadeOut();
  }
}

function toMilliSec(d) {
  return (Math.floor(d / 1000) + "\"" + ("" + d % 1000).padStart(3, "0")).padStart(6, "0");
}

function finished(a, b) {
  ath = a * 1000
  if (ath == b) {
    cbm = Math.floor(Math.pow(800, (1 + cb / 10)))
    $("#msgame-console").text("정확하시군요. " + cbm + " 점 드리겠습니다.");
    sc += cbm
    cb += 1
  } else if (Math.abs(ath - b) < 100) {
    cbm = Math.floor(Math.pow((500 / Math.abs(ath - b)), (1 + cb / 10)))
    $("#msgame-console").text("정확하시군요. " + cbm + " 점 드리겠습니다.");
    sc += cbm
    cb += 1
  } else {
    $("#msgame-console").text("안타깝습니다. 조금 더 노력해 보세요!");
    cb = 0
  }
  $("#msgame-score").text(sc);
  $("#msgame-combo").text(cb);
}
 // 여기까지 코드 입력 //

		
  }

}
$( plugin_msgame );
/* msgame 끝 */

/** 플러그인 numbase***************************
* 숫자야구 remake
* 버전 => 1.41
* 작성자 : [[사용자:Riemann|Riemann]] 
* JSON => numbase = {"name":"numbase","descript":"숫자야구 remake","version":"1.41","local":true,"creat":"Riemann","state":"사용자:Riemann/numbase","executable":true}; 
*/ 
function plugin_numbase(){
  if($("[data-name='numbase']").length >= 1){
		 
var title = mw.config.get('wgPageName');
if (title.slice( -1 ) == "4") {
    var no = 4
    }
else {
    var no = 3
}

var trial = 0;
var d = new Date();
$("#sBtn").click(function(){
    $("#description").css("display", "none");
    $("#sBtn").css("display", "none");
    $("#res").css("display", "table");
    cpuNum = initNumbase();
    document.getElementById('count').innerHTML = "시도 횟수: " + trial;
    var bDate = d.getTime();
    numGuess(bDate);
});

function initNumbase() {
var choice = "";
var initArray = [0,1,2,3,4,5,6,7,8,9];
var i, j;
for (i = 0; i < no; i++) {
    j = Math.floor(Math.random() * initArray.length);
    choice += initArray[j];
    initArray.splice(j,1);
}
return choice;
}

function numGuess(bDate) {
document.getElementById('disp').style.display = 'table';
document.getElementById('numList').style.display = 'block';
var numb = document.getElementById('numList');
var numBlocks = "";
var disp = "";
document.getElementById('disp').innerHTML = disp;
for (i = 0; i < 10; i++) {
    numBlocks += "" + i + "";
}
numBlocks += "C";
numBlocks += "입력";
numb.innerHTML = numBlocks;

function restrictLen(l,n) {
   if (l.length < no) {
        l += n;
   } else {
        alert(no + " 자리로 입력하세요.");
   }
   return l;
}

$("#numBlock0").click(function(){
    disp = restrictLen(disp,0);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock0").css("display", "none");
});
$("#numBlock1").click(function(){
    disp = restrictLen(disp,1);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock1").css("display", "none");
});
$("#numBlock2").click(function(){
    disp = restrictLen(disp,2);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock2").css("display", "none");
});
$("#numBlock3").click(function(){
    disp = restrictLen(disp,3);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock3").css("display", "none");
});
$("#numBlock4").click(function(){
    disp = restrictLen(disp,4);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock4").css("display", "none");
});
$("#numBlock5").click(function(){
    disp = restrictLen(disp,5);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock5").css("display", "none");
});
$("#numBlock6").click(function(){
    disp = restrictLen(disp,6);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock6").css("display", "none");
});
$("#numBlock7").click(function(){
    disp = restrictLen(disp,7);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock7").css("display", "none");
});
$("#numBlock8").click(function(){
    disp = restrictLen(disp,8);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock8").css("display", "none");
});
$("#numBlock9").click(function(){
    disp = restrictLen(disp,9);
    document.getElementById('disp').innerHTML = disp;
    $("#numBlock9").css("display", "none");
});
$("#numBlockC").click(function(){
    disp = "";
    document.getElementById('disp').innerHTML = disp;
    $(".numBlock").css("display", "inline-flex");
});
$("#numBlockX").click(function(){
    if (disp.length < no) {
        alert(no + " 자리로 입력하세요.")
    } else {
        trial += 1
        document.getElementById('count').innerHTML = "시도 횟수: " + trial;
        v = valid(disp,cpuNum);
        $("#res").append("" + trial + "" + disp + "" + v + "");
        disp = "";
        document.getElementById('disp').innerHTML = disp;
        $(".numBlock").css("display", "inline-flex");
        if ((v == "0B 3S" && no == 3) || (v == "0B 4S" && no == 4)) {
            var dd = new Date();
            var duration = Math.floor((dd.getTime() - bDate) / 1000);
            document.getElementById('end').innerHTML = "축하합니다. 정수를 맞히셨습니다. " + trial + "회, " + duration + "초가 소비되었습니다. 이용해주셔서 감사합니다.";
            $("#disp").css("display", "none");
            $("#numList").css("display", "none");
            $("#end").css("display", "inline");
            return 0;
        }
    }
});
}

function valid(u,c) {
    var b = 0;
    var s = 0;
    var bs;
    for (i = 0; i < no; i++) {
        for (j = 0; j < no; j++) {
            if (u[i] == c[j]) {
                if (i == j) {
                    s += 1;
                }
                else {
                    b += 1;
                }
            }
        }
    }
    bs = "" + b + "B " + s + "S"
    return bs;
}

		
  }

}
$( plugin_numbase );
/* numbase 끝 */

/** 플러그인 uncyslide***************************
* 백괴슬라이드 실행
* 버전 => 1.1.02
* 작성자 : [[사용자:BANIP|BANIP]] 
* JSON => uncyslide = {"name":"uncyslide","descript":"백괴슬라이드 실행","version":"1.1.02","local":true,"creat":"BANIP","state":"백괴슬라이드/플러그인","executable":true}; 
*/ 
function plugin_uncyslide(){
  if($("[data-name='uncyslide']").length >= 1){
		 // 이부부분에 코드 입력 //
var slideable = plugin_Slideable();
var create = slideable.create;
var execute = slideable.execute;
var dispose = slideable.dispose;

var rankingSystem = plugin_RankingSystem()("백괴슬라이드/랭킹", function(prev,next){ return Number(prev.time) - Number(next.time)});
var outputKeys = {time:"소요시간"};
var startMap = localStorage.getItem("uncySlide/startmap") || 0;
var game = {
    0: {
        center: "아래로 밀어주세요.",
        bottom: 1
    },
    1: {
        center: "오른쪽으로 밀어보세요.",
        right: 2
    },
    2: {
        center: "어디로 밀어보실래요?",
        top: 3,
        bottom: 3,
    },
    3: {
        center: "반갑습니다. 백괴슬라이드입니다.",
        bottom: 4,
    },
    4: {
        center: "어디로 당기고 미느냐에 따라, 게임의 결과가 달라집니다.",
        bottom: 5,
    },
    5: {
        center: "는 개뿔 이겜 시스템만든다고 그런 장황한거 만들 정신머리는 없었습니다",
        bottom: 5.1,
    },
    5.1: {
        center: "진심 힘들었습니다.",
        bottom: 5.2,
    },
    5.2: {
        center: "잘했죠?",
        bottom: 5.3,
    },
    5.3: {
        center: "위로 밀어서 칭찬하거나 아래로 밀어서 욕해주세요.",
        top: 5.4,
        bottom: 5.5,
    },
    5.4: {
        center: "감사합니다. 헤헤",
        bottom: 6,
    },
    5.5: {
        center: "흑흑.. 힘들었는데..",
        bottom: 6,
    },
    6: {
        center: "그래도 미디어위키의 틀에서 벗어난 겜인만큼 최대한 나은 경험을 선사하고자 노력했습니다. 잘부탁드립니다.",
        bottom: function(){
            localStorage.setItem("uncySlide/startmap","main");
            execute("main");
        },
    },
    main: {
        center: "아래: 게임시작토론: 위설명: 오른쪽",
        bottom: function(){ execute("start",{count:100,time:Date.now()}) },
        top: "debate",
        right: "i0",
    },
    i0: {
        center:"가장자리에 화살표 보이죠?",
        bottom:"i1"
    },
    i1: {
        center:"화면을 넘겨서 드래그해서 진행하는 게임이에요.",
        bottom:"i2"
    },
    i2: {
        center:"원래라면 좀 큰 스케일의 게임으로 만들고 싶었는데..",
        bottom:"i3"
    },
    i3: {
        center:"제 역량이 겜 크기에서 다 드러나네요...",
        bottom:"i4"
    },
    i4: {
        center:"아무쪼록 힘들게 만들었으니 재밌게 즐겨주세요.",
        right:"main"
    },
    debate: function(){
        location.href = "https://libertyga.me/wiki/%ED%86%A0%EB%A1%A0:%EB%B0%B1%EA%B4%B4%EC%8A%AC%EB%9D%BC%EC%9D%B4%EB%93%9C";
    },
    start: function(arg){
        function getRandomDirection(){
            switch( Math.ceil(Math.random() * 4) ){
                case 1: return "top"; break;
                case 2: return "bottom"; break;
                case 3: return "left"; break;
                case 4: return "right"; break;
            }
        }
        function getColorCode(count,maxcount){
            var code = "hsl(" + count / maxcount * 360 +",100%,70%)";
            return code
        }
        
        var count = arg.count;
        var maxcount = arg.maxcount || count;
        var time = arg.time;
        var $this = $(this);
        var timerInterval;
        var slideableItem = {
            center: function(){
                var $this = $(this);
                $this.css({
                    "background": getColorCode(count,maxcount)
                });
                
                timerInterval = setInterval(function(){
                    var overtime = (Date.now() - time) * 0.001;
                    var printableTime = overtime.toFixed(2);
                    $this.find(".counter").html(printableTime + "초");
                },5)
                
                return "" + count + "";
            }
        };

        slideableItem[getRandomDirection()] = function(){
            clearInterval(timerInterval);
            if(count === 1) return execute("result",{count:count - 1,time:time,maxcount:maxcount});
            execute("start",{count:count - 1,time:time,maxcount:maxcount}) 
        };

        create(slideableItem);
    },
    result: function(arg){
        var maxcount = arg.maxcount || count;
        var time = ( (Date.now() - arg.time) / 1000 ).toFixed(2);
        var updateParam = {
        	time: time,
        	name: mw.config.get("wgUserName")
        };
        rankingSystem.update(updateParam,function(rankingScore,thisScore){ return rankingScore.time > thisScore.time},outputKeys);

        create({
            center: "갯수: " + maxcount + " 시간: " + time + "왼쪽: 메인으로오른쪽: 토론으로",
            left:"main",
            right:"debate",
        });
    }
}
dispose(game, startMap, {});
		
  }

}
$( plugin_uncyslide );
/* uncyslide 끝 */

/** 플러그인 Slideable***************************
* 슬라이드 플러그인 라이브러리
* 버전 => 1.0.21
* 작성자 : [[사용자:BANIP|BANIP]] 
* JSON => Slideable = {"name":"Slideable","descript":"슬라이드 플러그인 라이브러리","version":"1.0.21","local":true,"creat":"BANIP","state":"사용자:BANIP/플러그인/슬라이드","executable":false}; 
*/ 
function plugin_Slideable(){
  if($("[data-name='Slideable']").length >= 1){
		 // 이부부분에 코드 입력 //
    //모든 키 순회
    function forEach(object, callback) {
        for (var key in object) {
            var variable = object[key];
            callback(variable, key);
        }
    }

function create(directionData) {
    function initClassName($target, data) {
        forEach(data, function(value, direction) {
            $target.find("." + direction).addClass("on");
        })
    }

    function initDOM($target, data) {
        $target[0].data = data;
        $target.find(".center").html(data.center);
        $target.find(".top.on").css("background","url('https://upload.wikimedia.org/wikipedia/commons/8/85/Arrow_top_svg.svg') no-repeat center");
        $target.find(".bottom.on").css("background","url('https://upload.wikimedia.org/wikipedia/commons/f/f2/Arrow_bottom_svg.svg') no-repeat center");
        $target.find(".left.on").css("background","url('https://upload.wikimedia.org/wikipedia/commons/4/40/Arrowleft_svg.svg') no-repeat center");
        $target.find(".right.on").css("background","url('https://upload.wikimedia.org/wikipedia/commons/e/ec/Arrow2right.svg') no-repeat center");
    }

    var slideUtil = {
        moveObject: function($this, axis) {
            var x = axis[0], y = axis[1];

            var data = $this[0].data;
            if (!data.right && x > 0) x = 0;
            if (!data.left && x < 0) x = 0;
            if (!data.top && y < 0) y = 0;
            if (!data.bottom && y > 0) y = 0;
            $this.css("transform", "translate(" + x + "px," + y + "px)");
        },
        isHideable: function($this, axis, limit) {
            var x = axis[0], y = axis[1];
            var data = $this[0].data;
            if (data.right && x > limit) return "right";
            if (data.left && x < limit * -1) return "left";
            if (data.bottom && y > limit) return "bottom";
            if (data.top && y < limit * -1) return "top";
        },
        hide: function(direction, $this) {
            function getCss(direction) {
                var css = {
                    opacity: 0.01
                };
                var interval = 50;
                switch (direction) {
                    case "left":
                        css.left = -1 * interval + "vw";
                        break;
                    case "right":
                        css.left = interval + "vw";
                        break;
                    case "bottom":
                        css.top = interval + "vh";
                        break;
                    case "top":
                        css.top = -1 * interval + "vh";
                        break;
                }

                return css;
            }

            var self = $this[0];
            var data = self.data;
            if (self.isHide === true) {
                return;
            }
            self.isHide = true;
            $this.animate(getCss(direction), {
                duration: 300,
                easing: "swing",
                start: data[direction],
                complete: function() {
                    $this.remove();
                }
            });
        }
    }

    function setEvent($target, data) {
        var util = slideUtil;
        var moveLimit = 50;

        $(".slideable").mousedown(function(e) {
            this.isMouseDown = true;
            this.startAxis = [e.clientX, e.clientY];
        })

        $(".slideable").mousemove(function(e) {
            if (this.isMouseDown) {
                event.preventDefault()
                var axis = [e.clientX, e.clientY];
                var startAxis = this.startAxis;
                var moveInterval = [axis[0] - startAxis[0], axis[1] - startAxis[1]]
                util.moveObject($(this), moveInterval);
                var hideDirection = util.isHideable($(this), moveInterval, moveLimit);
                if (hideDirection) util.hide(hideDirection, $(this));
            }
        })

        $(".slideable").mouseup(function(e) {
            this.isMouseDown = false;
        })

        function getTouchEvent(e) {
            return e.originalEvent.touches[0]
        }

        $(".slideable").on("touchstart", function(e) {
            var touch = getTouchEvent(e);

            this.isMouseDown = true;
            this.startAxis = [touch.clientX, touch.clientY];
        })

        $(".slideable").on("touchmove", function(e) {
            event.preventDefault()
            if (this.isMouseDown) {
                event.preventDefault()
                var touch = getTouchEvent(e);
                var axis = [touch.clientX, touch.clientY];
                var startAxis = this.startAxis;
                var moveInterval = [axis[0] - startAxis[0], axis[1] - startAxis[1]]
                util.moveObject($(this), moveInterval);
                var hideDirection = util.isHideable($(this), moveInterval, moveLimit);
                if (hideDirection) util.hide(hideDirection, $(this));
            }
        })

        $(".slideable").on("touchend", function(e) {
            this.isMouseDown = false;
        })

    }

    //슬라이드아이템의 방향키로 숫자 혹은 문자로 지정된 경우
    //함수로 변환
    function setExecutable(target, item){
        forEach(item,function(value,direction){
            new Promise(function(resolve, reject){
                 if(direction === "center"){
                    switch( typeof value ){
                    case "function":
                        resolve( value.bind(target)() );
                    break;
                  }
              } else {
                switch( typeof value ){
                    case "string": case "number":
                        resolve(function(){ execute(value); }.bind(target));
                    break;
                }
              }
            }).then(function(result){
                 item[direction] = result;
            })

        })
    }
    
    var $target = $(".slideable.cloneable").clone().removeClass("cloneable");
    $("body").prepend($target);
    setExecutable($target[0], directionData);
    initClassName($target, directionData);
    initDOM($target, directionData);
    setEvent($target, directionData);
}

// create는 다른 함수들에 의존하지 않음 //
var game;

function execute(number, argument) {
    dispose(game, number, argument);
}

function dispose(slideableArray, start, argument) {
    game = slideableArray;
    
    var slideableItem = slideableArray[start];
    switch (typeof slideableItem) {
        case "function":
            slideableItem(argument);
            break;
        case "object":
            create(slideableItem);
            break;
    }
}

//모바일 전체화면으로 수정
var setFullScreen = (function(){
    //window.scrollTo(0,1);
})();

return {
    create: create,
    execute: execute,
    dispose: dispose
}
		
  }

}
/* Slideable 끝 */



/** 플러그인 RankingSystem***************************
* 랭킹시스템 라이브러리
* 버전 => 1.1.0
* 작성자 : [[사용자:BANIP|BANIP]] 
* JSON => RankingSystem = {"name":"RankingSystem","descript":"랭킹시스템 라이브러리","version":"1.1.0","local":true,"creat":"BANIP","state":"사용자:BANIP/플러그인/랭킹시스템","executable":false}; 
*/ 
function plugin_RankingSystem(){
  if($("[data-name='RankingSystem']").length >= 1){
		 // 이부부분에 코드 입력 //

/**
  * @param 
  		{string} documentTitle 랭킹정보가 있는 문서의 제목.
  		{function} sortCallback 랭킹을 정렬할때 기준으로 사용하는 함수
  		    {any} prev 랭킹 정렬 기준으로 사용할 왼쪽의 값
  		   	{any} next 랭킹 정렬 기준으로 사용할 오른쪽의 값
  		{object} api MediaWikiapi의 인스턴스, 없어도 됨.

  	@return {Object}
  		{function} get 랭킹정보를 object형태로 획득
  		{function} update 랭킹정보 업데이트
  			{object} updateInfo 업데이트할 사용자 정보
  			{function} updateCriteria 사용자정보의 업데이트 기준
  			@param {any} rankingScore 랭킹에서 사용중인 스코어
  				   {any} thisScore 사용자 스코어
  			@return{bool} true가 반환되면 업데이트
  			{object} alternateKeys 랭킹에서 보여지는 대체 키
*/

return function(documentTitle, sortCallback, api) {
    function forEach(object, callback) {
        for (var key in object) {
            var variable = object[key];
            callback(variable, key);
        }
    }

    function getRankingJSON(rankingDoc) {
        if (!rankingDoc) return {};
        var includeOnlyString = "includeonly"
        var regexp = new RegExp("\<" + includeOnlyString + "\>(.*)\<\/" + includeOnlyString + "\>");
        var stringRanking = regexp.exec(rankingDoc)[1];
        return JSON.parse(stringRanking);
    }

    function updateDoc(rankingJSON, api, alternateKeys) {
        //alternateKeys가 반영된 개개인의 랭킹정보 획득
        function getOutputJSON(json) {
            var result = {};
            forEach(json, function(value, key) {
                key = alternateKeys[key] || key;
                result[key] = value;
            })
            return result;
        }

        //보여지는 형태의 랭킹정보 획득
        function getOutputString(json) {
            var name = json.name;
            var result = "* '''" + name + "''' : ";
            forEach(json, function(value, key) {
                if (key === "name") return;
                key = alternateKeys[key] || key;
                result += key + ": " + value + ", ";
            })
            result += "\n"
            return result
        }

        var stringRanking = JSON.stringify(rankingJSON);
        var result = "<includ" + "eonly>" + stringRanking + "</inclu" + "deonly>\n";
        result += "<onlyin" + "clude>\n";

        var rankingList = Object.entries(rankingJSON).sort(function(prev,next){
          return sortCallback(prev[1],next[1])
        }).map(function(value){
          return value[0]
        });

        rankingList.forEach(function(key) {
            var json = rankingJSON[key];
            var outputJSON = getOutputJSON(json);
            result += getOutputString(outputJSON)
        });

        result += "</only" + "include>";
        var reply = documentTitle.replace(new RegExp("\/.*"),"") + " 점수 갱신";
        api.changeDocument(documentTitle, reply, result, true);
        return result;
    }

    function updateUserScore(rankingJSON, thisScore, updateCriteria) {
        updateCriteria = updateCriteria || function(rankingScore, thisScore) {
            return rankingScore.score < thisScore.score;
        }

        var userName = thisScore.name;
        var rankingScore = rankingJSON[userName];

        if (!rankingScore || updateCriteria(rankingScore, thisScore)) {
            rankingJSON[userName] = thisScore;
        }
    }

    api = api || MediaWikiAPI();
    var userName = mw.config.get("wgUserName");
    var rankingDoc = api.getDocument(documentTitle);
    var rankingJSON = getRankingJSON(rankingDoc);

    var actions = {
        get: function() {
            return rankingJSON;
        },
        update: function(updateInfo, updateCriteria, alternateKeys) {
            rankingJSON = actions.get();
            updateUserScore(rankingJSON, updateInfo, updateCriteria);
            updateDoc(rankingJSON, api, alternateKeys);
        }
    }
    return actions;
}

		
  }

}
/* RankingSystem 끝 */