사용자:Hd219134/common.js: 두 판 사이의 차이
백괴게임>Hd219134 (플러그인 uncyslide,Slideable설치) |
백괴게임>Hd219134 잔글편집 요약 없음 |
||
833번째 줄: | 833번째 줄: | ||
$( plugin_haircut ); | $( plugin_haircut ); | ||
/* haircut 끝 */ | /* haircut 끝 */ | ||
2019년 1월 15일 (화) 21:32 판
/** 플러그인 SimMD5***************************
* 마법의 MD-5 시뮬레이터 게임에 사용되는 스크립트로, 인터페이스와 배틀시스템을 구현합니다.
* 버전 => 1.3
* 작성자 : [[사용자:Gustmd7410|Gustmd7410]]
* JSON => SimMD5 = {"name":"SimMD5","descript":"마법의 MD-5 시뮬레이터 게임에 사용되는 스크립트로, 인터페이스와 배틀시스템을 구현합니다.","version":"1.3","local":true,"creat":"Gustmd7410","state":"마법의 MD-5 시뮬레이터/플러그인","executable":true};
*/
function plugin_SimMD5(){
if($("[data-name='SimMD5']").length >= 1){
// 이부분에 코드 입력 //
mw.loader.using('oojs-ui-widgets').done(function() {
function prepare() {
function responsible(event) {
var button = $('#input-time .oo-ui-numberInputWidget-plusButton, #input-time .oo-ui-numberInputWidget-minusButton');
if(event.matches) {
button.css('display', 'none');
input.time.$label.css('margin-right', null);
} else {
button.css('display', 'null');
input.time.$label.css('margin-right', '30px');
}
}
function encode(string) {
return string
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/{/g, '{')
.replace(/\|/g, '|')
.replace(/=/g, '=')
.replace(/}/g, '}')
.replace(/\[/g, '[')
.replace(/\]/g, ']')
.replace(/_/g, '_');
}
function cancel(btn) {
if(stat.length) {
battle.done = null;
battle.turn = 0;
battle.attack = null;
battle.sequence = null;
battle.combo = null;
battle.temp = null;
bar = [];
bar[0] = new OO.ui.ProgressBarWidget({
progress: 100
});
bar[1] = new OO.ui.ProgressBarWidget({
progress: 100
});
bar[0].$bar.css({
background: '#3366CC'
});
bar[0].$element.css({
'border-right': 'none',
'border-top-right-radius': 0,
'border-bottom-right-radius': 0
});
bar[1].$bar.css({
background: '#FF5500'
});
bar[1].$element.css({
'border-left': 'none',
'border-top-left-radius': 0,
'border-bottom-left-radius': 0
});
input.start.setLabel('재시작');
input.reset.setLabel('초기화');
$('#stat-turn').text(0);
$('.stat-0.stat-currentHP').data('value', stat[0].HP).text(stat[0].HP.toFixed(2)).css('color', '#3366CC');
$('.stat-1.stat-currentHP').data('value', stat[1].HP).text(stat[1].HP.toFixed(2)).css('color', '#FF5500');
$('.stat-0.stat-HPbar').html(bar[0].$element);
$('.stat-1.stat-HPbar').html(bar[1].$element);
if(btn) $('#log')[0].innerText += '\n다시 시작하려면 재시작 버튼을 눌러주세요.';
}
}
function stop() {
clearInterval(battle.work);
$('#input-stop').hide();
$('#input-start').show();
input.reset.setDisabled(false);
input[0].setDisabled(false);
input[1].setDisabled(false);
input.time.setDisabled(false);
input.swap.setDisabled(false);
}
var input = {};
input[0] = new OO.ui.TextInputWidget({
placeholder: '선',
title: '후',
value: new URLSearchParams(location.search).get('p0') || ''
});
input.start = new OO.ui.ButtonInputWidget({
type: 'submit',
flags: ['primary', 'progressive'],
label: '시작'
});
input.stop = new OO.ui.ButtonInputWidget({
flags: ['primary', 'destructive'],
label: '정지'
});
input[1] = new OO.ui.TextInputWidget({
placeholder: '후',
title: '후',
value: new URLSearchParams(location.search).get('p1') || ''
});
input.time = new OO.ui.NumberInputWidget({
value: 1,
min: 0,
label: '초 간격'
});
input.reset = new OO.ui.ButtonInputWidget({
type: 'reset',
flags: ['destructive'],
label: '초기화'
});
input.swap = new OO.ui.ButtonInputWidget({
label: $('<div />').css({
height: '20px',
width: '20px',
'background-image': 'url("/wiki/Special:Redirect/file/Ambox_move_black.svg")',
'background-size': 'cover'
}),
title: '교체',
framed: false
});
input.table = new OO.ui.ToggleSwitchWidget({
value: true
});
input.icon = new OO.ui.ButtonWidget({
framed: false,
icon: $('#mw-customcollapsible-input-option').hasClass('mw-collapsed')? 'expand' : 'collapse'
});
input.log = new OO.ui.ButtonWidget({
label: '기록 복사'
});
input.url = new OO.ui.ButtonWidget({
label: 'URL 복사'
});
input.box = new OO.ui.MultilineTextInputWidget();
var media = matchMedia('(max-width: 800px)');
var stat = [];
var bar = [];
var battle = {
turn: 0,
attack: null,
done: null,
work: null,
sequence: null,
combo: null,
temp: null
};
$('#input').wrap('<form />');
$('#input-0').html(input[0].$element);
$('#input-start').html(input.start.$element);
$('#input-stop').html(input.stop.$element);
$('#input-1').html(input[1].$element);
$('#input-time').html(input.time.$element);
$('#input-reset').html(input.reset.$element);
$('#input-swap').html(input.swap.$element);
$('#input-table').html(input.table.$element).append(' 스탯');
$('#input-icon').html(input.icon.$element);
$('#stat-load').html(new OO.ui.ProgressBarWidget().$element);
$('#log').text('시작하시려면 상단에 대결할 상대의 이름을 입력해 주세요. (1.3)');
$('#share-log').html(input.log.$element);
$('#share-url').html(input.url.$element);
$('#share-cvbox').html(input.box.$element);
input.box.$input.attr('readonly', '').css('height', '2.5em');
$('#stat-bar').hide();
$('#share').hide();
responsible(media);
media.addListener(responsible);
new MutationObserver(function(mutation) {
input.icon.setIcon($(mutation[0].target).hasClass('mw-collapsed')? 'expand' : 'collapse');
}).observe($('#mw-customcollapsible-input-option')[0], {
attributes: true,
attributeFilter: ['class']
});
input.swap.$element.click(function() {
if(!input.swap.disabled) {
var val = [input[1].value, input[0].value];
input[0].setValue(val[0]);
input[1].setValue(val[1]);
if(stat.length) {
stat = [stat[1], stat[0]];
$('#stat-turn').text(0);
$('.stat-0').each(function() {
if($(this).hasClass('stat-name')) $(this).text(stat[0].name);
else if($(this).hasClass('stat-attack')) $(this).text(stat[0].attack);
else if($(this).hasClass('stat-quick')) $(this).text(stat[0].quick);
else if($(this).hasClass('stat-defense')) $(this).text(stat[0].defense);
else if($(this).hasClass('stat-hit')) $(this).text(stat[0].hit);
else if($(this).hasClass('stat-luck')) $(this).text(stat[0].luck);
else if($(this).hasClass('stat-fullHP')) $(this).text(stat[0].HP);
else if($(this).hasClass('stat-currentHP')) $(this).data('value', stat[0].HP).text(stat[0].HP.toFixed(2));
else if($(this).hasClass('stat-HPbar')) $(this).html(bar[0].$element);
});
$('.stat-1').each(function() {
if($(this).hasClass('stat-name')) $(this).text(stat[1].name);
else if($(this).hasClass('stat-attack')) $(this).text(stat[1].attack);
else if($(this).hasClass('stat-quick')) $(this).text(stat[1].quick);
else if($(this).hasClass('stat-defense')) $(this).text(stat[1].defense);
else if($(this).hasClass('stat-hit')) $(this).text(stat[1].hit);
else if($(this).hasClass('stat-luck')) $(this).text(stat[1].luck);
else if($(this).hasClass('stat-fullHP')) $(this).text(stat[1].HP);
else if($(this).hasClass('stat-currentHP')) $(this).data('value', stat[1].HP).text(stat[1].HP.toFixed(2));
else if($(this).hasClass('stat-HPbar')) $(this).html(bar[1].$element);
});
var url = new URL(location);
url.searchParams.set('p0', input[0].value);
url.searchParams.set('p1', input[1].value);
history.replaceState(null, '', url);
cancel();
input.start.setLabel('시작');
}
}
});
input.table.$element.click(function() {
if(input.table.value) {
if($('#stat-turn').text()) $('#stat-table').show(500);
} else {
$('#stat-table').hide(500);
}
});
input.reset.$button[0].form.addEventListener('reset', function(event) {
event.preventDefault();
if(!input.reset.disabled) {
if(battle.done || battle.done === null) {
var url = new URL(location);
url.searchParams['delete']('p0');
url.searchParams['delete']('p1');
history.replaceState(null, '', url);
stat = [];
input[0].setValue();
input[1].setValue();
input.time.setValue(1);
input.table.setValue(true);
input.start.setLabel('시작');
$('#share').hide();
$('#share-cvbox').hide();
$('#stat-table').hide(500);
$('#stat-bar').hide(500);
$('#stat-turn, .stat-0, .stat-1').text('');
$('#log-time').hide();
$('#log').show();
$('#log').text('시작하시려면 상단에 대결할 상대의 이름을 입력해 주세요.');
$('.stat-HPbar').html('');
} else cancel(true);
}
});
input.start.$button[0].form.addEventListener('submit', function(event) {
function last() {
$('#input-stop').show();
$('#input-start').hide();
input.reset.setLabel('취소');
input[0].setDisabled(true);
input[1].setDisabled(true);
input.time.setDisabled(true);
input.reset.setDisabled(true);
input.swap.setDisabled(true);
input.start.setLabel('재개');
battle.work = start(battle, stat.map(function(obj, index) {
return new Proxy(obj, {
get: function(target, key, receiver) {
if(key === 'HP') return +$('.stat-' + index + '.stat-currentHP').data('value');
else return Reflect.get(target, key, receiver);
},
set: function(target, key, value) {
if(key === 'HP') {
if(value < 0) {
value = 0;
$('.stat-' + index + '.stat-currentHP').css('color', '#000000');
}
$('.stat-' + index + '.stat-currentHP').data('value', value).text(value.toFixed(2));
bar[index].setProgress(value / target.HP * 100);
}
}
});
}), input.time.value * 1000, function(msg) {
$('#log')[0].innerText += msg;
$('#log').scrollTop($('#log')[0].scrollHeight);
if(battle.sequence === 0) {
$('#stat-turn').text(battle.turn);
$('.stat-' + battle.attack + '.stat-name').css({
background: battle.attack? '#FF5500' : '#3366CC',
color: '#FFFFFF'
});
$('.stat-' + (battle.attack ^ 1) + '.stat-name').css({
background: '#EAECF0',
color: battle.attack? '#3366CC' : '#FF5500'
});
}
}, function(msg) {
$('#log')[0].innerText += msg;
$('#log')[0].innerText += '\n\n백괴스러운 MD-5 시뮬레이터 [https://game.uncyclopedia.kr/wiki/마법의_MD-5_시뮬레이터]';
$('#log').scrollTop($('#log')[0].scrollHeight);
$('#share').show();
stop();
battle.done = true;
battle.turn = 0;
battle.attack = null;
battle.sequence = null;
battle.combo = null;
battle.temp = null;
input.start.setLabel('재시작');
input.reset.setLabel('초기화');
});
}
event.preventDefault();
if(!input.start.disabled) {
$('#share').hide();
$('#share-cvbox').hide();
if(input.time.value >= 0) {
$('#log-time').hide();
$('#log').show();
if(!stat.length) $.get({
url: '/w/api.php',
data: {
action: 'parse',
format: 'json',
title: '마법의 MD-5 시뮬레이터',
text: '[{{#invoke:SimMD5|stat|' + encode(input[0].value) + '|AJAX}},{{#invoke:SimMD5|stat|' + encode(input[1].value) + '|AJAX}}]',
prop: 'text',
disablelimitreport: true,
formatversion: 2
},
beforeSend: function() {
if($('#stat-bar').html()) {
$('#stat-bar').hide();
$('#stat-load').show();
} else $('#stat-load').show(500);
$('#log').text('스탯 계산중입니다. 잠시만 기다려 주세요.');
var url = new URL(location);
url.searchParams.set('p0', input[0].value);
url.searchParams.set('p1', input[1].value);
history.replaceState(null, '', url);
},
success: function(callback) {
stat = JSON.parse($(callback.parse.text).text());
bar = [];
bar[0] = new OO.ui.ProgressBarWidget({
progress: 100
});
bar[1] = new OO.ui.ProgressBarWidget({
progress: 100
});
bar[0].$bar.css({
background: '#3366CC'
});
bar[0].$element.css({
'border-right': 'none',
'border-top-right-radius': 0,
'border-bottom-right-radius': 0
});
bar[1].$bar.css({
background: '#FF5500'
});
bar[1].$element.css({
'border-left': 'none',
'border-top-left-radius': 0,
'border-bottom-left-radius': 0
});
$('#stat-turn').text(0);
$('.stat-0').each(function() {
if($(this).hasClass('stat-name')) $(this).text(stat[0].name);
else if($(this).hasClass('stat-attack')) $(this).text(stat[0].attack);
else if($(this).hasClass('stat-quick')) $(this).text(stat[0].quick);
else if($(this).hasClass('stat-defense')) $(this).text(stat[0].defense);
else if($(this).hasClass('stat-hit')) $(this).text(stat[0].hit);
else if($(this).hasClass('stat-luck')) $(this).text(stat[0].luck);
else if($(this).hasClass('stat-fullHP')) $(this).text(stat[0].HP);
else if($(this).hasClass('stat-currentHP')) $(this).data('value', stat[0].HP).text(stat[0].HP.toFixed(2));
else if($(this).hasClass('stat-HPbar')) $(this).html(bar[0].$element);
});
$('.stat-1').each(function() {
if($(this).hasClass('stat-name')) $(this).text(stat[1].name);
else if($(this).hasClass('stat-attack')) $(this).text(stat[1].attack);
else if($(this).hasClass('stat-quick')) $(this).text(stat[1].quick);
else if($(this).hasClass('stat-defense')) $(this).text(stat[1].defense);
else if($(this).hasClass('stat-hit')) $(this).text(stat[1].hit);
else if($(this).hasClass('stat-luck')) $(this).text(stat[1].luck);
else if($(this).hasClass('stat-fullHP')) $(this).text(stat[1].HP);
else if($(this).hasClass('stat-currentHP')) $(this).data('value', stat[1].HP).text(stat[1].HP.toFixed(2));
else if($(this).hasClass('stat-HPbar')) $(this).html(bar[1].$element);
});
$('.stat-0.stat-currentHP').css('color', '#3366CC');
$('.stat-1.stat-currentHP').css('color', '#FF5500');
$('#stat-load').hide();
if(input.table.value) $('#stat-table').show(500);
$('#stat-bar').show();
$('#log').text('');
$('#log')[0].innerText += '[' + stat[0].name + '] 공격력: ' + stat[0].attack + ' / 방어력: ' + stat[0].defense + ' / 민첩: ' + stat[0].quick + ' / 명중: ' + stat[0].quick + ' / 운: ' + stat[0].luck + ' / HP: ' + stat[0].HP + '\n';
$('#log')[0].innerText += '[' + stat[1].name + '] 공격력: ' + stat[1].attack + ' / 방어력: ' + stat[1].defense + ' / 민첩: ' + stat[1].quick + ' / 명중: ' + stat[1].quick + ' / 운: ' + stat[1].luck + ' / HP: ' + stat[1].HP + '\n';
$('#log')[0].innerText += '\n';
battle.turn = 1;
battle.done = false;
battle.attack = 0;
battle.sequence = 0;
battle.combo = [0, 0];
battle.temp = {};
last();
},
error: function(error) {
$('#stat-load').hide(500);
$('#log').text('스탯 계산에 오류가 발생하였습니다. 다시 시도해 주십시오. (' + error.status + ')');
}
});
else if(battle.done || battle.done === null) {
if(battle.done) cancel();
$('#log').text('');
$('#log')[0].innerText += '[' + stat[0].name + '] 공격력: ' + stat[0].attack + ' / 방어력: ' + stat[0].defense + ' / 민첩: ' + stat[0].quick + ' / 명중: ' + stat[0].quick + ' / 운: ' + stat[0].luck + ' / HP: ' + stat[0].HP + '\n';
$('#log')[0].innerText += '[' + stat[1].name + '] 공격력: ' + stat[1].attack + ' / 방어력: ' + stat[1].defense + ' / 민첩: ' + stat[1].quick + ' / 명중: ' + stat[1].quick + ' / 운: ' + stat[1].luck + ' / HP: ' + stat[1].HP + '\n';
$('#log')[0].innerText += '\n';
battle.turn = 1;
battle.done = false;
battle.attack = 0;
battle.sequence = 0;
battle.combo = [0, 0];
battle.temp = {};
last();
} else last();
} else {
$('#log-time').show();
$('#log').hide();
}
}
});
input.stop.$element.click(function() {
if(!input.stop.disabled) stop();
});
input[0].$input.focus(function() {
cancel();
stat = [];
input.start.setLabel('시작');
$(this).select();
});
input[1].$input.focus(function() {
cancel();
stat = [];
input.start.setLabel('시작');
$(this).select();
});
input.log.$button.click(function() {
input.box.setValue($('#log').text());
$('#share-cvbox').show();
input.box.$input.select();
document.execCommand('copy');
});
input.url.$button.click(function() {
var url = new URL('/wiki/마법의_MD-5_시뮬레이터', location);
var search = new URLSearchParams(location.search);
url.searchParams.set('p0', search.get('p0'));
url.searchParams.set('p1', search.get('p1'));
input.box.setValue(url);
$('#share-cvbox').show();
input.box.$input.select();
document.execCommand('copy');
});
input.box.$input.click(function() {
$(this).select();
});
}
function start(battle, stat, time, each, last) {
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function range(weight) {
var range = [-0.5, -0.25, 0, 0.25, 0.5].map(function(ratio, index) {
return 20 + (weight - 50) * ratio;
});
range.reduce(function(acc, current, index, prob) {
return prob[index] += acc;
});
return range;
}
function rank(range, val) {
return range.findIndex(function(current, index) {
return (index === 0 || range[index - 1] < val) && val <= current;
});
}
function power(stat, rank) {
return stat * (((rank === 0)? 0 : rand(1 + 25 * (rank - 1), 25 * rank)) / 100);
}
function bonus(plus, minus, rank) {
rank -= 2;
if(rank === 0) return 0;
return ((rank > 0)? plus : minus) * (rand(1 + 50 * (rank - 1), 50 * rank) / 100);
}
function josa(text, exist, not, only) {
text = text.normalize('NFD');
var code = text.charCodeAt(text.length - 1);
if(0x1161 <= code && code <= 0x11A7) return ((only)? '' : text) + not;
else if(0x11A8 <= code && code <= 0x11FF) return ((only)? '' : text) + exist;
else return ((only)? '' : text) + exist + '(' + not + ')';
}
return setInterval(function() {
var attacker = battle.attack;
var defender = attacker ^ 1;
if(stat[0].HP > 0 && stat[1].HP > 0) {
switch(battle.sequence) {
case 0:
var scale = range(stat[attacker].luck);
var adv = bonus(stat[attacker].hit, stat[defender].quick, rank(range(50), 50 + ((battle.combo[defender])? 0 : battle.combo[defender]) - ((battle.combo[attacker])? 0: battle.combo[attacker])));
var grade = {
attack: rank(scale, rand(1, 100)),
defense: rank(range(stat[defender].luck), rand(1, 100)),
};
var damage = power(stat[attacker].attack, grade.attack) - power(stat[defender].defense, grade.defense) + adv;
battle.temp = {
rank: rank(scale, damage),
damage: (damage > 0)? damage : 0
};
if(battle.temp.damage > stat[attacker].attack) battle.temp.rank = 5;
if(battle.temp.damage) {
if(!battle.temp.rank) battle.temp.rank = 1;
if(battle.combo[attacker] < 0) battle.combo[attacker] = 0;
battle.combo[attacker]++;
} else {
battle.temp.rank = 0;
if(battle.combo[attacker] > 0) battle.combo[attacker] = 0;
battle.combo[attacker]--;
}
each('[' + stat[attacker].name + ']의 공격 ');
battle.sequence++;
break;
case 1:
var rankText = ['MISS', 'HIT', 'GOOD', 'NICE', 'PERFECT', 'CRITICAL'][battle.temp.rank];
each(rankText + '! ');
battle.sequence++;
break;
case 2:
stat[defender].HP -= battle.temp.damage;
var msg = (battle.temp.rank === 0)? '공격을 피했다. (' : (+battle.temp.damage.toFixed(2)) + '의 대미지를 받았다. (' + ((battle.combo[attacker] > 0)? battle.combo[attacker] : 0) + ' COMBO, ';
each('[' + stat[defender].name + ']' + josa(stat[defender].name, '은', '는', true) + ' ' + msg + '남은 HP: ' + (+stat[defender].HP.toFixed(2)) + ')\n');
if(attacker === 1) battle.turn++;
battle.sequence = 0;
battle.attack = defender;
break;
}
} else last('\n[' + stat[defender].name + '] 승! (' + battle.turn + '턴)');
}, time);
}
$(prepare);
});
// 여기까지 코드 입력 //
}
}
$( plugin_SimMD5 );
/* SimMD5 끝 */
/** 플러그인 inputform***************************
* 완전한 입력기를 구현합니다. (베타)
* 버전 => 1.6.1
* 작성자 : [[사용자:Gustmd7410|Gustmd7410]]
* JSON => inputform = {"name":"inputform","descript":"완전한 입력기를 구현합니다. (베타)","version":"1.6.1","local":false,"creat":"Gustmd7410","state":"틀:입력 상자/플러그인","executable":true};
*/
function plugin_inputform(){
// 이부분에 코드 입력 //
mw.loader.using('oojs-ui-core').done(function () {
function toBool(value) {
switch (value) {
case undefined: return false;
case '': return true;
}
}
function toArray(value) {
if (value)
return value.split(' ');
else
return undefined;
}
function InpTable(table) {
this["case"] = {};
this["default"] = Object.assign({
prefix: '',
value: undefined,
suffix: '',
replace: [],
sub: [0]
}, table["default"]);
if (table["case"]) {
for (var value in table["case"]) {
this["case"][value] = Object.assign({}, this["default"], { value: this["default"].value || value }, table["case"][value]);
}
}
}
$('.input-form').each(function () {
var container = this;
$(this).html(new $('<form />', {
"class": $(this).data('class'),
id: $(this).data('id'),
style: $(this).data('style'),
'accept-charset': 'UTF-8',
autocomplete: toBool($(this).data('autocomplete')),
novalidate: toBool($(this).data('novalidate')),
html: $(this).html()
}));
$(this).children('form').submit(function (event) {
event.preventDefault();
var action = new URL('/w/index.php', location);
if (toBool($(container).data('pass')))
action.search = location.search;
if ($(container).data('get'))
new URLSearchParams($(container).data('get')).forEach(function (value, key) {
action.searchParams.set(key, value);
});
action.searchParams.set('title', $(container).data('title'));
$(this).children('.input-field').each(function () {
if (typeof ($(this).data('table')) == 'object') {
var name = $(this).data('name');
var rawval = $(this).find('input').val();
var table = new InpTable($(this).data('table'));
var cvttbl = table["case"][rawval] || table["default"];
var cvtval = (cvttbl.value || rawval).slice(cvttbl.sub[0], cvttbl.sub[1]);
cvttbl.replace.forEach(function (reparr) {
var regex = reparr[0].substr(1).split('/');
regex.pop();
regex = regex.join('/');
var flag = reparr[0].substr(1).split('/').reverse()[0];
cvtval = cvtval.replace(new RegExp(regex, flag), reparr[1]);
});
action.searchParams.set(name, cvttbl.prefix + cvtval + cvttbl.suffix);
}
else
action.searchParams.set($(this).data('name'), $(this).find('input').val());
});
location.href = action.href;
});
});
$('.input-field').each(function () {
$(this).html(new OO.ui.TextInputWidget({
accessKey: $(this).data('accessKey'),
autocomplete: toBool($(this).data('autocomplete')),
autofocus: toBool($(this).data('autofocus')),
classes: toArray($(this).data('classes')),
disabled: toBool($(this).data('disabled')),
flags: toArray($(this).data('flags')),
icon: $(this).data('icon'),
iconTitle: $(this).data('iconTitle'),
id: $(this).data('id'),
indicator: $(this).data('indicator'),
indicatorTitle: $(this).data('indicatorTitle'),
inputId: $(this).data('inputId'),
maxLength: Number($(this).data('maxLength')),
name: $(this).data('name'),
placeholder: $(this).data('placeholder'),
readOnly: toBool($(this).data('readOnly')),
required: toBool($(this).data('required')),
spellcheck: toBool($(this).data('spellcheck')),
tabIndex: Number($(this).data('tabIndex')),
text: $(this).data('text'),
title: $(this).data('title'),
type: $(this).data('type'),
validate: (function(container) {
if ($(container).data('validatetype') == 'RegExp') {
var value = $(container).data('validate').substr(1).split('/');
return RegExp(value[0], value[1]);
}
else
return $(container).data('validate');
})(this),
value: this.dataset.value || ''
}).$element);
if(toBool($(this).data('inline'))) $(this).find('*').css({
display: 'inline',
width: 'auto'
});
});
$('.input-button').each(function () {
$(this).html(new OO.ui.ButtonInputWidget({
accessKey: $(this).data('accessKey'),
classes: toArray($(this).data('classes')),
disabled: toBool($(this).data('disabled')),
flags: toArray($(this).data('flags')),
framed: toBool($(this).data('framed')),
icon: $(this).data('icon'),
iconTitle: $(this).data('iconTitle'),
id: $(this).data('id'),
indicator: $(this).data('indicator'),
indicatorTitle: $(this).data('indicatorTitle'),
inputId: $(this).data('inputId'),
label: $(this).data('label'),
name: $(this).data('name'),
tabIndex: Number($(this).data('tabIndex')),
text: $(this).data('text'),
title: $(this).data('title'),
type: $(this).data('type'),
value: $(this).data('value')
}).$element);
});
noPlugin('input');
});
// 여기까지 코드 입력 //
}
$( plugin_inputform );
/* inputform 끝 */
/** 플러그인 haircut***************************
* 게임 진행에 필요합니다.
* 버전 => 2.0
* 작성자 : [[사용자:Lemminkäinen|Lemminkäinen]]
* JSON => haircut = {"name":"haircut","descript":"게임 진행에 필요합니다.","version":"2.0","local":true,"creat":"Lemminkäinen","state":"머리 자르기/js","executable":true};
*/
function plugin_haircut(){
if($("[data-name='haircut']").length >= 1){
// 이부분에 코드 입력 //
/*Elements Load 시작*/
var cut_res_container=document.getElementById("cut_res_container");
var cut_container=document.getElementById("cut_container");
var cut_linehair=document.getElementById("cut_line");
var cuthair=document.getElementById("cuthair");
/*Load 끝*/
var rand=function(r1,r2){
return Math.floor(Math.random()*r1)+r2;
}
var cut_now=rand(400,600);
var cut_line=rand(200,300);
var cut_initial=cut_now-cut_line;
var cdf=document.getElementById("cut_diff").innerHTML;
var cut_diff=(cdf<=0 || isNaN(cdf) || cdf>2)?(0.5):(Number(cdf));
var cut_speed=cut_now/cut_diff;
var cut_result1=0; var cut_result2=0;
cut_res_container.style.display="none";
cut_container.style.height=cut_now+"px";
cut_linehair.style.height=cut_line+"px";
if(cut_initial<=0) { alert('머리가 너무 짧아 자를 수 없습니다!'); throw("WTF your hair is already short"); }
function cut_again(){
$('#scissors').animate({ top:"100%" },cut_speed,'linear',function(){ $('#scissors').animate({ top:0 },cut_speed,'linear',function(){ cut_again() }); });
}//animate는 자스로 대체하려니 setInterval이나 setTimeout 등으로 해야 하는데 여어어엉 귀찮아서..
cut_again();
function cut_calc(pos){
if(pos<cut_line){
cut_rescalc(pos);
return;
}
cut_now=pos;
cut_speed=cut_now/cut_diff;
cut_container.style.height=cut_now+"px";
cuthair.innerHTML=cut_now;
}
function cut_rescalc(pos){
document.getElementById("cuthair_info").style.display="none";
cut_container.style.display="none";
document.getElementById("cut").style.display="none";
cut_res_container.style.display="block";
cut_result1=(100*(1-(cut_now-cut_line)/cut_initial));
cut_result2=(100*(pos/cut_line));
document.getElementById("cut_result1").innerHTML=cut_result1;
document.getElementById("cut_result2").innerHTML=cut_result2;
var cut_stories1=document.getElementsByClassName("cut_story");
var cut_stories2=document.getElementsByClassName("cuts_story");
if(cut_result1===0){ cut_stories1[0].style.display="block"; document.getElementById('cuts_story').style.display="none"; }
else if(cut_result1<90){ cut_stories1[1].style.display="block"; }
else if(cut_result1<95){ cut_stories1[2].style.display="block"; }
else if(cut_result1<98){ cut_stories1[3].style.display="block"; }
else if(cut_result1<=100){ cut_stories1[4].style.display="block"; }
/* story2 (cut_result2, cuts) */
if(cut_result2<90){ cut_stories2[0].style.display="block"; }
else if(cut_result2<95){ cut_stories2[1].style.display="block"; }
else if(cut_result2<98){ cut_stories2[2].style.display="block"; }
else if(cut_result2<=100){ cut_stories2[3].style.display="block"; }
}
$('#cut').click(function(){ cut_calc($('#scissors').position().top ); });//addEventListener...그냥 생각하길 관두고
// 여기까지 코드 입력 //
}
}
$( plugin_haircut );
/* haircut 끝 */
/** 플러그인 RankingSystem***************************
* 랭킹시스템 라이브러리
* 버전 => 1.0.7
* 작성자 : [[사용자:BANIP|BANIP]]
* JSON => RankingSystem = {"name":"RankingSystem","descript":"랭킹시스템 라이브러리","version":"1.0.7","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) {
console.log(rankingDoc)
if (!rankingDoc) return {};
var regexp = /\<includeonly\>(.*)\<\/includeonly\>/;
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 끝 */
/** 플러그인 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 += "<div id=\"numBlock" + i + "\" class=\"numBlock\">" + i + "</div>";
}
numBlocks += "<div id=\"numBlockC\" class=\"numBlockC\">C</div>";
numBlocks += "<div id=\"numBlockX\" class=\"numBlockC\">입력</div>";
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("<tr><td>" + trial + "</td><td>" + disp + "</td><td>" + v + "</td></tr>");
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 끝 */
/** 플러그인 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 끝 */
/** 플러그인 uncytick***************************
* 게임 실행용 플러그인
* 버전 => 1.0.0
* 작성자 : [[사용자:BANIP|BANIP]]
* JSON => uncytick = {"name":"uncytick","descript":"게임 실행용 플러그인","version":"1.0.0","local":true,"creat":"BANIP","state":"사용자:BANIP/틱택토 live/플러그인","executable":true};
*/
function plugin_uncytick(){
if($("[data-name='uncytick']").length >= 1){
// 이부분에 코드 입력 //
jQuery.getScript("https://socket-io-chat.now.sh/socket.io/socket.io.js")
.done(function(){
var Socket = /** @class */ (function () {
function Socket(url, username) {
if (username === void 0) { username = Math.random().toString(); }
this.username = username;
this.socket = io(url);
this.defineJoin();
this.bindSocketListener();
}
Socket.prototype.defineJoin = function () {
this.socket.emit("join", { username: this.username });
};
Socket.prototype.bindSocketListener = function () {
var _this = this;
var socket = this.socket;
socket.on("newuser", function (_a) {
var username = _a.username;
Chat.server(username + "\uB2D8\uC774 \uB4E4\uC5B4\uC654\uC5B4\uC694.");
});
socket.on("passuser", function (_a) {
var username = _a.username;
Chat.server(username + "\uB2D8\uC774 \uB098\uAC14\uC5B4\uC694.");
});
socket.on("getuserlist", function (data) {
var buttonClickListener = function ($li, username, id) {
socket.emit("requestjoin", { targetId: id });
$(".activePull").removeClass();
$li.addClass("activePull");
Chat.server(username + "에게 게임신청을 했어요.");
};
var $lis = data
.map(function (userData) {
if (userData == null)
return;
var username = userData.username, id = userData.id;
var $li = $("<li />")
.text(username)
.data("id", id);
if (username != _this.username) {
var $button = $("<button>").text("게임 신청").addClass("btn-request");
$button.click(function () { return buttonClickListener($li, username, id); });
$li.append($button);
}
return $li;
});
$("#userlist").html($lis);
});
socket.on("servermessage", function (data) {
Chat.server(data.message);
});
socket.on("receivemessage", function (data) {
Chat.client(data.username, data.message);
});
socket.on("gamestart", function (_a) {
var enemyUsername = _a.enemyUsername;
var canStartGame = _this.game == undefined || _this.game.isGameEnd == true;
if (canStartGame) {
_this.game = new Game(socket, _this.username, enemyUsername);
}
else {
Chat.server(_this.game.enemyUsername + "\uACFC\uC758 \uAC8C\uC784\uC774 \uC544\uC9C1 \uB05D\uB098\uC9C0 \uC54A\uC558\uC5B4\uC694.");
}
});
};
return Socket;
}());
var Chat = /** @class */ (function () {
function Chat() {
}
Chat.server = function (message) {
var $li = $("<li></li>").text(message);
$("#messages").append($li);
Chat.moveBottom();
};
Chat.client = function (username, message) {
var $li = $("\n <li>\n <span class='username' /> : <span class='message'>\n </li>");
$li.find(".username").text(username);
$li.find(".message").text(message);
$("#messages").append($li);
Chat.moveBottom();
};
Chat.moveBottom = function () {
$("#messages").scrollTop($("#messages")[0].scrollHeight);
};
return Chat;
}());
var Game = /** @class */ (function () {
function Game(socket, username, ememyusername) {
this.socket = socket;
this.isGameEnd = false;
this.enemyUsername = ememyusername;
Chat.server(ememyusername + "과의 게임이 시작되었어요!");
$(".btn-request").fadeOut();
var bindClick = function ($target, axis) {
var x = axis[0], y = axis[1];
$target.text("H").click(function () {
console.log([x, y]);
socket.emit("draw", {
axis: [x, y]
});
});
};
$("#gamepan").slideDown().find("> div")
.each(function (x) {
$(this).find("> a").each(function (y) { bindClick($(this), [x, y]); });
});
this.bindSocketListener();
}
Game.prototype.bindSocketListener = function () {
var socket = this.socket;
var self = this;
socket.on("renewgamepan", function (_a) {
var gamepan = _a.gamepan;
gamepan.forEach(function (hori, x) {
return hori.forEach(function (cell, y) {
var textType = {
"1": "O",
"0": "H",
"-1": "X",
};
var text = textType[cell];
$("#gamepan").find("div").eq(x).find("a").eq(y)
.data("x", x).data("y", y)
.text(text);
console.log(x, y);
});
});
});
socket.on("gameend", function (_a) {
var state = _a.state;
var hideGamePan = function () { return $("#gamepan").slideUp(); };
var messageType = {
"win": "게임 승리!! 축하드려요!",
"lose": "윽... 져버렸네요...",
"draw": "비겼어요!",
};
var endMessage = messageType[state];
Chat.server(endMessage);
$(".btn-request").fadeIn();
setTimeout(hideGamePan, 3000);
self.isGameEnd = true;
self.removesocketListener();
});
};
Game.prototype.removesocketListener = function () {
$("#gamepan").find("a").off("click");
this.socket.off("gameend").off("renewgamepan");
};
return Game;
}());
var gamehtml = '<div id="gamepan"><div><a></a><a></a><a></a></div><div><a></a><a></a><a></a></div><div><a></a><a></a><a></a></div></div><div class="wrap"><ul id="userlist" class="scrollbox"></ul><ul id="messages" class="scrollbox"></ul><input id="chat" placeholder="메세지를 입력하세요..."/></div>';
$("#gamewindow").html(gamehtml);
var thisSocket = new Socket("https://banip.tk" + "/uncytt",mw.config.values.wgUserName);
$("#chat").keypress(function (e) {
if (e.key === "Enter" && $(this).val() != "") {
thisSocket.socket.emit("sendmessage", { message: $(this).val() });
$(this).val("");
}
});
});
// 여기까지 코드 입력 //
}
}
$( plugin_uncytick );
/* uncytick 끝 */
/** 플러그인 autosave***************************
* 자동저장 시스템을 위한 플러그인
* 버전 => 2.0.2
* 작성자 : [[사용자:Manymaster|Manymaster]]
* JSON => autosave = {"name":"autosave","descript":"자동저장 시스템을 위한 플러그인","version":"2.0.2","local":false,"creat":"Manymaster","state":"틀:자동저장/플러그인","executable":true};
*/
function plugin_autosave(){
/* 작동 가능한 네임스페이스 */
var safeNameSpace = [""];
/* autosave 편집모드가 아닐 경우 플러그인 종료 */
var searchParams = geturlSearch(location);
var isEditMode = searchParams.action === "edit";
var isAutosaveMode = searchParams.autosave === "1";
if (!(isEditMode && isAutosaveMode)) return "";
/* 자동 저장하기에 안전한 네임스페이스가 아닌 경우 플러그인 종료 */
var thisNamespaceNumber = mw.config.get("wgNamespaceNumber");
var nameSpaceIds = mw.config.get("wgNamespaceIds");
var isSafeNameSpace = safeNameSpace
.map(function (namespace) { return nameSpaceIds[namespace]; })
.some(function (nsNumber) { return nsNumber == thisNamespaceNumber; });
if (!(isSafeNameSpace)) return "";
/* 자동 인증된 사용자가 아닌 경우 플러그인 종료 */
var userGroups = mw.config.get('wgUserGroups');
var autocheck = 0;
if (userGroups) {
for (var i = 0; i < userGroups.length; i++) {
if (userGroups[i] === 'autoconfirmed') {
autocheck++;
}
}
}
if (autocheck != 1) return "";
/* 지정된 단락에서 불러오기 */
var savetempDom = $(".game-autosave");
if ($(".game-autosave").length === 0)
throw new Error("autosave => game-autosave를 클래스명으로 가진 돔을 찾을 수 없습니다.");
var savetemp = $(".game-autosave").html();
/* 문제가 되는 문자열 치환 */
savetemp = savetemp.replace(/(<([^>]+)>)/ig, "");
savetemp = savetemp.replace(/\n+/gi, "\n");
savetemp = savetemp.replace("\n", "");
savetemp = savetemp.replace(/</gi, "<");
savetemp = savetemp.replace(/>/gi, ">");
/* 기록, 저장하고 빠져나오기 */
$("#wpTextbox1").val(savetemp);
$("#wpSave").click();
return;
/** 이 플러그인 제작을 도와주신 분들
* Ver 2 제작자: [[사용자:BANIP|BANIP]]
* 원 코드 작성자: [[사용자:*devunt]]
*/
}
$( plugin_autosave );
/* autosave 끝 */
/** 플러그인 msgame***************************
* 스톱워치 게임
* 버전 => 0.942
* 작성자 : [[사용자:Riemann|Riemann]]
* JSON => msgame = {"name":"msgame","descript":"스톱워치 게임","version":"0.942","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).keydown(function() {
if (bl == false) {
bl = true
startF();
} else {
bl = false
stopF();
}
});
$("#msgame-start").click(function() {
bl = true
startF();
});
$("#msgame-stop").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 끝 */
/** 플러그인 uncyslide***************************
* 백괴슬라이드 실행
* 버전 => 1.1.0
* 작성자 : [[사용자:BANIP|BANIP]]
* JSON => uncyslide = {"name":"uncyslide","descript":"백괴슬라이드 실행","version":"1.1.0","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: "반갑습니다. <br>백괴슬라이드입니다.",
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: "<ul><li>아래: 게임시작</li><li>토론: 위</li><li>설명: 오른쪽</li></ul>",
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://game.uncyclopedia.kr/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%)";
console.log(code);
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 "<div class='counter' style='font-size:5vw;'></div><div style='font-size:20vw;'>" + count + "</div>";
}
};
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 + " <br/>시간: " + time + "<ul><li>왼쪽: 메인으로</li><li>오른쪽: 토론으로</li></ul>",
left:"main",
right:"debate",
});
}
}
dispose(game, startMap, {});
}
}
$( plugin_uncyslide );
/* uncyslide 끝 */
/** 플러그인 Slideable***************************
* 슬라이드 플러그인 라이브러리
* 버전 => 1.0.0
* 작성자 : [[사용자:BANIP|BANIP]]
* JSON => Slideable = {"name":"Slideable","descript":"슬라이드 플러그인 라이브러리","version":"1.0.0","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/9/96/Arrow2right_svg.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);
console.log(hideDirection)
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);
console.log(hideDirection)
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];
console.log(slideableItem);
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 끝 */