-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent.js
304 lines (259 loc) · 10.6 KB
/
content.js
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
class TopCutCalculator {
constructor() {
this.i18n = new I18n();
this.defaultTopCutRules = [
{ maxPlayers: 8, rounds: 3, topCut: 0 },
{ maxPlayers: 16, rounds: 4, topCut: 4 },
{ maxPlayers: 32, rounds: 6, topCut: 8 },
{ maxPlayers: 64, rounds: 7, topCut: 8 },
{ maxPlayers: 128, rounds: 6, topCut: 16 },
{ maxPlayers: 256, rounds: 7, topCut: 16 },
{ maxPlayers: 512, rounds: 8, topCut: 16 },
{ maxPlayers: 1024, rounds: 9, topCut: 32 },
{ maxPlayers: 2048, rounds: 10, topCut: 32 },
{ maxPlayers: Infinity, rounds: 10, topCut: 64 }
];
this.createElements();
this.attachEventListeners();
}
createElements() {
// Criar FAB
const fab = document.createElement('button');
fab.id = 'topcut-fab';
fab.innerHTML = '📊';
document.body.appendChild(fab);
// Criar Modal com novo campo de Top Cut
const modal = document.createElement('div');
modal.id = 'topcut-modal';
modal.innerHTML = `
<div class="modal-header">
${this.i18n.t('title')}
<button id="settings-button" class="settings-icon">⚙️</button>
</div>
<div class="input-group">
<label>${this.i18n.t('players')}</label>
<input type="number" id="players-input" placeholder="Auto-detect">
</div>
<div class="input-group">
<label>${this.i18n.t('rounds')}</label>
<input type="number" id="rounds-input" placeholder="Auto-detect">
</div>
<div class="input-group">
<label>${this.i18n.t('topCut')}</label>
<select id="topcut-input">
<option value="auto">Auto</option>
<option value="0">${this.i18n.t('noTopCut')}</option>
<option value="4">Top 4</option>
<option value="8">Top 8</option>
<option value="16">Top 16</option>
<option value="32">Top 32</option>
<option value="64">Top 64</option>
<option value="128">Top 128</option>
</select>
</div>
<button class="button" id="calculate-button">${this.i18n.t('calculate')}</button>
<div class="results" id="results"></div>
`;
document.body.appendChild(modal);
}
attachEventListeners() {
const fab = document.getElementById('topcut-fab');
const modal = document.getElementById('topcut-modal');
const calculateButton = document.getElementById('calculate-button');
const playersInput = document.getElementById('players-input');
fab.addEventListener('click', () => {
const isVisible = modal.style.display === 'block';
modal.style.display = isVisible ? 'none' : 'block';
if (!isVisible) {
this.autoDetectValues();
}
});
calculateButton.addEventListener('click', () => {
this.calculateTopCut();
});
// Atualizar top cut automático quando número de jogadores mudar
playersInput.addEventListener('change', () => {
const topCutSelect = document.getElementById('topcut-input');
if (topCutSelect.value === 'auto') {
const players = parseInt(playersInput.value);
const suggestedTopCut = this.determineTopCutSize(players);
this.updateTopCutSuggestion(suggestedTopCut);
}
});
// Adicionar listener para o botão de configurações
const settingsButton = document.getElementById('settings-button');
settingsButton.addEventListener('click', () => {
// Abre a página de opções da extensão
chrome.runtime.sendMessage({ action: 'openOptions' });
});
}
updateTopCutSuggestion(topCut) {
const results = document.getElementById('results');
if (topCut === 0) {
results.innerHTML = 'Sugestão: Sem Top Cut';
} else {
results.innerHTML = `Sugestão: Top ${topCut}`;
}
}
determineTopCutSize(players) {
const rule = this.defaultTopCutRules.find(r => players <= r.maxPlayers);
return rule ? rule.topCut : 64;
}
calculateTopCut() {
const playersCount = parseInt(document.getElementById('players-input').value);
const roundsCount = parseInt(document.getElementById('rounds-input').value);
const topCutSelect = document.getElementById('topcut-input');
if (!playersCount || !roundsCount) {
document.getElementById('results').innerHTML =
'<span style="color: rgba(255, 255, 255, 0.87)">Por favor, insira todos os valores.</span>';
return;
}
let topCutSize = topCutSelect.value === 'auto'
? this.determineTopCutSize(playersCount)
: parseInt(topCutSelect.value);
const results = this.calculatePossibleRecords(roundsCount, topCutSize);
// Calcula a porcentagem do top cut
const topCutPercentage = topCutSize > 0
? Math.round((topCutSize/playersCount) * 100)
: 0;
document.getElementById('results').innerHTML = `
<div style="color: rgba(255, 255, 255, 0.87)">
<div style="margin-bottom: 2px">${this.i18n.t('topCut')}: ${topCutSize === 0 ? this.i18n.t('noTopCut') : `Top ${topCutSize} (${topCutPercentage}%)`}</div>
<div style="white-space: nowrap">${this.i18n.t('records')}: ${results}</div>
</div>
`;
}
async autoDetectValues() {
const url = window.location.href;
const tournamentId = url.match(/tournament\/(.*?)(\/|$)/)?.[1];
if (!tournamentId) return;
try {
// Primeiro detectar número de jogadores
const standingsResponse = await fetch(`https://play.limitlesstcg.com/tournament/${tournamentId}/standings`);
const standingsText = await standingsResponse.text();
const playersCount = this.extractPlayersCount(standingsText);
if (playersCount) {
// Atualizar número de jogadores
document.getElementById('players-input').value = playersCount;
// Encontrar a regra correspondente baseada no número de jogadores
const rule = this.defaultTopCutRules.find(r => playersCount <= r.maxPlayers);
if (rule) {
// Atualizar número de rodadas
document.getElementById('rounds-input').value = rule.rounds;
// Atualizar top cut
document.getElementById('topcut-input').value = rule.topCut;
// Calcular automaticamente
this.calculateTopCut();
}
}
} catch (error) {
console.error('Erro ao detectar valores:', error);
document.getElementById('results').innerHTML =
'<span style="color: rgba(255, 255, 255, 0.87)">Erro ao detectar valores automaticamente. Por favor, insira manualmente.</span>';
}
}
extractRoundsCount(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// Método 1: Procurar na div de informações do torneio
const tournamentInfo = doc.querySelector('.tournament-info');
if (tournamentInfo) {
const infoText = tournamentInfo.textContent;
const roundsMatch = infoText.match(/Number of Rounds:\s*(\d+)/i);
if (roundsMatch && roundsMatch[1]) {
return parseInt(roundsMatch[1]);
}
}
// Método 2: Procurar em elementos específicos que contenham "Number of Rounds"
const elements = doc.querySelectorAll('div, p, span, td');
for (const element of elements) {
if (element.textContent.includes('Number of Rounds')) {
const roundsMatch = element.textContent.match(/Number of Rounds:\s*(\d+)/i);
if (roundsMatch && roundsMatch[1]) {
return parseInt(roundsMatch[1]);
}
}
}
// Método 3: Procurar na tabela de informações
const tableRows = doc.querySelectorAll('tr');
for (const row of tableRows) {
const text = row.textContent;
if (text.includes('Number of Rounds')) {
const roundsMatch = text.match(/(\d+)/);
if (roundsMatch && roundsMatch[1]) {
return parseInt(roundsMatch[1]);
}
}
}
// Método 4: Procurar pelo maior número de rodada nos pairings
const roundElements = doc.querySelectorAll('[data-round]');
if (roundElements.length > 0) {
const rounds = Array.from(roundElements)
.map(el => parseInt(el.getAttribute('data-round')))
.filter(num => !isNaN(num));
if (rounds.length > 0) {
return Math.max(...rounds);
}
}
console.log('HTML da página:', html); // Debug
return null;
}
extractPlayersCount(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// Pegar todas as linhas da tabela, excluindo o cabeçalho
const rows = doc.querySelectorAll('tbody tr');
// Retorna o número total de linhas (jogadores) menos 1
return rows.length > 0 ? rows.length - 1 : 0;
}
calculatePossibleRecords(rounds, topCutSize) {
const possibleRecords = [];
const totalPlayers = parseInt(document.getElementById('players-input').value);
let remainingSpots = topCutSize;
// Calcula as possibilidades de vitórias necessárias (do melhor ao pior record)
for (let wins = rounds; wins >= 0; wins--) {
const losses = rounds - wins;
// Calcula quantos jogadores teoricamente podem alcançar esse record
const playersWithThisRecord = Math.round(
totalPlayers *
this.binomialCoefficient(rounds, wins) *
Math.pow(0.5, rounds)
);
if (remainingSpots > 0) {
// Calcula quantos jogadores com esse record passarão
const playersAdvancing = Math.min(remainingSpots, playersWithThisRecord);
// Calcula a porcentagem de jogadores que passam com esse record
const percentageAdvancing = Math.round((playersAdvancing / playersWithThisRecord) * 100);
if (percentageAdvancing > 0) {
possibleRecords.push({
record: `${wins}-${losses}`,
percentage: percentageAdvancing
});
remainingSpots -= playersAdvancing;
}
}
}
// Retorna apenas os records que têm chance real de classificação
return possibleRecords
.map(r => `${r.record} (${r.percentage}%)`)
.join(' | ');
}
calculatePossiblePlayers(rounds, wins) {
// Usando o coeficiente binomial para calcular possíveis combinações
return this.binomialCoefficient(rounds, wins);
}
binomialCoefficient(n, k) {
let result = 1;
for (let i = 1; i <= k; i++) {
result *= (n + 1 - i);
result /= i;
}
return result;
}
determineRoundsCount(players) {
const rule = this.defaultTopCutRules.find(r => players <= r.maxPlayers);
return rule ? rule.rounds : 10;
}
}
// Inicializar a calculadora
new TopCutCalculator();