-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathundercards.user.js
More file actions
576 lines (558 loc) · 21.8 KB
/
undercards.user.js
File metadata and controls
576 lines (558 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
// ==UserScript==
// @name UnderCards script
// @description Minor changes to undercards game
// @require https://raw.githubusercontent.com/feildmaster/SimpleToast/1.4.1/simpletoast.js
// @require https://raw.githubusercontent.com/feildmaster/UnderScript/0.11.4/utilities.js
// @version 0.11.5
// @author feildmaster
// @history 0.12 - Added minimize button to battle log.
// @history 0.11.5 - The following now work again: end turn "fixes", deck auto-sort, deck preview.
// @history 0.11.4 - Fix issue where script was not loading
// @history 0.11.3 - Fix mines (and other potential cards) staying around on the baord for too long
// @history 0.11.2 - End turn once per turn, and add a 3 second delay. Fix middle click
// @history 0.11.1 - Peaking at cards now adds them to the battle log, join queue button stays disabled when the server is restarting
// @history 0.11 - Fix transparent deck preview, automatically sort deck
// @history 0.10.3 - Fix refreshing page, Log artifact activations
// @history 0.10.2 - Bump version so broken updates work (hopefully)
// @history 0.10.1 - Moved file to proper extension (makes fresh installs easier)
// @history 0.10 - Added deck card preview
// @history 0.9.2 - Fixed enemy names *again* (copy/pasting is bad)
// @history 0.9.1 - Spectate result music is now disabled if you disable music playing.
// @history 0.9.0 - Added detailed history log, log is top-bottom now, battle end is now a toast
// @history 0.8.5 - Added some game debug
// @history 0.8.4 - Removed "remember deck" feature (upstream), fixed event log
// @history 0.8.3 - Script works now
// @history 0.8.2 - Fix the queue disconnecting.
// @history 0.8.1 - Rework loading jQuery performance
// @history 0.8 - Better performance and reliability. Disable the join queue buttons until they are ready
// @history 0.7 - updated to new restrictions, thanks cloudflare -_-
// @history 0.6 - some upgrades to the battle log, fixed url
// @history 0.5.4 - Don't scroll the battle log with the page (possibly make this configurable later)
// @history 0.5.3 - Remove the chat stuff, the new chat is better.
// @history 0.5.2 - do the same for the chat window
// @history 0.5.1 - don't cover the battle screen
// @history 0.5 - remember chat messages on page-change, added a battle log, lots of code changes
// @history 0.4 - Remember "event deck" too!, also fixed bugs.
// @history 0.3 - Lowered "game found" volume
// @history 0.2 - Added EndTurn hotkey (space, middle click), focus chat (enter)
// @history 0.1 - Made deck selection smart
// @match https://undercards.net/*
// @website https://github.com/feildmaster/UnderScript
// @supportURL https://github.com/feildmaster/UnderScript/issues
// @downloadURL https://raw.githubusercontent.com/feildmaster/UnderScript/master/undercards.user.js
// @namespace https://feildmaster.com/
// @grant none
// ==/UserScript==
// === Variables start
const hotkeys = [];
// === Variables end
eventManager.on("getWaitingQueue", function lowerVolume() {
// Lower the volume, the music changing is enough as is
audioQueue.volume = 0.3;
});
eventManager.on("PlayingGame", function bindHotkeys() {
// Binds to Space, Middle Click
hotkeys.push(new Hotkey("End turn").bindKey(32).bindClick(2).run((e) => {
if (!$(e.target).is("#endTurnBtn") && userTurn === userId) endTurn();
}));
});
eventManager.on('PlayingGame', function fixEndTurn() {
const oEndTurn = endTurn;
let endedTurn = false;
endTurn = function restrictedEndTurn() {
if (endedTurn || $('#endTurnBtn').prop('disabled')) return;
endedTurn = true;
oEndTurn();
};
eventManager.on('getTurnStart', function turnStarted() {
if (userTurn !== userId) return;
endedTurn = false;
if (turn > 3) {
$('#endTurnBtn').prop('disabled', true);
setTimeout(() => {
$('#endTurnBtn').prop('disabled', false);
}, 3000);
}
});
});
eventManager.on("GameStart", function battleLogger() {
const ignoreEvents = Object.keys({
getConnectedFirst: '',
refreshTimer: 'Never need to know about this one',
getPlayableCards: 'On turn start, selects cards player can play',
getTurn: 'Turn update',
getCardDrawed: 'Add card to your hand',
updateSpell: '',
updateMonster: 'monster on board updated',
getFakeDeath: 'Card "died" and respawns 1 second later',
getMonsterTemp: "You're about to play a monster",
getSpellTemp: "You're about to play a spell",
getTempCancel: 'Temp card cancelled',
getShowMulligan: 'Switching out hands, ignore it',
getHideMulligan: 'Hide the mulligan, gets called twice',
getUpdateHand: 'Updates full hand',
getError: 'Takes you to "home" on errors, can be turned into a toast',
getGameError: 'Takes you to "play" on game errors, can be turned into a toast',
});
let turn = 0, currentTurn = 0, players = {}, monsters = {}, lastEffect, other = {}, finished = false;
const make = {
player: function makePlayer(player, title = false) {
const c = $('<span>');
c.append(player.username);
c.addClass(player.class);
if (!title) {
c.css('text-decoration', 'underline');
// show lives, show health, show gold, show hand, possibly deck size as well
const data = `${player.hp} hp, ${player.gold} gold`;
c.hover(hover.show(data, '2px solid white'));
}
return c;
},
card: function makeCard(card) {
const c = $('<span>');
c.append(card.name);
c.css('text-decoration', 'underline');
let data = `<table class="cardBoard ${card.paralyzed ? 'paralyzed' : ''}">`;
data += `<tr><td class="cardName resize ${card.classe || card.class}" colspan="3">${card.name}`;
if (card.shiny) {
// TODO: rainbow
}
// TODO: skins
data += `</td><td class="cardCost">${card.cost}</td></tr>`;
data += `<tr><td id="cardImage" colspan="4">`;
const status = fn.cardStatus(card);
if (status.length) {
// add status images
status.forEach((s, i) => {
data += `<img class="infoPowers" style="z-index:20;right:${4 + i * 20}px;" src="images/powers/${s}.png"/>`;
});
}
data += `<img src="images/cards/${card.image}.png"/></td></tr>`;
data += `<tr><td class="cardDesc" colspan="4">${card.desc || ''}`
if (card.silence) {
data += '<img class="silenced" title="Silence" src="images/silence.png">';
}
data += '</td></tr>';
if (!card.typeCard) {
data += `<tr><td id="cardATQ">${card.attack}</td><td id="cardRarity" colspan="2"><img src="images/rarity/${card.rarity}.png" /></td><td id="cardHP" class="${card.hp!==card.maxHp ? "damaged" : ""}">${card.hp}</td></tr>`;
} else {
data += `<tr><td id="cardRarity" colspan="4"><img src="images/rarity/${card.rarity}.png" /></td></tr>`;
}
data += `</table>`;
c.hover(hover.show(data));
return c;
},
};
eventManager.on('GameEvent', function logEvent(data) {
if (finished) { // Sometimes we get events after the battle is over
fn.debug(`Extra action: ${data.action}`, 'debugging.events.extra');
return;
}
debug(data.action, 'debugging.events.name');
const emitted = eventManager.emit(data.action, data).ran;
if (!emitted) {
fn.debug(`Unknown action: ${data.action}`);
}
});
eventManager.on('getAllGameInfos getGameStarted getReconnection', function initBattle(data) {
debug(data, 'debugging.raw.game');
let you, enemy;
// Battle logging happens after the game runs
if (this.event === 'getGameStarted') {
you = {
id: data.yourId,
username: data.yourUsername,
hp: 30, // This is wrong with artifacts? Maybe?
gold: 2, // This is wrong with artifacts? Maybe?
};
enemy = {
id: data.enemyId,
username: data.enemyUsername,
hp: 30, // This is wrong with artifacts? Maybe?
gold: 2, // This is wrong with artifacts? Maybe?
};
} else {
you = JSON.parse(data.you);
enemy = JSON.parse(data.enemy);
// Set gold
const gold = JSON.parse(data.golds);
you.gold = gold[you.id];
enemy.gold = gold[enemy.id];
// Set lives
const lives = JSON.parse(data.lives);
you.lives = lives[you.id];
enemy.lives = lives[enemy.id];
// populate monsters
JSON.parse(data.board).forEach(function (card) {
if (card === null) return;
// id, attack, hp, maxHp, originalattack, originalHp, typeCard, name, image, cost, originalCost, rarity, shiny, quantity
card.desc = getDescription(card);
monsters[card.id] = card;
});
}
you.level = data.yourLevel;
you.class = data.yourClass;
you.rank = data.yourRank;
enemy.level = data.enemyLevel;
enemy.class = data.enemyClass;
enemy.rank = data.enemyRank;
// yourArtifacts, yourAvatar {id, image, name, rarity, ucpCost}, division, oldDivision, profileSkin {id, name, image, ucpCost}
debug({you, enemy}, 'debugging.game');
turn = data.turn || 0;
players[you.id] = you;
players[enemy.id] = enemy;
// Test changing ID's at endTurn instead of startTurn
other[you.id] = enemy.id;
other[enemy.id] = you.id;
// Initialize the log
log.init();
$("div#history div.handle").html('').append(`[${data.gameType}] `, make.player(you), ' vs ', make.player(enemy));
log.add(`Turn ${turn}`);
if (data.userTurn) {
currentTurn = data.userTurn;
log.add(make.player(players[data.userTurn]), "'s turn");
}
});
eventManager.on('getFight getFightPlayer', function fight(data) {
const target = this.event === 'getFightPlayer' ? make.player(players[data.defendPlayer]) : make.card(monsters[data.defendMonster]);
log.add(make.card(monsters[data.attackMonster]), ' attacked ', target);
});
eventManager.on('getUpdatePlayerHp', function updateHP(data) {
debug(data, 'debugging.raw.updateHP');
const oHp = players[data.playerId].hp;
const hp = data.isDamage ? oHp - data.hp : data.hp - oHp;
players[data.playerId].hp = data.hp;
if (oHp !== data.hp) { // If the player isn't at 0 hp already
log.add(make.player(players[data.playerId]), ` ${data.isDamage ? "lost" : "gained"} ${hp} hp`);
}
if (data.hp === 0 && players[data.playerId].lives > 1 && !players[data.playerId].hasOwnProperty("lostLife")) { // If they have extra lives, and they didn't lose a life already
log.add(make.player(players[data.playerId]), ' lost a life');
players[data.playerId].lostLife = true;
}
});
eventManager.on('getDoingEffect', function doEffect(data) {
debug(data, 'debugging.raw.effect');
// affecteds: [ids]; monsters affected
// playerAffected1: id; player affected
// playerAffected2: id; player affected
// TODO: Figure out how to do this better
if (lastEffect === 'm' + data.monsterId) return;
lastEffect = 'm' + data.monsterId;
log.add(make.card(monsters[data.monsterId]), "'s effect activated");
});
eventManager.on('getArtifactDoingEffect', function doEffect(data) {
debug(data, 'debugging.raw.effectArtifact');
if (lastEffect === 'a' + data.playerId) return;
lastEffect = 'a' + data.playerId;
log.add(make.player(players[data.playerId]), "'s artifact activated");
});
eventManager.on('getSoulDoingEffect', function soulEffect(data) {
debug(data, 'debugging.raw.effectSoul');
if (lastEffect === 's' + data.playerId) return;
lastEffect = 's' + data.playerId;
log.add(make.player(players[data.playerId]), "'s soul activated");
// affecteds
// playerAffected1
// playerAffected2
});
eventManager.on('getTurnStart', function turnStart(data) {
debug(data, 'debugging.raw.turnStart');
lastEffect = 0;
if (data.numTurn !== turn) {
log.add(`Turn ${data.numTurn}`);
}
currentTurn = data.idPlayer; // It would (kindof) help to actually update who's turn it is
turn = data.numTurn;
log.add(make.player(players[currentTurn]), "'s turn");
});
eventManager.on('getTurnEnd', function turnEnd(data) {
debug(data, 'debugging.raw.turnEnd');
// Lets switch the turn NOW, rather than later, the purpose of this is currently unknown... It just sounded like a good idea, also delete the "lostLife" flag...
if (time <= 0) {
log.add(make.player(players[currentTurn]), ' timed out');
}
delete players[currentTurn].lostLife;
currentTurn = other[data.idPlayer];
delete players[currentTurn].lostLife;
lastEffect = 0;
});
eventManager.on('getUpdateBoard', function updateGame(data) {
debug(data, 'debugging.raw.boardUpdate');
const oldMonsters = monsters;
monsters = {};
// TOOD: stuff....
JSON.parse(data.board).forEach(function (card) {
if (card === null) return;
card.desc = getDescription(card);
monsters[card.id] = card;
});
});
eventManager.on('getMonsterDestroyed', function monsterKilled(data) {
debug(data, 'debugging.raw.kill');
// monsterId: #
log.add(make.card(monsters[data.monsterId]), ' was killed');
delete monsters[data.monsterId];
});
eventManager.on('getCardBoard', function playCard(data) { // Adds card to X, Y (0(enemy), 1(you))
debug(data, 'debugging.raw.boardAdd');
const card = JSON.parse(data.card);
card.desc = getDescription(card);
monsters[card.id] = card;
log.add(make.player(players[data.idPlayer]), ' played ', make.card(card));
});
eventManager.on('getSpellPlayed', function useSpell(data) {
debug(data, 'debugging.raw.spell');
// immediately calls "getDoingEffect" and "getUpdateBoard"
const card = JSON.parse(data.card);
card.desc = getDescription(card);
monsters[card.id] = card;
log.add(make.player(players[data.idPlayer]), ' used ', make.card(card));
});
eventManager.on('getShowCard', function showCard(data) {
const card = JSON.parse(data.card);
card.desc = getDescription(card);
log.add(make.player(players[data.idPlayer]), ' exposed ', make.card(card));
});
eventManager.on('getCardDestroyedHandFull', function destroyCard(data) {
debug(data, 'debugging.raw.fullHand');
const card = JSON.parse(data.card);
card.desc = getDescription(card);
debug(data.card);
// This event gets called for *all* discards. Have to do smarter logic here (not just currentTurn!)
log.add(make.player(players[currentTurn]), ' discarded ', make.card(card));
});
eventManager.on('getPlayersStats', function updatePlayer(data) { // TODO: When does this get called?
debug(data, 'debugging.raw.stats');
let key, temp = JSON.parse(data.handsSize);
for (key in temp) {
// TODO: hand size monitoring
//players[key].hand
}
// TODO: deck monitoring (decksSize)
temp = JSON.parse(data.golds);
for (key in temp) {
players[key].gold = temp[key];
}
temp = JSON.parse(data.lives);
for (key in temp) {
players[key].lives = temp[key];
}
// data.artifcats
// data.turn
});
eventManager.on('getVictory getDefeat', function gameEnd(data) {
debug(data, 'debugging.raw.end');
finished = true;
if (data.disconnected) {
log.add(make.player(players[opponentId]), " left the game");
}
const you = make.player(players[userId]);
const enemy = make.player(players[opponentId]);
if (this.event === 'getDefeat') {
log.add(enemy, ' beat ', you);
} else {
log.add(you, ' beat ', enemy);
}
});
eventManager.on('getResult', function endSpectating(data) {
debug(data, 'debugging.raw.end');
finished = true;
if (data.cause === "Surrender") {
log.add(`${data.looser} surrendered.`);
} else if (data.cause === "Disconnection") {
log.add(`${data.looser} disconnected.`);
}
if (typeof music !== 'undefined') {
music.addEventListener('playing', function () {
if (localStorage.getItem('gameMusicDisabled')) {
music.pause();
}
});
}
// TODO: colorize
log.add(`${data.winner} beat ${data.looser}`);
const toast = {
title: 'Game Finished',
text: 'Return Home',
buttons: {
className: 'skiptranslate',
text: '🏠',
onclick: () => {
document.location.href = "/";
},
},
};
if (!localStorage.getItem('setting.disableResultToast') && fn.toast(toast)) {
BootstrapDialog.closeAll();
}
});
eventManager.on(ignoreEvents.join(' '), function ignore(data) {
debug(data, 'debugging.raw.ignore');
debug(data, `debugging.raw.ignore.${this.event}`);
});
eventManager.on('getTurnEnd', function hideSpells() {
// Fixes a bug with "mines" and any other potential cards that don't get cleared correctly.
$('#board .spellPlayed').remove();
})
});
// === Play hooks
onPage("Play", function () {
// TODO: Better "game found" support
debug("On play page");
let queues, disable = true;
let restarting = false;
eventManager.on("jQuery", function onPlay() {
if (disable) {
queues = $("button.btn.btn-primary");
queues.prop("disabled", true);
restarting = $('p.infoMessage:contains("The server will restart in")').length === 1;
if (restarting) {
queues.hover(hover.show('Joining is disabled due to server restart.'));
}
}
});
(function hook() {
if (typeof socketQueue === "undefined") {
debug("Timeout hook");
return setTimeout(hook);
}
socket = socketQueue;
const oOpen = socketQueue.onopen;
socketQueue.onopen = function onOpenScript(event) {
disable = false;
oOpen(event);
if (queues && !restarting) queues.prop("disabled", false);
};
const oHandler = socketQueue.onmessage;
socketQueue.onmessage = function onMessageScript(event) {
const data = JSON.parse(event.data);
oHandler(event);
eventManager.emit(data.action, data);
};
})();
});
// === Game hooks
onPage("Game", function () {
debug("Playing Game");
eventManager.emit("GameStart");
eventManager.emit("PlayingGame");
(function hook() {
if (typeof socket === 'undefined') {
debug("Timeout hook");
return setTimeout(hook);
}
const oHandler = socket.onmessage;
socket.onmessage = function onMessageScript(event) {
const data = JSON.parse(event.data);
//eventManager.emit('PreGameEvent', data, true);
oHandler(event);
eventManager.emit('GameEvent', data);
};
})();
});
// Deck hook
onPage('Decks', function () {
debug('Deck editor');
function hoverCard(element) {
const id = element.attr('id');
const shiny = element.hasClass('shiny') ? '.shiny' : '';
const card = $(`table#${id}${shiny}:lt(1)`).clone();
if (card.length !== 1) return;
card.find('#quantity').remove();
if (card.css('opacity') !== '1') card.css('opacity', 1);
loadCard(card);
return hover.show(card);
}
// Initial load
eventManager.on('jQuery', () => {
$('li.list-group-item').each(function (index) {
const element = $(this);
element.hover(hoverCard(element));
});
$(document).ajaxSuccess((event, xhr, settings) => {
const data = JSON.parse(settings.data);
if (data.action === 'removeCard') { // Card was removed, hide element
hover.hide();
} else if (data.action === 'addCard') { // Card was added
const element = $(`#deckCards${data.classe} li:last`);
element.hover(hoverCard(element, true));
const list = $(`#deckCards${data.classe}`);
list.append(list.children('li').detach().sort(function (a, b) {
const card1 = $(`table#${$(a).attr('id')}`);
const card2 = $(`table#${$(b).attr('id')}`);
const card1cost = parseInt(card1.find('.cardCost').html(), 10);
const card2cost = parseInt(card2.find('.cardCost').html(), 10);
if (card1cost === card2cost) {
const card1name = card1.find('.cardName').html();
const card2name = card2.find('.cardName').html();
if (card1name == card2name) return 0;
return card1name > card2name ? 1 : -1;
}
return card1cost > card2cost ? 1 : -1;
}));
}
});
});
});
// Spectate hooks
onPage("gameSpectate", function () {
debug("Spectating Game");
eventManager.emit("GameStart");
(function hook() {
if (typeof socket === "undefined") {
debug("Timeout hook");
return setTimeout(hook);
}
const oHandler = socket.onmessage;
socket.onmessage = function onMessageScript(event) {
const data = JSON.parse(event.data);
//eventManager.emit('PreGameEvent', data, true);
oHandler(event);
eventManager.emit('GameEvent', data);
};
})();
});
// === Always do the following - if jquery is loaded
eventManager.on("jQuery", function always() {
// Bind hotkey listeners
$(document).on("mouseup.script", function (event) {
if (false) return; // TODO: Check for clicking in chat
hotkeys.forEach(function (v) {
if (v.clickbound(event.which)) {
v.run(event);
}
});
});
$(document).on("keyup.script", function (event) {
if ($(event.target).is("input")) return; // We don't want to listen while typing in chat (maybe listen for F-keys?)
hotkeys.forEach(function (v) {
if (v.keybound(event.which)) {
v.run(event);
}
});
});
/* This legacy code doesn't work
$(window).unload(function() {
// Store chat text (if any)
var val = $("div.chat-public input.chat-text").val();
if (!val) return;
localStorage.oldChat = val;
});
if (localStorage.oldChat) {
$("div.chat-public input.chat-text").val(localStorage.oldChat);
delete localStorage.oldChat;
}
// */
});
// Attempt to detect jQuery
let tries = 20;
(function jSetup() {
if (typeof jQuery === "undefined") {
if (tries-- <= 0) { // jQuery is probably not going to load at this point...
return;
}
setTimeout(jSetup, 1);
return;
}
eventManager.emit("jQuery");
})();