-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
5995 lines (5092 loc) · 223 KB
/
Copy pathscript.js
File metadata and controls
5995 lines (5092 loc) · 223 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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Konami Code Easter Egg with Streamer Window Sync
(function() {
const konamiCode = ['ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowLeft', 'ArrowRight'];
let konamiIndex = 0;
let pokemonFontActive = false;
// Check if Konami code state is saved in localStorage
if (localStorage.getItem('pokemonFontActive') === 'true') {
document.body.classList.add('pokemon-font-active');
pokemonFontActive = true;
}
document.addEventListener('keydown', function(e) {
// Check if the key matches the next key in the sequence
if (e.key === konamiCode[konamiIndex]) {
konamiIndex++;
// If the entire code has been entered
if (konamiIndex === konamiCode.length) {
togglePokemonFont();
konamiIndex = 0; // Reset for next time
}
} else {
// Reset if wrong key is pressed
konamiIndex = 0;
// But check if the current key is the first key in the sequence
if (e.key === konamiCode[0]) {
konamiIndex = 1;
}
}
});
function togglePokemonFont() {
pokemonFontActive = !pokemonFontActive;
if (pokemonFontActive) {
document.body.classList.add('pokemon-font-active');
localStorage.setItem('pokemonFontActive', 'true');
// Show a fun notification
showKonamiNotification('✨ Pokemon Font Activated! ✨');
// Sync with streamer window if it exists
syncStreamerWindowFont(true);
} else {
document.body.classList.remove('pokemon-font-active');
localStorage.setItem('pokemonFontActive', 'false');
showKonamiNotification('Pokemon Font Deactivated');
// Sync with streamer window if it exists
syncStreamerWindowFont(false);
}
}
function syncStreamerWindowFont(isActive) {
// Check if streamer window exists and is open
if (typeof streamerWindow !== 'undefined' && streamerWindow && !streamerWindow.closed) {
try {
if (isActive) {
streamerWindow.document.body.classList.add('pokemon-font-active');
} else {
streamerWindow.document.body.classList.remove('pokemon-font-active');
}
} catch (e) {
console.log('Could not sync font with streamer window:', e);
}
}
}
function showKonamiNotification(message) {
const notification = document.createElement('div');
notification.textContent = message;
notification.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
color: #2a5834;
padding: 20px 40px;
border-radius: 10px;
font-size: 16px;
font-weight: bold;
z-index: 10000;
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
border: 4px solid #2a5834;
animation: konamiPulse 0.5s ease-in-out;
`;
// Add animation keyframes if they don't exist
if (!document.querySelector('#konami-style')) {
const style = document.createElement('style');
style.id = 'konami-style';
style.textContent = `
@keyframes konamiPulse {
0%, 100% { transform: translate(-50%, -50%) scale(1); }
50% { transform: translate(-50%, -50%) scale(1.1); }
}
`;
document.head.appendChild(style);
}
document.body.appendChild(notification);
// Remove notification after 2 seconds
setTimeout(() => {
notification.style.transition = 'opacity 0.5s';
notification.style.opacity = '0';
setTimeout(() => {
document.body.removeChild(notification);
}, 500);
}, 2000);
}
// Make sync function globally accessible so it can be called when streamer window opens
window.syncStreamerWindowFont = syncStreamerWindowFont;
window.isPokemonFontActive = () => pokemonFontActive;
})();
// Custom ROM data storage
let customRomData = {
pokemon: [],
routes: [],
sprites: {},
evolutionLines: {},
name: 'Custom ROM',
gymLeaders: [], // ADD THIS
eliteFour: [], // ADD THIS
kantoLeaders: [] // ADD THIS (optional, for games like HGSS)
};
// Show custom ROM upload interface inline
function showCustomRomUploadInterface() {
const gameContainer = document.getElementById('game-select-container');
gameContainer.style.display = 'block';
const savedName = customRomData.name !== 'Custom ROM' ? customRomData.name : '';
gameContainer.innerHTML = `
<div style="max-width: 700px; margin: 0 auto;">
<h3 style="color: #2a5834; margin-bottom: 15px; font-size: 12px;">ROM Hack Name</h3>
<p style="font-size: 8px; margin-bottom: 10px; color: #666;">Give your custom ROM a name</p>
<div style="margin-bottom: 20px;">
<input type="text"
id="custom-rom-name"
placeholder="Enter ROM Hack name..."
value="${savedName || 'Custom ROM'}"
onchange="updateCustomRomName()"
style="width: 100%; padding: 10px; font-family: 'Press Start 2P', monospace;
font-size: 9px; border: 2px solid #78c850; border-radius: 4px;
background: white; color: #2a5834;">
</div>
<h3 style="color: #2a5834; margin-bottom: 15px; font-size: 12px;">Step 1: Upload Pokemon Data</h3>
<p style="font-size: 8px; margin-bottom: 10px; color: #666;">CSV format: name,type1,type2,sprite_url,evolution_line</p>
<div class="drop-zone" id="pokemon-drop-zone">
<div class="drop-zone-icon">📄</div>
<div class="drop-zone-label">Drag & Drop Pokemon CSV Here</div>
<div class="drop-zone-hint">or click to browse</div>
</div>
<div style="display: flex; gap: 10px; margin-bottom: 15px;">
<input type="file" id="pokemon-csv-upload" accept=".csv" style="display: none;">
<button onclick="document.getElementById('pokemon-csv-upload').click()"
style="padding: 10px 15px; background: #3498db; color: white; border: none;
border-radius: 4px; cursor: pointer; font-family: 'Press Start 2P', monospace;
font-size: 8px;">
Browse Files
</button>
<button onclick="downloadPokemonTemplate()"
style="padding: 10px 15px; background: #27ae60; color: white; border: none;
border-radius: 4px; cursor: pointer; font-family: 'Press Start 2P', monospace;
font-size: 8px;">
Download Template
</button>
</div>
<div id="pokemon-upload-status" style="font-size: 7px; color: #666; margin-bottom: 15px;"></div>
<h3 style="color: #2a5834; margin-bottom: 15px; font-size: 12px;">Step 2: Upload Routes Data</h3>
<p style="font-size: 8px; margin-bottom: 10px; color: #666;">CSV format: route_name</p>
<div class="drop-zone" id="routes-drop-zone">
<div class="drop-zone-icon">🗺️</div>
<div class="drop-zone-label">Drag & Drop Routes CSV Here</div>
<div class="drop-zone-hint">or click to browse</div>
</div>
<div style="display: flex; gap: 10px; margin-bottom: 15px;">
<input type="file" id="routes-csv-upload" accept=".csv" style="display: none;">
<button onclick="document.getElementById('routes-csv-upload').click()"
style="padding: 10px 15px; background: #3498db; color: white; border: none;
border-radius: 4px; cursor: pointer; font-family: 'Press Start 2P', monospace;
font-size: 8px;">
Browse Files
</button>
<button onclick="downloadRoutesTemplate()"
style="padding: 10px 15px; background: #27ae60; color: white; border: none;
border-radius: 4px; cursor: pointer; font-family: 'Press Start 2P', monospace;
font-size: 8px;">
Download Template
</button>
</div>
<div id="routes-upload-status" style="font-size: 7px; color: #666; margin-bottom: 15px;"></div>
<h3 style="color: #2a5834; margin-bottom: 15px; font-size: 12px;">Step 3: Upload Sprites (Optional)</h3>
<p style="font-size: 8px; margin-bottom: 10px; color: #666;">Upload sprites or use URLs in CSV</p>
<div class="drop-zone" id="sprites-drop-zone">
<div class="drop-zone-icon">🖼️</div>
<div class="drop-zone-label">Drag & Drop Sprite Images Here</div>
<div class="drop-zone-hint">or click to browse (multiple files supported)</div>
</div>
<div style="display: flex; gap: 10px; margin-bottom: 15px;">
<input type="file" id="sprites-upload" accept="image/*" multiple style="display: none;">
<button onclick="document.getElementById('sprites-upload').click()"
style="padding: 10px 15px; background: #3498db; color: white; border: none;
border-radius: 4px; cursor: pointer; font-family: 'Press Start 2P', monospace;
font-size: 8px;">
Browse Files
</button>
</div>
<div id="sprites-upload-status" style="font-size: 7px; color: #666; margin-bottom: 20px;"></div>
<h3 style="color: #2a5834; margin-bottom: 15px; font-size: 12px;">Step 4: Upload Gym Leaders & Elite Four (Optional)</h3>
<p style="font-size: 8px; margin-bottom: 10px; color: #666;">CSV format: name,location,badge,type,level_cap,is_elite_four,title</p>
<div class="drop-zone" id="gym-leaders-drop-zone">
<div class="drop-zone-icon">🏆</div>
<div class="drop-zone-label">Drag & Drop Gym Leaders CSV Here</div>
<div class="drop-zone-hint">or click to browse</div>
</div>
<div style="display: flex; gap: 10px; margin-bottom: 15px;">
<input type="file" id="gym-leaders-csv-upload" accept=".csv" style="display: none;">
<button onclick="document.getElementById('gym-leaders-csv-upload').click()"
style="padding: 10px 15px; background: #3498db; color: white; border: none;
border-radius: 4px; cursor: pointer; font-family: 'Press Start 2P', monospace;
font-size: 8px;">
Browse Files
</button>
<button onclick="downloadGymLeadersTemplate()"
style="padding: 10px 15px; background: #27ae60; color: white; border: none;
border-radius: 4px; cursor: pointer; font-family: 'Press Start 2P', monospace;
font-size: 8px;">
Download Template
</button>
</div>
<div id="gym-leaders-upload-status" style="font-size: 7px; color: #666; margin-bottom: 20px;"></div>
</div>
`;
setupCustomRomListeners();
setupDragAndDrop();
checkCustomRomReadyInline();
}
function setupDragAndDrop() {
const dropZones = [
{ id: 'pokemon-drop-zone', inputId: 'pokemon-csv-upload', handler: handlePokemonCSV },
{ id: 'routes-drop-zone', inputId: 'routes-csv-upload', handler: handleRoutesCSV },
{ id: 'sprites-drop-zone', inputId: 'sprites-upload', handler: handleSpritesUpload },
{ id: 'gym-leaders-drop-zone', inputId: 'gym-leaders-csv-upload', handler: handleGymLeadersCSV }
];
dropZones.forEach(zone => {
const dropZone = document.getElementById(zone.id);
const fileInput = document.getElementById(zone.inputId);
if (!dropZone || !fileInput) return;
// Prevent default drag behaviors
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropZone.addEventListener(eventName, preventDefaults, false);
document.body.addEventListener(eventName, preventDefaults, false);
});
// Highlight drop zone when item is dragged over it
['dragenter', 'dragover'].forEach(eventName => {
dropZone.addEventListener(eventName, () => {
dropZone.classList.add('drag-over');
}, false);
});
['dragleave', 'drop'].forEach(eventName => {
dropZone.addEventListener(eventName, () => {
dropZone.classList.remove('drag-over');
}, false);
});
// Handle dropped files
dropZone.addEventListener('drop', (e) => {
const dt = e.dataTransfer;
const files = dt.files;
if (files.length > 0) {
// Create a mock event object for the handler
const mockEvent = {
target: {
files: files,
value: ''
}
};
zone.handler(mockEvent);
}
}, false);
// Also handle click to open file browser
dropZone.addEventListener('click', () => {
fileInput.click();
});
});
}
// Prevent default drag behaviors
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
// Check if ready and update the main start button
function checkCustomRomReadyInline() {
const startBtn = document.getElementById('start-tracker');
if (customRomData.pokemon.length > 0 && customRomData.routes.length > 0) {
startBtn.disabled = false;
selectedGame = 'custom_rom'; // Mark as ready
} else {
startBtn.disabled = true;
selectedGame = null;
}
}
// Update ROM name from input
function updateCustomRomName() {
const romNameInput = document.getElementById('custom-rom-name');
if (romNameInput && romNameInput.value.trim()) {
customRomData.name = romNameInput.value.trim();
}
}
// Download Gym Leaders CSV template
function downloadGymLeadersTemplate() {
const template = `name,location,badge,type,level_cap,is_elite_four,title,is_kanto
Brock,Pewter City,Boulder Badge,Rock,14,FALSE,,FALSE
Misty,Cerulean City,Cascade Badge,Water,21,FALSE,,FALSE
Lt. Surge,Vermilion City,Thunder Badge,Electric,28,FALSE,,FALSE
Erika,Celadon City,Rainbow Badge,Grass,32,FALSE,,FALSE
Koga,Fuchsia City,Soul Badge,Poison,37,FALSE,,FALSE
Sabrina,Saffron City,Marsh Badge,Psychic,43,FALSE,,FALSE
Blaine,Cinnabar Island,Volcano Badge,Fire,47,FALSE,,FALSE
Giovanni,Viridian City,Earth Badge,Ground,50,FALSE,,FALSE
Lorelei,Elite Four,Ice Crown,Ice,54,TRUE,Elite Four,FALSE
Bruno,Elite Four,Fighting Crown,Fighting,56,TRUE,Elite Four,FALSE
Agatha,Elite Four,Ghost Crown,Ghost,58,TRUE,Elite Four,FALSE
Lance,Elite Four,Dragon Crown,Dragon,60,TRUE,Elite Four,FALSE
Blue,Pokemon League,Champion Crown,Normal,63,TRUE,Champion,FALSE
# Instructions:
# - name: Gym Leader/Elite Four member name (required)
# - location: City/location name (required)
# - badge: Badge name (optional for Elite Four)
# - type: Pokemon type specialty (required)
# - level_cap: Level cap after defeating this leader (required, number)
# - is_elite_four: TRUE for Elite Four/Champion, FALSE for gym leaders (required)
# - title: "Elite Four" or "Champion" for Elite Four members, leave blank for gym leaders
# - is_kanto: TRUE for Kanto leaders (like in HGSS), FALSE for main region (optional)
#
# Valid types: Normal, Fire, Water, Electric, Grass, Ice, Fighting, Poison,
# Ground, Flying, Psychic, Bug, Rock, Ghost, Dragon, Dark, Steel, Fairy
#
# Leaders should be listed in the order they're encountered`;
downloadCSV(template, 'gym_leaders_template.csv');
showToast('Gym Leaders template downloaded!', 'success');
}
// Download Pokemon CSV template
function downloadPokemonTemplate() {
const template = `name,type1,type2,sprite_url,evolution_line
Fakemon1,Fire,,https://example.com/fakemon1.png,Fakemon1>Fakemon2>Fakemon3
Fakemon2,Fire,Flying,https://example.com/fakemon2.png,Fakemon1>Fakemon2>Fakemon3
Fakemon3,Fire,Dragon,https://example.com/fakemon3.png,Fakemon1>Fakemon2>Fakemon3
Fakemon4,Water,,,Fakemon4
Legendmon,Psychic,Fairy,https://example.com/legendmon.png,Legendmon
# Instructions:
# - name: Pokemon name (required, must be unique)
# - type1: Primary type (required)
# - type2: Secondary type (optional, leave blank if none)
# - sprite_url: Direct URL to sprite image (optional if uploading sprites separately)
# - evolution_line: Evolution chain separated by > (e.g., "Starter>Middle>Final")
# For Pokemon that don't evolve, just put their own name
#
# Valid types: Normal, Fire, Water, Electric, Grass, Ice, Fighting, Poison,
# Ground, Flying, Psychic, Bug, Rock, Ghost, Dragon, Dark, Steel, Fairy`;
downloadCSV(template, 'pokemon_template.csv');
showToast('Pokemon template downloaded!', 'success');
}
// Download Routes CSV template
function downloadRoutesTemplate() {
const template = `route_name
Route 1
Route 2
Dark Forest
Mystery Cave
Champion Road
Victory Road
Elite Four Challenge
# Instructions:
# - route_name: Name of the route/location (required)
# - One route per line
# - Routes will appear in the order listed`;
downloadCSV(template, 'routes_template.csv');
showToast('Routes template downloaded!', 'success');
}
// Helper function to download CSV
function downloadCSV(content, filename) {
const blob = new Blob([content], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
}
function validateCSVHeaders(text, expectedHeaders, fileType) {
const lines = text.split('\n').filter(line => line.trim() && !line.startsWith('#'));
if (lines.length < 1) {
return { valid: false, error: `${fileType} CSV is empty or only contains comments` };
}
const headers = lines[0].toLowerCase().split(',').map(h => h.trim());
const missingHeaders = expectedHeaders.filter(expected => !headers.includes(expected.toLowerCase()));
if (missingHeaders.length > 0) {
return {
valid: false,
error: `${fileType} CSV is missing required columns: ${missingHeaders.join(', ')}.\n\nFound columns: ${headers.join(', ')}\n\nExpected columns: ${expectedHeaders.join(', ')}`
};
}
if (lines.length < 2) {
return { valid: false, error: `${fileType} CSV has no data rows (only headers found)` };
}
return { valid: true };
}
// Parse Pokemon CSV
async function handlePokemonCSV(event) {
const file = event.target.files[0];
if (!file) return;
const statusDiv = document.getElementById('pokemon-upload-status');
statusDiv.innerHTML = '<span class="upload-status-info">Processing Pokemon data...</span>';
try {
const text = await file.text();
// Validate CSV structure
const expectedHeaders = ['name', 'type1'];
const validation = validateCSVHeaders(text, expectedHeaders, 'Pokemon');
if (!validation.valid) {
throw new Error(validation.error);
}
const lines = text.split('\n').filter(line => line.trim() && !line.startsWith('#'));
const header = lines[0].toLowerCase().split(',').map(h => h.trim());
customRomData.pokemon = [];
customRomData.evolutionLines = {};
for (let i = 1; i < lines.length; i++) {
const values = lines[i].split(',').map(v => v.trim());
const pokemon = {};
header.forEach((col, index) => {
pokemon[col] = values[index] || '';
});
if (!pokemon.name || !pokemon.type1) {
console.warn(`Skipping invalid row ${i + 1}: missing name or type1`);
continue;
}
const normalizedName = pokemon.name.toLowerCase().replace(/[^a-z0-9-]/g, '');
if (pokemon.evolution_line) {
const evolutions = pokemon.evolution_line.split('>').map(e =>
e.trim().toLowerCase().replace(/[^a-z0-9-]/g, '')
);
customRomData.evolutionLines[normalizedName] = evolutions;
} else {
customRomData.evolutionLines[normalizedName] = [normalizedName];
}
customRomData.pokemon.push({
name: normalizedName,
displayName: pokemon.name,
types: [pokemon.type1.toLowerCase(), pokemon.type2 ? pokemon.type2.toLowerCase() : null].filter(Boolean),
spriteUrl: pokemon.sprite_url || null
});
}
statusDiv.innerHTML = `<span class="upload-status-success">✓ Loaded ${customRomData.pokemon.length} Pokemon!</span>`;
checkCustomRomReady();
showToast(`Loaded ${customRomData.pokemon.length} Pokemon from CSV!`, 'success');
} catch (error) {
statusDiv.innerHTML = `<span class="upload-status-error">✗ Error: ${error.message}</span>`;
showToast('Failed to parse Pokemon CSV: ' + error.message, 'error', 8000);
// Clear the file input
customRomData.pokemon = [];
customRomData.evolutionLines = {};
checkCustomRomReady();
}
event.target.value = '';
}
// Parse Routes CSV
async function handleRoutesCSV(event) {
const file = event.target.files[0];
if (!file) return;
const statusDiv = document.getElementById('routes-upload-status');
statusDiv.innerHTML = '<span class="upload-status-info">Processing routes data...</span>';
try {
const text = await file.text();
// Validate CSV structure
const expectedHeaders = ['route_name'];
const validation = validateCSVHeaders(text, expectedHeaders, 'Routes');
if (!validation.valid) {
throw new Error(validation.error);
}
const lines = text.split('\n')
.map(line => line.trim())
.filter(line => line && !line.startsWith('#'));
customRomData.routes = [];
// Skip header and process routes
for (let i = 1; i < lines.length; i++) {
const routeName = lines[i].trim();
if (routeName) {
customRomData.routes.push(routeName);
}
}
if (customRomData.routes.length === 0) {
throw new Error('No valid routes found in CSV');
}
statusDiv.innerHTML = `<span class="upload-status-success">✓ Loaded ${customRomData.routes.length} routes!</span>`;
checkCustomRomReady();
showToast(`Loaded ${customRomData.routes.length} routes from CSV!`, 'success');
} catch (error) {
statusDiv.innerHTML = `<span class="upload-status-error">✗ Error: ${error.message}</span>`;
showToast('Failed to parse routes CSV: ' + error.message, 'error', 8000);
// Clear the routes
customRomData.routes = [];
checkCustomRomReady();
}
event.target.value = '';
}
// Handle sprite uploads
async function handleSpritesUpload(event) {
const files = event.target.files;
if (!files || files.length === 0) return;
const statusDiv = document.getElementById('sprites-upload-status');
statusDiv.innerHTML = '<span class="upload-status-info">Processing sprite uploads...</span>';
try {
let successCount = 0;
let errorCount = 0;
const errors = [];
for (let i = 0; i < files.length; i++) {
const file = files[i];
// Validate file is an image
if (!file.type.startsWith('image/')) {
errorCount++;
errors.push(`${file.name} is not an image file`);
continue;
}
const fileName = file.name.replace(/\.[^/.]+$/, '');
const normalizedName = fileName.toLowerCase().replace(/[^a-z0-9-]/g, '');
const reader = new FileReader();
const dataUrl = await new Promise((resolve, reject) => {
reader.onload = (e) => resolve(e.target.result);
reader.onerror = reject;
reader.readAsDataURL(file);
});
customRomData.sprites[normalizedName] = dataUrl;
successCount++;
}
let statusMessage = `<span class="upload-status-success">✓ Uploaded ${successCount} sprite(s)!</span>`;
if (errorCount > 0) {
statusMessage += `<br><span class="upload-status-error">✗ ${errorCount} file(s) skipped (not images)</span>`;
}
statusDiv.innerHTML = statusMessage;
showToast(`Uploaded ${successCount} sprite(s)!${errorCount > 0 ? ` (${errorCount} skipped)` : ''}`, successCount > 0 ? 'success' : 'warning');
} catch (error) {
statusDiv.innerHTML = `<span class="upload-status-error">✗ Error uploading sprites: ${error.message}</span>`;
showToast('Failed to upload sprites: ' + error.message, 'error');
}
event.target.value = '';
}
// Parse Gym Leaders CSV
async function handleGymLeadersCSV(event) {
const file = event.target.files[0];
if (!file) return;
const statusDiv = document.getElementById('gym-leaders-upload-status');
statusDiv.innerHTML = '<span class="upload-status-info">Processing gym leaders data...</span>';
try {
const text = await file.text();
// Validate CSV structure
const expectedHeaders = ['name', 'location', 'type', 'level_cap', 'is_elite_four'];
const validation = validateCSVHeaders(text, expectedHeaders, 'Gym Leaders');
if (!validation.valid) {
throw new Error(validation.error);
}
const lines = text.split('\n').filter(line => line.trim() && !line.startsWith('#'));
const header = lines[0].toLowerCase().split(',').map(h => h.trim());
customRomData.gymLeaders = [];
customRomData.eliteFour = [];
customRomData.kantoLeaders = [];
let validCount = 0;
let skippedCount = 0;
for (let i = 1; i < lines.length; i++) {
const values = lines[i].split(',').map(v => v.trim());
const leader = {};
header.forEach((col, index) => {
leader[col] = values[index] || '';
});
if (!leader.name || !leader.type || !leader.level_cap) {
console.warn(`Skipping row ${i + 1}: missing required fields (name, type, or level_cap)`);
skippedCount++;
continue;
}
const isEliteFour = leader.is_elite_four?.toUpperCase() === 'TRUE';
const isKanto = leader.is_kanto?.toUpperCase() === 'TRUE';
const levelCap = parseInt(leader.level_cap);
if (isNaN(levelCap)) {
console.warn(`Skipping row ${i + 1}: invalid level_cap (must be a number)`);
skippedCount++;
continue;
}
const leaderData = {
id: leader.name.toLowerCase().replace(/[^a-z0-9]/g, '_'),
name: leader.name,
location: leader.location || 'Unknown',
badge: leader.badge || '',
type: leader.type.charAt(0).toUpperCase() + leader.type.slice(1).toLowerCase(),
levelCap: levelCap,
title: leader.title || ''
};
if (isEliteFour) {
customRomData.eliteFour.push(leaderData);
} else if (isKanto) {
customRomData.kantoLeaders.push(leaderData);
} else {
customRomData.gymLeaders.push(leaderData);
}
validCount++;
}
const totalLeaders = customRomData.gymLeaders.length +
customRomData.eliteFour.length +
customRomData.kantoLeaders.length;
statusDiv.innerHTML = `<span class="upload-status-success">✓ Loaded ${customRomData.gymLeaders.length} gym leaders, ${customRomData.eliteFour.length} Elite Four members${customRomData.kantoLeaders.length > 0 ? `, ${customRomData.kantoLeaders.length} Kanto leaders` : ''}!</span>`;
if (skippedCount > 0) {
statusDiv.innerHTML += `<br><span class="upload-status-error">⚠ ${skippedCount} row(s) skipped due to missing or invalid data</span>`;
}
showToast(`Loaded ${totalLeaders} gym leaders/Elite Four members from CSV!${skippedCount > 0 ? ` (${skippedCount} skipped)` : ''}`, 'success');
} catch (error) {
statusDiv.innerHTML = `<span class="upload-status-error">✗ Error: ${error.message}</span>`;
showToast('Failed to parse gym leaders CSV: ' + error.message, 'error', 8000);
// Clear the data on error
customRomData.gymLeaders = [];
customRomData.eliteFour = [];
customRomData.kantoLeaders = [];
}
event.target.value = '';
}
// Check if custom ROM is ready to start
function checkCustomRomReady() {
checkCustomRomReadyInline();
}
// Start tracker with custom ROM data
function startCustomRom() {
if (customRomData.pokemon.length === 0 || customRomData.routes.length === 0) {
showToast('Please upload both Pokemon and routes data!', 'error');
return;
}
// Update ROM name from input before saving
updateCustomRomName();
// Store custom ROM data
gameData.customRomData = JSON.parse(JSON.stringify(customRomData));
gameData.currentGeneration = 'custom-rom';
gameData.currentGame = 'custom_rom';
// REMOVE THIS LINE - don't set isCustomRom for uploaded ROMs
// gameData.isCustomRom = true;
// Setup Pokemon names for autocomplete
pokemonNames = customRomData.pokemon.map(p => p.displayName);
// Setup evolution lines
evolutionLines = { ...customRomData.evolutionLines };
// Setup routes for the custom game
gameRoutes['custom_rom'] = {
name: customRomData.name || 'Custom ROM',
generation: 'custom-rom',
routes: [...customRomData.routes]
};
// Store gym leader data if it exists
if (customRomData.gymLeaders.length > 0 || customRomData.eliteFour.length > 0) {
gameData.customRomData.gymLeaders = [...customRomData.gymLeaders];
gameData.customRomData.eliteFour = [...customRomData.eliteFour];
gameData.customRomData.kantoLeaders = [...customRomData.kantoLeaders];
}
saveData();
document.getElementById('generation-selector-modal').style.display = 'none';
initializeApp();
showToast(`${customRomData.name} loaded successfully! Start catching Pokemon!`, 'success');
}
// Setup file upload listeners
function setupCustomRomListeners() {
const pokemonUpload = document.getElementById('pokemon-csv-upload');
if (pokemonUpload) {
pokemonUpload.addEventListener('change', handlePokemonCSV);
}
const routesUpload = document.getElementById('routes-csv-upload');
if (routesUpload) {
routesUpload.addEventListener('change', handleRoutesCSV);
}
const spritesUpload = document.getElementById('sprites-upload');
if (spritesUpload) {
spritesUpload.addEventListener('change', handleSpritesUpload);
}
const gymLeadersUpload = document.getElementById('gym-leaders-csv-upload');
if (gymLeadersUpload) {
gymLeadersUpload.addEventListener('change', handleGymLeadersCSV);
}
}
// Game data structure
let gameData = {
player1: { caught: [], team: [null, null, null, null, null, null] },
player2: { caught: [], team: [null, null, null, null, null, null] },
soulLinks: [],
usedRoutes: [],
failedRoutes: [],
playerNames: { player1: 'Player 1', player2: 'Player 2' },
strictPrimaryTypeMode: true,
currentGame: null,
currentGeneration: null,
gymProgress: {},
isCustomRom: false,
customPokemonGens: [],
customRomData: null,
spriteStyle: 'modern' // 'modern' or 'ds'
};
// Carousel state
let currentCarouselIndex = 0;
let totalCarouselSlides = 8;
// Current gym progress tab
let currentGymTab = 'gymLeaders';
// Gym tracker expanded state
let gymTrackerExpanded = false;
function normalizePokemonNameForAPI(name) {
let normalized = name.toLowerCase().trim().replace(/'/g, '');
// Special cases that need hyphens
const specialCases = {
'mr. mime': 'mr-mime',
'mrmime': 'mr-mime',
'mime jr.': 'mime-jr',
'mimejr': 'mime-jr',
'mr mime': 'mr-mime',
'mime jr': 'mime-jr',
'type: null': 'type-null',
'typenull': 'type-null',
'type null': 'type-null',
'tapu koko': 'tapu-koko',
'tapukoko': 'tapu-koko',
'tapu lele': 'tapu-lele',
'tapulele': 'tapu-lele',
'tapu bulu': 'tapu-bulu',
'tapubulu': 'tapu-bulu',
'tapu fini': 'tapu-fini',
'tapufini': 'tapu-fini',
'jangmo-o': 'jangmo-o',
'jangmoo': 'jangmo-o',
'hakamo-o': 'hakamo-o',
'hakamoo': 'hakamo-o',
'kommo-o': 'kommo-o',
'kommoo': 'kommo-o',
'porygon-z': 'porygon-z',
'porygonz': 'porygon-z',
'ho-oh': 'ho-oh',
'hooh': 'ho-oh',
'flabébé': 'flabebe',
'flabebe': 'flabebe'
};
if (specialCases[normalized]) {
return specialCases[normalized];
}
// Pokemon with forms - default to their base form
// This took me so fucking long to workout. Can you tell I've only really played Gen 2-3 & 6??
const formBasedPokemon = {
'deoxys': 'deoxys-normal',
'wormadam': 'wormadam-plant',
'giratina': 'giratina-altered',
'shaymin': 'shaymin-land',
'basculin': 'basculin-red-striped',
'darmanitan': 'darmanitan-standard',
'tornadus': 'tornadus-incarnate',
'thundurus': 'thundurus-incarnate',
'landorus': 'landorus-incarnate',
'keldeo': 'keldeo-ordinary',
'meloetta': 'meloetta-aria',
'meowstic': 'meowstic-male',
'aegislash': 'aegislash-shield',
'pumpkaboo': 'pumpkaboo-average',
'gourgeist': 'gourgeist-average',
'oricorio': 'oricorio-baile',
'lycanroc': 'lycanroc-midday',
'wishiwashi': 'wishiwashi-solo',
'minior': 'minior-red-meteor',
'mimikyu': 'mimikyu-disguised',
'necrozma': 'necrozma'
};
// For Alolan forms
if (normalized.includes('-alola') || normalized.includes('alola')) {
normalized = normalized.replace(/\s+/g, '-');
if (!normalized.includes('-alola')) {
normalized = normalized.replace('alola', '-alola');
}
}
normalized = normalized.replace(/[^a-z0-9-]/g, '');
// Handle Nidoran gender symbols
if (normalized.includes('nidoran')) {
if (name.includes('♀') || name.toLowerCase().includes('female') || name.includes('-f')) {
return 'nidoran-f';
} else if (name.includes('♂') || name.toLowerCase().includes('male') || name.includes('-m')) {
return 'nidoran-m';
}
}
// Check if this Pokemon needs a form specified
if (formBasedPokemon[normalized]) {
return formBasedPokemon[normalized];
}
return normalized;
}
// Confetti Animation Functions
function createConfetti() {
const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57', '#ff9ff3', '#54a0ff'];
const confettiContainer = document.createElement('div');
confettiContainer.className = 'confetti-container';
document.body.appendChild(confettiContainer);
// Create 150 confetti pieces
// Broken ass, loads them all at the top and they stop for a second.
for (let i = 0; i < 150; i++) {
const confetti = document.createElement('div');
confetti.className = 'confetti-piece';
confetti.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
confetti.style.left = Math.random() * 100 + '%';
confetti.style.animationDelay = Math.random() * 3 + 's';
confetti.style.animationDuration = (Math.random() * 2 + 2) + 's';
confettiContainer.appendChild(confetti);
}
// Remove confetti after animation
setTimeout(() => {
document.body.removeChild(confettiContainer);
}, 5000);
}
// Gym Leader Progress Functions
function initializeGymProgress() {
if (!gameData.currentGame) return;
if (!gameData.gymProgress[gameData.currentGame]) {
gameData.gymProgress[gameData.currentGame] = {};
}
}
// Calculate current level cap based on gym progress
function getCurrentLevelCap() {
const gymData = getCurrentGymLeaders();
if (!gymData) return '--';
const currentProgress = gameData.gymProgress[gameData.currentGame] || {};
// Count completed gym leaders
const completedGyms = gymData.leaders.filter(leader => currentProgress[leader.id]).length;
const totalGyms = gymData.leaders.length;
// Count completed Kanto leaders if they exist
// Looking at you Gen 2 remakes
let completedKanto = 0;
let totalKanto = 0;
if (gymData.kantoLeaders) {
completedKanto = gymData.kantoLeaders.filter(leader => currentProgress[leader.id]).length;
totalKanto = gymData.kantoLeaders.length;
}
const totalGymCount = totalGyms + totalKanto;
const completedGymCount = completedGyms + completedKanto;
// Check if champion is defeated
const champion = gymData.eliteFour.find(member => member.title === 'Champion');
const championDefeated = champion ? currentProgress[champion.id] : false;
let nextEncounter = null;
// Find the next undefeated encounter in order