Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
518 lines (448 loc) · 18.9 KB
/
Copy pathscript.js
File metadata and controls
518 lines (448 loc) · 18.9 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
const LS = {
ITEMS: 'co_items',
RARITIES: 'co_rarities',
WEIGHTS: 'co_weights',
HISTORY: 'co_history',
PRESETS: 'co_presets',
PROFILE: 'co_profile',
THEME: 'co_theme',
ACCENT: 'co_accent',
};
const RARITIES = [
{ id: 'consumer', color: '#b0b0b0', weight: 3 },
{ id: 'industrial', color: '#5b98cf', weight: 4 },
{ id: 'milspec', color: '#4b69cf', weight: 5 },
{ id: 'restricted', color: '#8847cf', weight: 4 },
{ id: 'classified', color: '#d32ce6', weight: 3 },
{ id: 'covert', color: '#eb4b4b', weight: 2 },
{ id: 'gold', color: '#ffd700', weight: 1 },
];
let items = [];
let rarities = [];
let weights = [];
let history = [];
let presets = [];
let isSpinning = false;
const $ = id => document.getElementById(id);
const bulkInput = $('bulkInput');
const addBtn = $('addBtn');
const itemList = $('itemList');
const itemsEmpty = $('itemsEmpty');
const itemCount = $('itemCount');
const clearItemsBtn = $('clearItemsBtn');
const spinBtn = $('spinBtn');
const spinLabel = spinBtn.querySelector('.spin-label');
const track = $('track');
const trackWrap = $('trackWrap');
const resultModal = $('resultModal');
const resultItem = $('resultItem');
const resultWho = $('resultWho');
const resultCloseBtn = $('resultCloseBtn');
const historyList = $('historyList');
const historyEmpty = $('historyEmpty');
const historyCount = $('historyCount');
const clearHistoryBtn = $('clearHistoryBtn');
const presetNameInput = $('presetNameInput');
const presetSaveBtn = $('presetSaveBtn');
const presetList = $('presetList');
const settingsBtn = $('settingsBtn');
const settingsModal = $('settingsModal');
const settingsCloseBtn = $('settingsCloseBtn');
const settingsProfileInput = $('settingsProfileInput');
const themeDark = $('themeDark');
const themeLight = $('themeLight');
const colorPicker = $('colorPicker');
/* ─── Storage ─── */
function loadAll() {
try {
const d = localStorage.getItem(LS.ITEMS);
if (d) { const p = JSON.parse(d); if (Array.isArray(p)) items = p; }
const r = localStorage.getItem(LS.RARITIES);
if (r) { const p = JSON.parse(r); if (Array.isArray(p)) rarities = p; }
const w = localStorage.getItem(LS.WEIGHTS);
if (w) { const p = JSON.parse(w); if (Array.isArray(p)) weights = p; }
const h = localStorage.getItem(LS.HISTORY);
if (h) { const p = JSON.parse(h); if (Array.isArray(p)) history = p; }
const pr = localStorage.getItem(LS.PRESETS);
if (pr) { const p = JSON.parse(pr); if (Array.isArray(p)) presets = p; }
const pf = localStorage.getItem(LS.PROFILE);
if (pf) { settingsProfileInput.value = pf; }
const th = localStorage.getItem(LS.THEME);
if (th) document.documentElement.dataset.theme = th;
const ac = localStorage.getItem(LS.ACCENT);
if (ac) applyAccent(ac);
} catch {}
if (weights.length !== items.length) weights = items.map(() => 10);
if (rarities.length !== items.length) rarities = items.map(() => 'consumer');
recomputeAllRarities();
}
function saveAll() {
localStorage.setItem(LS.ITEMS, JSON.stringify(items));
localStorage.setItem(LS.RARITIES, JSON.stringify(rarities));
localStorage.setItem(LS.WEIGHTS, JSON.stringify(weights));
}
function saveHistory() { localStorage.setItem(LS.HISTORY, JSON.stringify(history)); }
function savePresets() { localStorage.setItem(LS.PRESETS, JSON.stringify(presets)); }
function saveProfile() { localStorage.setItem(LS.PROFILE, settingsProfileInput.value.trim()); }
function saveTheme(t) { localStorage.setItem(LS.THEME, t); }
function saveAccent(c) { localStorage.setItem(LS.ACCENT, c); }
/* ─── Theme ─── */
function setTheme(theme) {
document.documentElement.dataset.theme = theme;
saveTheme(theme);
themeDark.classList.toggle('active', theme === 'dark');
themeLight.classList.toggle('active', theme === 'light');
}
themeDark.addEventListener('click', () => setTheme('dark'));
themeLight.addEventListener('click', () => setTheme('light'));
/* ─── Accent Color ─── */
function applyAccent(color) {
document.documentElement.style.setProperty('--accent', color);
const r = parseInt(color.slice(1,3), 16);
const g = parseInt(color.slice(3,5), 16);
const b = parseInt(color.slice(5,7), 16);
const darker = `rgb(${Math.round(r*0.75)},${Math.round(g*0.75)},${Math.round(b*0.75)})`;
document.documentElement.style.setProperty('--accent2', darker);
document.documentElement.style.setProperty('--accent-glow', `rgba(${r},${g},${b},0.2)`);
saveAccent(color);
}
colorPicker.addEventListener('click', e => {
const swatch = e.target.closest('.color-swatch');
if (!swatch) return;
colorPicker.querySelectorAll('.color-swatch').forEach(s => s.classList.remove('active'));
swatch.classList.add('active');
applyAccent(swatch.dataset.color);
});
/* ─── Settings Modal ─── */
settingsBtn.addEventListener('click', () => settingsModal.classList.remove('hidden'));
settingsCloseBtn.addEventListener('click', () => settingsModal.classList.add('hidden'));
settingsModal.addEventListener('click', e => { if (e.target === settingsModal) settingsModal.classList.add('hidden'); });
settingsProfileInput.addEventListener('input', saveProfile);
/* ─── Rarity ─── */
function pickRarity() {
const total = RARITIES.reduce((s, r) => s + r.weight, 0);
let r = Math.random() * total;
for (const ra of RARITIES) { r -= ra.weight; if (r <= 0) return ra; }
return RARITIES[RARITIES.length - 1];
}
function rarColor(id) { const r = RARITIES.find(x => x.id === id); return r ? r.color : '#888'; }
function rarClass(id) { return 't-' + id; }
function recomputeAllRarities() {
const maxW = Math.max(...weights, 0);
if (maxW === 0) { rarities = weights.map(() => 'consumer'); return; }
rarities = weights.map(w => {
const ratio = w / maxW;
if (ratio >= 0.7) return 'consumer';
if (ratio >= 0.4) return 'industrial';
if (ratio >= 0.2) return 'milspec';
if (ratio >= 0.1) return 'restricted';
if (ratio >= 0.05) return 'classified';
if (ratio >= 0.02) return 'covert';
return 'gold';
});
}
/* ─── Parse ─── */
function parseBulk(text) {
if (!text.trim()) return [];
return text.split(/[\n,;|]+/)
.map(s => s.replace(/['"“”‘’]/g, '').trim())
.filter(Boolean);
}
/* ─── Render Items ─── */
function renderItems() {
itemList.innerHTML = '';
if (items.length === 0) {
itemsEmpty.style.display = 'block';
itemCount.textContent = '0';
spinBtn.disabled = true;
return;
}
itemsEmpty.style.display = 'none';
itemCount.textContent = items.length;
spinBtn.disabled = false;
const totalW = weights.reduce((s, w) => s + w, 0);
items.forEach((item, i) => {
const rc = rarColor(rarities[i]);
const w = weights[i] || 1;
const pct = totalW > 0 ? ((w / totalW) * 100) : 0;
const row = document.createElement('div');
row.className = 'item-row';
row.innerHTML =
`<span class="ir-rar" data-r="${i}" style="background:${rc}"></span>` +
`<span class="ir-name">${esc(item)}</span>` +
`<span class="ir-pct" data-p="${i}">${pct < 0.1 ? '<0.1' : pct.toFixed(1)}%</span>` +
`<div class="ir-wwrap">` +
`<div class="ir-bar"><div class="ir-fill" data-f="${i}" style="width:${Math.min(pct * 2, 100)}%;background:${rc}"></div></div>` +
`<input type="range" class="ir-slider" value="${w}" min="1" max="100" data-idx="${i}">` +
`<span class="ir-val" data-v="${i}">${w}</span>` +
`</div>` +
`<button class="ir-del" data-idx="${i}">✕</button>`;
itemList.appendChild(row);
});
itemList.querySelectorAll('.ir-slider').forEach(sl => {
sl.addEventListener('input', () => {
const val = parseInt(sl.value, 10);
const idx = parseInt(sl.dataset.idx, 10);
weights[idx] = val;
recomputeAllRarities();
const vEl = itemList.querySelector(`.ir-val[data-v="${idx}"]`);
if (vEl) vEl.textContent = val;
updatePcts();
saveAll();
});
});
itemList.querySelectorAll('.ir-del').forEach(btn => {
btn.addEventListener('click', () => {
const idx = parseInt(btn.dataset.idx, 10);
items.splice(idx, 1); weights.splice(idx, 1); recomputeAllRarities();
saveAll(); renderItems(); renderPresets();
});
});
}
function updatePcts() {
const totalW = weights.reduce((s, w) => s + w, 0);
items.forEach((_, i) => {
const w = weights[i] || 1;
const pct = totalW > 0 ? ((w / totalW) * 100) : 0;
const pEl = itemList.querySelector(`.ir-pct[data-p="${i}"]`);
if (pEl) pEl.textContent = pct < 0.1 ? '<0.1%' : pct.toFixed(1) + '%';
const fEl = itemList.querySelector(`.ir-fill[data-f="${i}"]`);
if (fEl) { fEl.style.width = Math.min(pct * 2, 100) + '%'; fEl.style.background = rarColor(rarities[i]); }
const rarEl = itemList.querySelector(`.ir-rar[data-r="${i}"]`);
if (rarEl) rarEl.style.background = rarColor(rarities[i]);
});
}
function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
/* ─── Spin ─── */
const ITEM_W = 204;
const BASE_BEFORE = 20;
const AFTER_SPIN = 5;
const MIN_SCROLL_ITEMS = 30;
const DURATION = 5500;
function easeOutCubic(t) { return 1 - Math.pow(1 - t, 3); }
function getCurrentX() {
const m = track.style.transform.match(/translateX\(([-\d.]+)px\)/);
return m ? parseFloat(m[1]) : 0;
}
function makeItems(winnerIdx, beforeCount) {
const w = items[winnerIdx];
const wr = rarities[winnerIdx] || 'consumer';
// weighted random pick from ALL items
function pick() {
const totalW = weights.reduce((s, v) => s + v, 0);
let r = Math.random() * totalW;
for (let i = 0; i < items.length; i++) { r -= weights[i]; if (r <= 0) return { text: items[i], rarity: rarities[i] }; }
return { text: items[items.length - 1], rarity: rarities[items.length - 1] };
}
const before = [];
for (let i = 0; i < beforeCount; i++) before.push(pick());
const after = [];
for (let i = 0; i < AFTER_SPIN; i++) after.push(pick());
return { before, after, winner: { text: w, rarity: wr } };
}
function spin() {
if (isSpinning || items.length < 2) return;
isSpinning = true; spinBtn.disabled = true; spinLabel.textContent = 'Крутится...';
const totalW = weights.reduce((s, w) => s + w, 0);
let r = Math.random() * totalW;
let wi = 0;
for (let i = 0; i < weights.length; i++) { r -= (weights[i] || 1); if (r <= 0) { wi = i; break; } }
const winner = items[wi];
const wr = rarities[wi] || 'consumer';
const cw = trackWrap.offsetWidth || 680;
const co = cw / 2 - ITEM_W / 2;
const currentX = getCurrentX();
const oldCount = track.children.length;
const minScrollPx = MIN_SCROLL_ITEMS * ITEM_W + Math.random() * ITEM_W * 0.5;
let beforeCount = BASE_BEFORE;
if (currentX < 0 && oldCount > 0) {
const minEndX = -(oldCount + beforeCount) * ITEM_W + co;
const deficit = minScrollPx - (currentX - minEndX);
if (deficit > 0) beforeCount += Math.ceil(deficit / ITEM_W) + 2;
}
const { before, after, winner: wObj } = makeItems(wi, beforeCount);
const startIdx = track.children.length;
before.forEach(it => {
const div = document.createElement('div');
div.className = 'track-item ' + rarClass(it.rarity);
div.innerHTML = `<span class="t-label">${esc(it.text)}</span><span class="t-bar"></span>`;
track.appendChild(div);
});
{
const div = document.createElement('div');
div.className = 'track-item ' + rarClass(wObj.rarity);
div.innerHTML = `<span class="t-label">${esc(wObj.text)}</span><span class="t-bar"></span>`;
track.appendChild(div);
}
after.forEach(it => {
const div = document.createElement('div');
div.className = 'track-item ' + rarClass(it.rarity);
div.innerHTML = `<span class="t-label">${esc(it.text)}</span><span class="t-bar"></span>`;
track.appendChild(div);
});
const winnerGlobalIdx = startIdx + beforeCount;
const endX = -(winnerGlobalIdx * ITEM_W) + co;
const startX = oldCount === 0 ? 0 : currentX;
track.style.transform = `translateX(${startX}px)`;
requestAnimationFrame(() => {
const t0 = performance.now();
function anim(now) {
const p = Math.min((now - t0) / DURATION, 1);
const e = easeOutCubic(p);
track.style.transform = `translateX(${startX + (endX - startX) * e}px)`;
if (p < 1) { requestAnimationFrame(anim); }
else {
track.style.transform = `translateX(${endX}px)`;
finish(winner, wr, winnerGlobalIdx);
}
}
requestAnimationFrame(anim);
});
}
function finish(winner, rarityId, winnerIdx) {
const all = track.querySelectorAll('.track-item');
const winColor = rarColor(rarityId);
let winnerEl = all[winnerIdx];
if (!winnerEl || winnerEl.querySelector('.t-label')?.textContent !== winner) {
// fallback: поиск ближайшего по тексту
console.warn('winnerIdx mismatch', { winner, winnerIdx, total: all.length,
actual: winnerEl?.querySelector('.t-label')?.textContent });
let best = null, bestDist = Infinity;
Array.from(all).forEach((el, i) => {
if (el.querySelector('.t-label')?.textContent === winner) {
const d = Math.abs(i - winnerIdx);
if (d < bestDist) { bestDist = d; best = el; }
}
});
winnerEl = best;
}
all.forEach(el => {
if (el === winnerEl) {
el.style.borderColor = winColor;
el.style.boxShadow = `0 0 24px ${winColor}60, inset 0 0 20px ${winColor}15`;
el.style.transform = 'scale(1.06)';
el.style.zIndex = '1';
const bar = el.querySelector('.t-bar');
if (bar) { bar.style.background = winColor; bar.style.boxShadow = `0 0 8px ${winColor}80`; bar.style.height = '5px'; }
} else {
el.style.opacity = '0.15';
el.style.filter = 'grayscale(0.7)';
}
});
isSpinning = false; spinBtn.disabled = false; spinLabel.textContent = 'Открыть кейс';
const who = settingsProfileInput.value.trim() || '';
addHistory(winner, rarityId, who);
showResult(winner, who);
}
function showResult(w, who) {
resultItem.textContent = w;
resultWho.textContent = who ? 'Для: ' + who : '';
resultWho.style.display = who ? 'block' : 'none';
resultModal.classList.remove('hidden');
}
function closeResult() { resultModal.classList.add('hidden'); }
/* ─── History ─── */
function renderHistory() {
historyList.innerHTML = '';
if (history.length === 0) { historyEmpty.style.display = 'block'; historyCount.textContent = '0'; return; }
historyEmpty.style.display = 'none';
historyCount.textContent = history.length;
history.slice().reverse().forEach(h => {
const c = h.rarity ? rarColor(h.rarity) : '#888';
const li = document.createElement('li'); li.className = 'history-item';
li.innerHTML =
`<span class="h-rar" style="background:${c}"></span>` +
`<span class="h-item">${esc(h.item)}</span>` +
(h.who ? `<span class="h-who">${esc(h.who)}</span>` : '') +
`<span class="h-date">${h.date}</span>`;
historyList.appendChild(li);
});
}
function addHistory(item, rarityId, who) {
const now = new Date();
const pad = n => String(n).padStart(2, '0');
const ds = `${pad(now.getDate())}.${pad(now.getMonth()+1)}.${pad(now.getFullYear())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
history.push({ item, date: ds, rarity: rarityId, who });
if (history.length > 100) history = history.slice(-100);
saveHistory(); renderHistory();
}
/* ─── Presets ─── */
function renderPresets() {
presetList.innerHTML = '';
if (presets.length === 0) { presetList.innerHTML = '<div class="empty-text">Нет сохранённых пресетов</div>'; return; }
presets.forEach((pr, i) => {
const div = document.createElement('div'); div.className = 'preset-item';
div.innerHTML =
`<span class="pi-name">${esc(pr.name)}</span>` +
`<span class="pi-count">${pr.items.length}</span>` +
`<div class="pi-actions">` +
`<button class="pi-load" data-idx="${i}">↻</button>` +
`<button class="pi-del" data-idx="${i}">✕</button>` +
`</div>`;
presetList.appendChild(div);
});
presetList.querySelectorAll('.pi-load').forEach(btn => {
btn.addEventListener('click', () => {
const pr = presets[parseInt(btn.dataset.idx, 10)];
if (!pr) return;
items = [...pr.items];
weights = pr.weights ? [...pr.weights] : items.map(() => 10);
recomputeAllRarities();
saveAll(); renderItems(); renderPresets();
});
});
presetList.querySelectorAll('.pi-del').forEach(btn => {
btn.addEventListener('click', () => { presets.splice(parseInt(btn.dataset.idx, 10), 1); savePresets(); renderPresets(); });
});
}
function savePreset() {
const name = presetNameInput.value.trim();
if (!name || items.length === 0) return;
const existing = presets.findIndex(p => p.name === name);
if (existing !== -1) {
if (!confirm(`Пресет "${name}" уже есть. Перезаписать?`)) return;
presets[existing] = { name, items: [...items], rarities: [...rarities], weights: [...weights] };
} else {
presets.push({ name, items: [...items], rarities: [...rarities], weights: [...weights] });
}
savePresets(); presetNameInput.value = ''; presetSaveBtn.disabled = true; renderPresets();
}
/* ─── Events ─── */
addBtn.addEventListener('click', () => {
const parsed = parseBulk(bulkInput.value);
if (parsed.length === 0) return;
parsed.forEach(p => { items.push(p); weights.push(10); });
recomputeAllRarities();
bulkInput.value = ''; saveAll(); renderItems(); renderPresets();
});
bulkInput.addEventListener('keydown', e => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); addBtn.click(); }
});
clearItemsBtn.addEventListener('click', () => {
if (items.length === 0) return;
if (!confirm('Очистить все варианты?')) return;
items = []; weights = []; recomputeAllRarities(); saveAll(); renderItems(); renderPresets();
});
spinBtn.addEventListener('click', spin);
resultCloseBtn.addEventListener('click', closeResult);
resultModal.addEventListener('click', e => { if (e.target === resultModal) closeResult(); });
document.addEventListener('keydown', e => { if (e.key === 'Escape') { closeResult(); settingsModal.classList.add('hidden'); } });
clearHistoryBtn.addEventListener('click', () => { if (history.length === 0) return; history = []; saveHistory(); renderHistory(); });
presetNameInput.addEventListener('input', () => { presetSaveBtn.disabled = !presetNameInput.value.trim() || items.length === 0; });
presetSaveBtn.addEventListener('click', savePreset);
/* ─── Init ─── */
loadAll();
if (!localStorage.getItem(LS.THEME)) setTheme('dark');
else setTheme(document.documentElement.dataset.theme);
if (!localStorage.getItem(LS.ACCENT)) {
const def = '#a78bfa';
colorPicker.querySelector('.color-swatch[data-color="' + def + '"]')?.classList.add('active');
applyAccent(def);
} else {
const saved = localStorage.getItem(LS.ACCENT);
colorPicker.querySelector(`.color-swatch[data-color="${saved}"]`)?.classList.add('active');
}
renderItems();
renderHistory();
renderPresets();
if (items.length > 0) bulkInput.placeholder = 'Добавь ещё...';