-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
4923 lines (4390 loc) · 217 KB
/
Copy pathscript.js
File metadata and controls
4923 lines (4390 loc) · 217 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
/*
* ╔══════════════════════════════════════════════════════════════════╗
* ║ OPEN MIC RPG — script.js ║
* ║ ║
* ║ TABLE OF CONTENTS (search §N to jump to section) ║
* ║ ───────────────────────────────────────────────── ║
* ║ §1 CONSTANTS & CONFIGURATION ║
* ║ §2 DATA: IDEA POOL ║
* ║ §3 DATA: SHOW POOL ║
* ║ §4 DATA: EVENT POOL ║
* ║ §5 VISUAL EFFECTS & ANIMATIONS ║
* ║ §6 SOUND SYSTEM ║
* ║ §7 STATE & GLOBALS ║
* ║ §8 HELPERS & UTILITIES ║
* ║ §9 XP & LEVEL SYSTEM ║
* ║ §10 SCORING ENGINE ⛔ protected — do not alter formulas ║
* ║ §11 PROGRESSION & FLOW STATE ║
* ║ §12 TIME & DAY SYSTEM ║
* ║ §13 EVENT ENGINE ║
* ║ §14 PERSISTENCE (save / load) ║
* ║ §15 UI: DOM CACHE ║
* ║ §16 UI: DIALOGS ║
* ║ §17 UI: RENDERING & SCENES ║
* ║ §18 UI: JOKE LIST ║
* ║ §19 UI: INTRO FLOW ║
* ║ §20 HANDLERS: WRITING ║
* ║ §21 HANDLERS: SHOWS ║
* ║ §22 HANDLERS: CONTENT, STUDY & OTHER ║
* ║ §23 HANDLERS: MATERIAL & JOKE MANAGEMENT ║
* ║ §24 BOOT SEQUENCE ║
* ╚══════════════════════════════════════════════════════════════════╝
*/
// ═══════════════════════════════════════════════════════════════════
// §1 CONSTANTS & CONFIGURATION
// ═══════════════════════════════════════════════════════════════════
const STORAGE_KEY = "openMicRPG.save.v2";
const LEGACY_STORAGE_KEY = "openMicRPG.legacyArchive.v1";
const SAVE_SCHEMA_VERSION = 3;
const GAME_CONTENT = window.OpenMicRpgContent || {};
const V2_PROGRESSION = GAME_CONTENT.progression || { classOrder: [], classPaths: {}, endingRules: {}, politico: {} };
const V2_EVENTS = GAME_CONTENT.v2Events || { classEvents: {} };
const V2_ENDINGS = GAME_CONTENT.endings || { base: {}, tone: {}, tier: {}, enabledSpecials: [] };
const CARVALHO_DIALOGS = GAME_CONTENT.carvalhoDialogs || [];
const eventPool = GAME_CONTENT.events || [];
const LEGEND_TEXT = "🤯 explodiu | 🔥 matou | 🙂 segurou | 😶 risinhos | 💧 deu água";
const MAX_SCHEDULED_SHOWS = 3;
function loadLegacyArchive() {
try {
const archive = JSON.parse(localStorage.getItem(LEGACY_STORAGE_KEY) || "[]");
return Array.isArray(archive)
? archive.filter(entry => entry && typeof entry === "object" && (entry.runId || entry.endingId || entry.classId))
: [];
} catch (error) {
console.warn("Falha ao carregar arquivo de legado.", error);
return [];
}
}
function computeLegacyBonuses() {
const archive = loadLegacyArchive();
const dominantTones = new Set(archive.map(run => run.dominantTone).filter(Boolean));
return {
oneliner: false,
humorNegro: false,
storytelling: false,
prop: false,
hack: archive.length >= 2 || dominantTones.has("hack"),
politico: archive.length >= 2 || dominantTones.has("político") || archive.some(run => run.politicoUnlocked),
writingGuide: archive.some(run => run.writingGuideUnlocked),
crowdWork: archive.some(run => run.crowdWorkUnlocked),
expandedClasses: archive.length >= 2
};
}
function saveRunToLegacyArchive(runSummary) {
try {
const archive = loadLegacyArchive();
archive.push(runSummary);
localStorage.setItem(LEGACY_STORAGE_KEY, JSON.stringify(archive));
return true;
} catch (error) {
console.warn("Falha ao salvar corrida no arquivo de legado.", error);
return false;
}
}
// ─── Time ───
const DAYS_OF_WEEK = ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"];
function getMaxActivityPoints() {
if (state && state.hasEmployment) return 2;
return 1;
}
const ACTIVITY_COSTS = {
study: 1,
desk: 1, // sentar e escrever
day: 1, // anotar durante o dia (both cost 1 now)
content: 1 // criar conteúdo
};
const createInitialTimeState = () => ({
currentDay: 1,
currentWeekDay: 1, // Segunda
currentWeek: 1,
activityPoints: getMaxActivityPoints(),
scheduledShows: [], // [{ showId, dayScheduled, showType }] — max 3
performedShowToday: false,
showHistory: [],
consecutiveGoodShows: 0,
flowState: null, // { active: true, daysRemaining: X, endChance: 0.2 }
eventsThisWeek: 0
});
// ─── Tones & Structures ───
const allowedTones = ["besteirol", "vulgar", "limpo", "humor negro", "hack", "político"];
function getUnlockedTones() {
const base = ["besteirol", "limpo", "vulgar"];
if (state && state.humorNegroUnlocked) base.push("humor negro");
if (state && (state.hackUnlocked || state.levelNumber >= 5)) base.push("hack");
if (state && (state.politicoUnlocked || state.levelNumber >= (V2_PROGRESSION.politico?.levelUnlock || 8))) base.push("político");
return base;
}
function getUnlockedStructures() {
const base = ["bit"];
if (state && state.onelinerUnlocked) base.push("oneliner");
if (state && state.storytellingUnlocked) base.push("storytelling");
if (state && state.propUnlocked) base.push("prop");
return base;
}
function getMaxCrowdWorkMinutes(selectedJokeCount) {
return state?.crowdWorkUnlocked ? Math.min(3, Math.max(0, selectedJokeCount || 0)) : 0;
}
function canStudyThisWeek() {
return (state?.weeklyStudyCount || 0) < 3;
}
const toneDescriptions = {
besteirol: "besteiras descompromissadas",
vulgar: "piadas pesadas sem filtro",
limpo: "humor família e bobinho",
"humor negro": "piadas azedas que dividem a sala",
hack: "observações batidas porém eficientes",
"político": "poder, sociedade e contradição"
};
const toneDescriptionsLong = {
besteirol: "Humor bobo e descompromissado. Funciona bem com plateias relaxadas que querem rir sem pensar.",
vulgar: "Piadas pesadas, linguagem explícita. Pode dividir a sala, mas conecta com quem curte.",
limpo: "Humor família, sem palavrões. Ideal para corporativos e eventos diversos.",
"humor negro": "Piadas sobre temas tabu. Pode ser brilhante ou desastroso dependendo da plateia.",
hack: "Observações batidas mas eficientes. Todo mundo já ouviu, mas ainda funciona.",
"político": "Humor sobre poder, vida pública e contradições sociais. Depende muito da sala."
};
const structures = ["oneliner", "storytelling", "bit", "prop"];
const STRUCTURE_MINUTE_RANGES = {
oneliner: [1, 1],
prop: [1, 1],
bit: [2, 2],
storytelling: [3, 3]
};
const structureDescriptions = {
oneliner: "Piada curta e direta, que não necessita de mais contexto. 1 min.",
storytelling: "Uma narrativa, uma história com vários punchs. 3 min.",
bit: "Sequência de piadas conectadas sobre um mesmo tema. 2 min.",
prop: "Usa objetos ou elementos visuais para complementar a piada. 1 min."
};
const PROFILE_BADGE_LABELS = {
storytellingUnlocked: { label: "📚 Storytelling", kind: "feature" },
fiveA5Unlocked: { label: "⭐ 5 a 5", kind: "milestone" },
seViraNos5Unlocked: { label: "🏠 Se Vira nos 5", kind: "milestone" },
pague15Unlocked: { label: "🏆 Pague 15", kind: "milestone" },
timingBasico: { label: "⏱️ Timing", kind: "perk" },
timingAvancado: { label: "⏱️ Timing Pro", kind: "perk" },
presencaDePalco: { label: "🎭 Presença", kind: "perk" },
crowdWorkIniciante: { label: "🗣️ Crowd Work", kind: "perk" },
crowdWorkPro: { label: "🗣️ Crowd Work Pro", kind: "perk" },
lidarComHeckler: { label: "🛡️ Hecklers", kind: "perk" },
energiaAlta: { label: "⚡ Energia Alta", kind: "perk" },
premissaSolida: { label: "📝 Premissa", kind: "perk" },
economiaDePalavras: { label: "✂️ Economia", kind: "perk" },
tagMachine: { label: "🏷️ Tag Machine", kind: "perk" },
callbackMaster: { label: "🔁 Callback", kind: "perk" },
setupKiller: { label: "🎯 Setup Killer", kind: "perk" }
};
// ─── Score scale (nota 5 → 1) ───
const SCORE_EMOJI_SCALE = [
{ threshold: 0.45, emoji: "🤯", label: "Explodiu", nota: 5 },
{ threshold: 0.32, emoji: "🔥", label: "Matou", nota: 4 },
{ threshold: 0.18, emoji: "🙂", label: "Segurou", nota: 3 },
{ threshold: 0.05, emoji: "😶", label: "Risinhos", nota: 2 },
{ threshold: -Infinity, emoji: "💧", label: "Deu água", nota: 1 }
];
// ─── Writing modes ───
const writingModes = {
desk: {
id: "desk",
label: "Sentar e escrever",
desc: "Gasta mais motivação mas gera piadas com potencial muito maior. 10% de chance de não render nada.",
costLabel: "⚡ 1 ponto",
motivationCost: 15,
textoBonus: 0.10,
failChance: 0.10
},
day: {
id: "day",
label: "Anotar durante o dia",
desc: "Não gasta motivação mas o material sai mais cru. 20% de chance de não render nada.",
costLabel: "⚡ 1 ponto",
motivationCost: 0,
textoBonus: 0,
failChance: 0.20
}
};
// ─── Scenes (image lookup by key) ───
const scenes = GAME_CONTENT.world?.scenes || {} ;
const avatarImages = GAME_CONTENT.world?.avatarImages || {} ;
const SHOW_RESULT_IDS = Object.freeze({
1: "deu-agua",
2: "risinhos",
3: "segurou",
4: "matou",
5: "explodiu"
});
function getShowResultImage(nota) {
const avatarId = avatarImages[state?.avatar] ? state.avatar : "avatar1";
const resultId = SHOW_RESULT_IDS[nota] || SHOW_RESULT_IDS[3];
return `assets/scenes/results/${avatarId}/${resultId}.png`;
}
const confettiColors = ['#d4a84b', '#ffd966', '#f5e6c8', '#a65d4e', '#5a8f5a'];
// ─── Narrative strings ───
const homeText = GAME_CONTENT.world?.homeText || "" ;
const mentorIntroLines = GAME_CONTENT.world?.mentorIntroLines || [] ;
// ─── Perk Trees ───
const PERK_TREES = V2_PROGRESSION.perkTrees || {};
// ─── Classes ───
const CLASSES = V2_PROGRESSION.classes || {};
function hasClassPassive(passiveId) {
const cls = CLASSES[state.chosenClass];
return cls?.passive === passiveId;
}
// ═══════════════════════════════════════════════════════════════════
// §2 DATA: IDEA POOL
// ═══════════════════════════════════════════════════════════════════
const ideaPool = [...(GAME_CONTENT.world?.ideaPool || []), ...(GAME_CONTENT.v2World?.politicoIdeas || [])];
// ═══════════════════════════════════════════════════════════════════
// §3 DATA: SHOW POOL
//
// Special shows (5a5, pague15) live at the end of this array.
// They are gated by Paulo Araújo events, not regular rotation.
// ═══════════════════════════════════════════════════════════════════
function inferShowAudienceType(show) {
if (show?.typeAffinity && typeof show.typeAffinity === "object") {
return inferAudienceTypeFromAffinity(show.typeAffinity);
}
const id = show.id || "";
if (id.includes("corporativo") || id.includes("sindicato")) return "corporate";
if (id.includes("teatro") || id.includes("show-solo") || id.includes("programa-tv")) return "theater";
if (id.includes("universitario") || id.includes("republica")) return "young-chaotic";
if (id.includes("podcast") || id.includes("rooftop-tech") || id.includes("metro")) return "digital-urban";
if (id.includes("shopping") || id.includes("familia") || id.includes("churrascaria")) return "family";
return "mixed-room";
}
function inferAudienceTypeFromAffinity(typeAffinity) {
const safe = typeAffinity || {};
const fallback = (typeof safe.default === "number") ? safe.default : 0;
const limpo = (typeof safe.limpo === "number") ? safe.limpo : fallback;
const hack = (typeof safe.hack === "number") ? safe.hack : fallback;
const vulgar = (typeof safe.vulgar === "number") ? safe.vulgar : fallback;
const humorNegro = (typeof safe["humor negro"] === "number") ? safe["humor negro"] : fallback;
const besteirol = (typeof safe.besteirol === "number") ? safe.besteirol : fallback;
if (limpo >= 0.55 && vulgar <= -0.6) return "corporate";
if (limpo >= 0.55 && vulgar <= -0.25 && humorNegro <= -0.15) return "family";
if (hack >= 0.45 && limpo >= 0.1) return "digital-urban";
if (besteirol >= 0.45 && vulgar >= 0.2) return "young-chaotic";
if (humorNegro >= 0.25 && limpo >= 0.25 && vulgar <= 0.2) return "theater";
return "mixed-room";
}
function inferShowRiskProfile(show) {
if (show.difficulty >= 0.46) return "high";
if (show.difficulty >= 0.28) return "medium";
return "low";
}
function inferShowSocialExposure(show) {
const id = show.id || "";
if (id.includes("programa-tv")) return "high";
if (id.includes("podcast") || id.includes("rooftop-tech")) return "medium";
return "low";
}
function inferShowCareerStage(show) {
return show.requiresCareerStage || show.requiresLevel || "open";
}
function inferShowRewardProfile(show, stage) {
if (stage === "headliner") return "prestige";
if (stage === "elenco") return "consistency";
if (show.difficulty >= 0.38) return "high-variance";
return "learning";
}
function enrichShowWithCareerMetadata(show) {
const stage = inferShowCareerStage(show);
const audienceType = show.audienceType || inferShowAudienceType(show);
const politicoConfig = V2_PROGRESSION.politico || {};
const politicoAffinity = politicoConfig.venueOverrides?.[show.id]
?? politicoConfig.categoryAffinity?.[audienceType]
?? 0;
return {
...show,
typeAffinity: { ...(show.typeAffinity || {}), "político": politicoAffinity },
careerStage: stage,
audienceType,
setLengthTarget: show.setLengthTarget || show.minMinutes,
riskProfile: show.riskProfile || inferShowRiskProfile(show),
rewardProfile: show.rewardProfile || inferShowRewardProfile(show, stage),
socialExposure: show.socialExposure || inferShowSocialExposure(show)
};
}
const showPool = (GAME_CONTENT.world?.showPool || []).map(show => enrichShowWithCareerMetadata(show));
function findShowById(showId) {
return showPool.find((show) => show.id === showId);
}
function validateGameContent() {
const errors = [];
const classIds = V2_PROGRESSION.classOrder || [];
const allowedMetrics = new Set([
"texto", "entrega", "network", "fans", "studyCount", "writeCount", "rewriteCount",
"contentCount", "showsScheduledCount", "showsPerformedCount", "goodShowsCount",
"consecutiveGoodShows", "bigRoomShowsCount", "elencoGoodShowsCount", "averageNota", "levelNumber"
]);
const seen = new Set();
classIds.forEach(classId => {
if (seen.has(classId)) errors.push(`Classe duplicada: ${classId}`);
seen.add(classId);
const path = V2_PROGRESSION.classPaths?.[classId];
if (!path) errors.push(`Caminho ausente: ${classId}`);
[1, 2].forEach(phase => {
const event = V2_EVENTS.classEvents?.[`${classId}:event${phase}`];
if (!event) errors.push(`Conteúdo de evento ausente: ${classId}:event${phase}`);
if (event && event.kind !== "path") errors.push(`Evento de classe sem tipo path: ${event.id}`);
if (phase === 2 && (!event?.choiceGroup || (event.choices || []).length !== 2)) errors.push(`Event 2 sem bifurcação válida: ${classId}`);
Object.keys(path?.[`event${phase}`]?.requirements || {}).forEach(metric => {
if (!allowedMetrics.has(metric)) errors.push(`Métrica inválida: ${metric}`);
});
});
});
(V2_EVENTS.pathEvents || []).forEach(event => {
if (event.kind !== "path") errors.push(`Evento-chave sem tipo path: ${event.id}`);
if (!event.choiceGroup) errors.push(`Evento-chave sem choiceGroup: ${event.id}`);
Object.keys(event.requirements || {}).forEach(metric => {
if (!allowedMetrics.has(metric)) errors.push(`Métrica inválida: ${metric}`);
});
});
eventPool.forEach(event => {
if (event.kind !== "incidental" && event.kind !== "path") errors.push(`Tipo de evento inválido: ${event.id}`);
});
["base", "tone", "structure", "pure", "tier"].forEach(key => {
if (!V2_ENDINGS[key] || typeof V2_ENDINGS[key] !== "object") errors.push(`Catálogo de finais ausente: ${key}`);
});
if (!V2_ENDINGS.cliffhanger) errors.push("Cliffhanger final ausente");
if (errors.length) throw new Error(`Conteúdo V2 inválido:\n- ${errors.join("\n- ")}`);
deepFreezeContent(GAME_CONTENT);
return true;
}
function deepFreezeContent(value) {
if (!value || typeof value !== "object" || Object.isFrozen(value)) return value;
Object.values(value).forEach(deepFreezeContent);
return Object.freeze(value);
}
// ═══════════════════════════════════════════════════════════════════
// §4 DATA: EVENT POOL
// ═══════════════════════════════════════════════════════════════════
// ═══════════════════════════════════════════════════════════════════
// §5 VISUAL EFFECTS & ANIMATIONS
// ═══════════════════════════════════════════════════════════════════
// Inject CSS keyframes needed by JS-created elements
(function injectFxStyles() {
const s = document.createElement('style');
s.textContent = `
@keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } }
.ripple-effect {
position: absolute; border-radius: 50%;
background: rgba(255, 255, 255, 0.4);
animation: ripple 0.6s ease-out; pointer-events: none;
}
@keyframes ripple { from { transform: scale(0); opacity: 1; } to { transform: scale(4); opacity: 0; } }
`;
document.head.appendChild(s);
})();
const showText = (target, message, index, interval, callback, token = null) => {
if (index < message.length) {
const element = document.querySelector(target);
if (element) {
if (token !== null && token !== narrationRenderToken) return;
element.textContent = message.substring(0, index + 1);
}
setTimeout(() => showText(target, message, index + 1, interval, callback, token), interval);
} else if (callback) {
callback();
}
};
const animateElement = (element, animationClass, duration = 500) => {
element.classList.add(animationClass);
setTimeout(() => element.classList.remove(animationClass), duration);
};
const createRipple = (event, element) => {
const ripple = document.createElement('span');
ripple.classList.add('ripple-effect');
const rect = element.getBoundingClientRect();
const size = Math.max(rect.width, rect.height);
ripple.style.width = ripple.style.height = `${size}px`;
ripple.style.left = `${event.clientX - rect.left - size / 2}px`;
ripple.style.top = `${event.clientY - rect.top - size / 2}px`;
element.appendChild(ripple);
setTimeout(() => ripple.remove(), 600);
};
const spawnConfetti = (count = 30) => {
const container = document.getElementById('confettiContainer');
if (!container) return;
for (let i = 0; i < count; i++) {
setTimeout(() => {
const confetti = document.createElement('div');
confetti.classList.add('confetti');
confetti.style.left = `${Math.random() * 100}%`;
confetti.style.top = `${50 + Math.random() * 30}%`;
confetti.style.backgroundColor = confettiColors[Math.floor(Math.random() * confettiColors.length)];
confetti.style.transform = `rotate(${Math.random() * 360}deg)`;
confetti.style.borderRadius = Math.random() > 0.5 ? '50%' : '0';
container.appendChild(confetti);
setTimeout(() => confetti.remove(), 1500);
}, i * 40);
}
};
const animateStatChange = (statName, isPositive = true) => {
const statElement = document.querySelector(`[data-stat="${statName}"]`);
if (statElement) {
statElement.classList.add('stat-updated');
statElement.style.setProperty('--stat-color', isPositive ? 'var(--neon-cyan)' : 'var(--neon-pink)');
setTimeout(() => statElement.classList.remove('stat-updated'), 500);
}
};
const animateNumber = (element, start, end, duration = 500) => {
const startTime = performance.now();
const diff = end - start;
const animate = (currentTime) => {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const easeProgress = 1 - Math.pow(1 - progress, 3);
element.textContent = Math.round(start + diff * easeProgress);
if (progress < 1) requestAnimationFrame(animate);
};
requestAnimationFrame(animate);
};
const shakeScreen = () => {
const game = document.getElementById('game');
game.style.animation = 'shake 0.5s ease';
setTimeout(() => { game.style.animation = ''; }, 500);
};
const flashScreen = (color = 'rgba(212, 168, 75, 0.25)') => {
const flash = document.createElement('div');
flash.style.cssText = `
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: ${color}; pointer-events: none; z-index: 9999;
animation: fadeOut 0.25s ease forwards;
`;
document.body.appendChild(flash);
setTimeout(() => flash.remove(), 250);
};
// ═══════════════════════════════════════════════════════════════════
// §6 SOUND SYSTEM
// ═══════════════════════════════════════════════════════════════════
const sounds = {
click: new Audio('pokemonsoundeffects/click.wav'),
save: new Audio('pokemonsoundeffects/save.wav'),
getSomething: new Audio('pokemonsoundeffects/get something.wav'),
victory: new Audio('pokemonsoundeffects/victory1.wav'),
boom: new Audio('pokemonsoundeffects/boom.wav'),
menu: new Audio('pokemonsoundeffects/menu.wav'),
pokeball: new Audio('pokemonsoundeffects/pokeball.wav'),
findSomething: new Audio('pokemonsoundeffects/find something.wav'),
comeWithMe: new Audio('pokemonsoundeffects/come with me.wav')
};
Object.values(sounds).forEach(sound => { sound.volume = 0.3; sound.load(); });
function playSound(soundName) {
if (sounds[soundName]) {
sounds[soundName].currentTime = 0;
sounds[soundName].play().catch(e => console.log('Audio play failed:', e));
}
}
// ═══════════════════════════════════════════════════════════════════
// §7 STATE & GLOBALS
// ═══════════════════════════════════════════════════════════════════
let state;
let currentShow = null;
let uiMode = "idle";
let introStep = 0;
let activeEvent = null;
let pendingEvent = null;
let lastLevelLabel = null;
let dialogTimeout = null;
const selectedJokeIds = new Set();
const criticalDialogQueue = [];
let suspendCriticalDialogs = false;
const deferredCriticalDialogs = [];
let narrationRenderToken = 0;
let sceneRenderToken = 0;
// Stat animation tracking
let previousStats = { fans: 0, motivation: 60, texto: 10, entrega: 5, stageTime: 0, xp: 0 };
let lastLevelNumber = null;
// Joke creation temporaries (kept module-level instead of polluting window)
let _pendingJokeIdea = null;
let _pendingJokeMode = null;
let _selectedTone = null;
let _selectedStructure = null;
let _customJokeTitle = null;
let _rewritingJoke = null;
let _newTone = null;
let _newStructure = null;
// ═══════════════════════════════════════════════════════════════════
// §8 HELPERS & UTILITIES
// ═══════════════════════════════════════════════════════════════════
const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
const formatSigned = (value) => (value > 0 ? `+${value}` : `${value}`);
const formatIdeaTitle = (idea) => idea.customTitle || `Piada sobre ${idea.seed}`;
const generatePotential = () => parseFloat((0.35 + Math.random() * 0.5).toFixed(2));
const CAREER_STAGES = ["open", "elenco"];
const VENUE_REPUTATION_MIN = -20;
const VENUE_REPUTATION_MAX = 40;
function resolveCareerStage(level = state?.level, levelNumber = state?.levelNumber) {
if (level === "elenco" || (typeof levelNumber === "number" && levelNumber >= 6)) return "elenco";
return "open";
}
function getCareerStage() {
return resolveCareerStage(state?.level, state?.levelNumber);
}
function getProfileTitle() {
if (!state) return "Comediante em formação";
if (state.chosenClass && CLASSES[state.chosenClass]) return CLASSES[state.chosenClass].name;
const stage = getCareerStage();
if (stage === "elenco") return "Em circuito";
if ((state.levelNumber || 1) >= 3) return "Em ascensão";
return "Comediante em formação";
}
function getProfileBadges() {
if (!state) return [];
const badges = [];
if (state.chosenClass && CLASSES[state.chosenClass]) {
badges.push({ label: `💼 ${CLASSES[state.chosenClass].name}`, kind: "career" });
} else {
const stage = getCareerStage();
badges.push({
label: stage === "elenco" ? "🎬 Elenco" : "🌱 Open Mic",
kind: "career"
});
}
if (state.storytellingUnlocked) badges.push(PROFILE_BADGE_LABELS.storytellingUnlocked);
if (state.fiveA5Unlocked) badges.push(PROFILE_BADGE_LABELS.fiveA5Unlocked);
if (state.seViraNos5Unlocked) badges.push(PROFILE_BADGE_LABELS.seViraNos5Unlocked);
if (state.pague15Unlocked) badges.push(PROFILE_BADGE_LABELS.pague15Unlocked);
const visiblePerks = Array.isArray(state.unlockedPerks)
? state.unlockedPerks
.map((perkId) => ({ perkId, badge: PROFILE_BADGE_LABELS[perkId] }))
.filter((entry) => !!entry.badge)
.map((entry) => entry.badge)
: [];
badges.push(...visiblePerks);
return badges.slice(0, 6);
}
function renderProfileBadges() {
if (!elements.profile?.title || !elements.profile?.badges) return;
elements.profile.title.textContent = getProfileTitle();
const badges = getProfileBadges();
const visibleBadges = badges.slice(0, 5);
const overflow = Math.max(0, badges.length - visibleBadges.length);
const badgeMarkup = visibleBadges.map((badge) => `<span class="profile-badge profile-badge-${badge.kind || "perk"}">${badge.label}</span>`).join("");
const overflowMarkup = overflow > 0 ? `<span class="profile-badge profile-badge-overflow">+${overflow}</span>` : "";
elements.profile.badges.innerHTML = `${badgeMarkup}${overflowMarkup}`;
}
function getCareerStageIndex(stage) {
if (stage === "headliner") return 2;
const index = CAREER_STAGES.indexOf(stage);
return index === -1 ? 0 : index;
}
function isCareerStageAtLeast(stage, targetStage) {
return getCareerStageIndex(stage) >= getCareerStageIndex(targetStage);
}
function createDefaultCareerMilestones() {
return {
firstShow: false,
firstStudy: false,
firstRewrite: false,
firstBomb: false,
firstKill: false,
jokes10: false,
firstConsistencyStreak: false,
firstTexto15: false,
firstElencoGig: false,
firstHeadlinerGig: false,
firstSoloGig: false
};
}
function createDefaultRouteCounters() {
return {
studyCount: 0,
writeCount: 0,
rewriteCount: 0,
contentCount: 0,
showsScheduledCount: 0
};
}
function createDefaultRunState(existing = {}) {
return {
runId: typeof existing.runId === "string" && existing.runId ? existing.runId : createId(),
status: existing.status === "ended" ? "ended" : "active",
ruleset: "v2",
endingId: existing.endingId || null,
pureEndingId: existing.pureEndingId || null,
specialEndingId: existing.specialEndingId || null,
endingClassId: existing.endingClassId || null,
endingArtId: existing.endingArtId || null,
dominantStructure: existing.dominantStructure || null,
endingTier: existing.endingTier || null,
endingScore: Number.isFinite(existing.endingScore) ? existing.endingScore : null,
endedDay: Number.isFinite(existing.endedDay) ? existing.endedDay : null,
archived: !!existing.archived
};
}
function createDefaultCareerPathState(existing = {}) {
const normalizePhaseMap = (source = {}) => Object.fromEntries(
(V2_PROGRESSION.classOrder || []).map(classId => {
const value = source[classId] || {};
const validStatus = ["unseen", "pending", "accepted", "declined", "completed"].includes(value.status) ? value.status : "unseen";
return [classId, {
status: validStatus,
completedDay: Number.isFinite(value.completedDay) ? value.completedDay : null
}];
})
);
return {
event1ByClass: normalizePhaseMap(existing.event1ByClass),
event2ByClass: normalizePhaseMap(existing.event2ByClass),
lockedPathId: V2_PROGRESSION.classPaths?.[existing.lockedPathId] ? existing.lockedPathId : null,
detectedClassId: V2_PROGRESSION.classPaths?.[existing.detectedClassId] ? existing.detectedClassId : null,
classAssignedDay: Number.isFinite(existing.classAssignedDay) ? existing.classAssignedDay : null,
goodShowsCount: Math.max(0, Math.round(existing.goodShowsCount || 0)),
bigRoomShowsCount: Math.max(0, Math.round(existing.bigRoomShowsCount || 0)),
elencoGoodShowsCount: Math.max(0, Math.round(existing.elencoGoodShowsCount || 0)),
employmentDeclinedUntil: Math.max(0, Math.round(existing.employmentDeclinedUntil || 0)),
employmentOfferPending: !!existing.employmentOfferPending,
activeTimeAdvance: normalizeCareerEventTimeAdvance(existing.activeTimeAdvance)
};
}
function normalizeCareerEventTimeAdvance(existing) {
if (!existing || typeof existing !== "object") return null;
const classId = V2_PROGRESSION.classPaths?.[existing.classId] ? existing.classId : null;
const phase = existing.phase === 2 ? 2 : existing.phase === 1 ? 1 : null;
if (!classId || !phase) return null;
return {
classId,
phase,
remainingDays: Math.max(0, Math.round(existing.remainingDays || 0)),
totalDays: Math.max(0, Math.round(existing.totalDays || 0)),
branchChoiceId: typeof existing.branchChoiceId === "string" ? existing.branchChoiceId : null
};
}
function createDefaultPathProgressState(existing = {}) {
const normalizeChoice = (value) => {
if (!value || typeof value !== "object" || !value.choiceId) return null;
return {
eventId: typeof value.eventId === "string" ? value.eventId : null,
choiceId: String(value.choiceId),
day: Number.isFinite(value.day) ? value.day : null,
specialization: typeof value.specialization === "string" ? value.specialization : null,
late: !!value.late
};
};
return {
flags: existing.flags && typeof existing.flags === "object" ? { ...existing.flags } : {},
choiceGroups: Object.fromEntries(
Object.entries(existing.choiceGroups || {})
.map(([groupId, value]) => [groupId, normalizeChoice(value)])
.filter(([, value]) => !!value)
),
completedEventIds: Array.isArray(existing.completedEventIds)
? [...new Set(existing.completedEventIds.filter(Boolean))]
: [],
pendingEventId: typeof existing.pendingEventId === "string" ? existing.pendingEventId : null
};
}
function createDefaultEventRuntime(existing = {}) {
return {
seenIds: Array.isArray(existing.seenIds) ? [...new Set(existing.seenIds.filter(Boolean))] : [],
cooldownUntilById: existing.cooldownUntilById && typeof existing.cooldownUntilById === "object" ? { ...existing.cooldownUntilById } : {},
pendingIds: Array.isArray(existing.pendingIds) ? existing.pendingIds.filter(Boolean) : [],
activeEventId: typeof existing.activeEventId === "string" ? existing.activeEventId : null
};
}
function seedCareerPathCountersFromHistory(pathState, history = []) {
if (!Array.isArray(history)) return pathState;
if (!pathState.goodShowsCount) pathState.goodShowsCount = history.filter(entry => entry.nota >= 4).length;
if (!pathState.bigRoomShowsCount) {
pathState.bigRoomShowsCount = history.filter(entry => {
const show = findShowById(entry.showId);
return (show?.minMinutes || 0) >= 7 || !!show?.isElencoCircuit;
}).length;
}
if (!pathState.elencoGoodShowsCount) {
pathState.elencoGoodShowsCount = history.filter(entry => findShowById(entry.showId)?.isElencoCircuit && entry.nota >= 4).length;
}
return pathState;
}
function createDefaultRouteInviteState() {
return {
cincoPiadas: { pending: false, nextOfferDay: 1 },
joaoValioSeVira: { pending: false, nextOfferDay: 1 },
pauloAraujoPague15: { pending: false, nextOfferDay: 1 },
joaoValioBlackHouseElenco: { pending: false, nextOfferDay: 1 }
};
}
function normalizeRouteInviteState(routeInviteState = {}) {
return Object.fromEntries(
Object.entries(createDefaultRouteInviteState()).map(([key, defaults]) => {
const raw = routeInviteState?.[key] || {};
return [key, {
pending: !!raw.pending,
nextOfferDay: Math.max(1, Math.round(raw.nextOfferDay || defaults.nextOfferDay || 1))
}];
})
);
}
function normalizeRouteCounters(counters = {}) {
return Object.fromEntries(
Object.entries(createDefaultRouteCounters()).map(([key, defaultValue]) => {
const value = Number(counters[key] ?? defaultValue);
return [key, Number.isFinite(value) ? Math.max(0, Math.round(value)) : defaultValue];
})
);
}
function incrementRouteCounter(counterKey, amount = 1) {
state.routeCounters = normalizeRouteCounters(state.routeCounters);
if (!(counterKey in state.routeCounters)) return;
state.routeCounters[counterKey] += Math.max(0, Math.round(amount || 0));
}
function createDefaultToneTally() {
return { besteirol: 0, vulgar: 0, limpo: 0, "humor negro": 0, hack: 0, "político": 0 };
}
function createDefaultStructureTally() {
return { bit: 0, oneliner: 0, storytelling: 0, prop: 0, crowdWork: 0 };
}
function normalizeStructureTally(tally = {}) {
return Object.fromEntries(
Object.entries(createDefaultStructureTally()).map(([structure, defaultValue]) => {
const value = Number(tally?.[structure] ?? defaultValue);
return [structure, Number.isFinite(value) ? Math.max(0, Math.round(value)) : defaultValue];
})
);
}
function normalizeToneTally(tally = {}) {
return Object.fromEntries(
Object.entries(createDefaultToneTally()).map(([tone, defaultValue]) => {
const value = Number(tally?.[tone] ?? defaultValue);
return [tone, Number.isFinite(value) ? Math.max(0, Math.round(value)) : defaultValue];
})
);
}
function tallyPerformedTones(setList = []) {
state.toneTally = normalizeToneTally(state.toneTally);
setList.forEach(joke => {
if (joke?.tone in state.toneTally) state.toneTally[joke.tone] += 1;
});
}
function tallyPerformedStructures(setList = [], crowdWorkMinutes = 0) {
state.structureTally = normalizeStructureTally(state.structureTally);
setList.forEach(joke => {
if (joke?.structure in state.structureTally) {
state.structureTally[joke.structure] += Math.max(1, Math.round(joke.minutes || 1));
}
});
state.structureTally.crowdWork += Math.max(0, Math.round(crowdWorkMinutes || 0));
}
function ensureCareerProgressState() {
if (!state) return;
if (state.chosenClass === "professor") state.chosenClass = "comicoClassico";
state.careerMilestones = { ...createDefaultCareerMilestones(), ...(state.careerMilestones || {}) };
state.routeCounters = normalizeRouteCounters(state.routeCounters);
state.runState = createDefaultRunState(state.runState);
state.careerPathState = seedCareerPathCountersFromHistory(createDefaultCareerPathState(state.careerPathState), state.showHistory);
state.pathProgressState = createDefaultPathProgressState(state.pathProgressState);
state.eventRuntime = createDefaultEventRuntime(state.eventRuntime);
state.eventRuntime.seenIds = [...new Set([...(state.eventRuntime.seenIds || []), ...(state.eventsSeen || [])])];
state.routeInviteState = normalizeRouteInviteState(state.routeInviteState);
state.careerChoices = state.careerChoices || [];
state.carvalhoDialogState = {
shownIds: Array.isArray(state.carvalhoDialogState?.shownIds) ? state.carvalhoDialogState.shownIds : [],
triggerCooldowns: state.carvalhoDialogState?.triggerCooldowns || {}
};
state.elencoCircuitState = {
weeklyGoalTarget: Math.max(2, state.elencoCircuitState?.weeklyGoalTarget || 2),
weeklyGoalProgress: Math.max(0, state.elencoCircuitState?.weeklyGoalProgress || 0),
completedWeek: state.elencoCircuitState?.completedWeek || null,
weeklySuccessStreak: Math.max(0, state.elencoCircuitState?.weeklySuccessStreak || 0),
bestWeeklyStreak: Math.max(0, state.elencoCircuitState?.bestWeeklyStreak || 0)
};
state.openStageState = {
consistencyStreak: Math.max(0, state.openStageState?.consistencyStreak || 0),
breakthroughs: Math.max(0, state.openStageState?.breakthroughs || 0)
};
state.onelinerUnlocked = !!state.onelinerUnlocked;
state.humorNegroUnlocked = !!state.humorNegroUnlocked;
state.hackUnlocked = !!state.hackUnlocked;
state.propUnlocked = !!state.propUnlocked;
state.politicoUnlocked = !!state.politicoUnlocked;
state.toneTally = normalizeToneTally(state.toneTally);
state.structureTally = normalizeStructureTally(state.structureTally);
state.venueReputation = normalizeVenueReputationMap(state.venueReputation);
}
function isRouteInviteEvent(eventOrId) {
const eventId = typeof eventOrId === "string" ? eventOrId : eventOrId?.id;
return eventId === "cincoPiadas" || eventId === "joaoValioSeVira" || eventId === "pauloAraujoPague15" || eventId === "joaoValioBlackHouseElenco";
}
function canRouteInviteAppearNow(eventId) {
if (!state) return false;
const inviteState = state.routeInviteState?.[eventId];
if (!inviteState?.pending) return false;
if ((state.currentDay || 1) < (inviteState.nextOfferDay || 1)) return false;
if (!Array.isArray(state.showHistory) || state.showHistory.length === 0) return false;
return true;
}
function refreshRouteInviteAvailability(source = "system") {
if (!state || !Array.isArray(eventPool)) return;
ensureCareerProgressState();
if (!state.fiveA5Unlocked && !state.eventsSeen.includes("cincoPiadas") && Array.isArray(state.jokes) && state.jokes.length >= 5) {
state.routeInviteState.cincoPiadas.pending = true;
}
const bestFiveA5 = Math.max(0, ...(state.showHistory || []).filter(entry => entry.showId === "5a5").map(entry => entry.nota || 0));
if (!state.seViraNos5Unlocked && !state.eventsSeen.includes("joaoValioSeVira") && bestFiveA5 >= 3) {
state.routeInviteState.joaoValioSeVira.pending = true;
}
if (!state.pague15Unlocked && !state.eventsSeen.includes("pauloAraujoPague15") && (state.shows5a5AtLevel4 || 0) >= 3) {
state.routeInviteState.pauloAraujoPague15.pending = true;
}
const bestSeViraNos5 = Math.max(0, ...(state.showHistory || []).filter(entry => entry.showId === "se-vira-nos-5").map(entry => entry.nota || 0));
if (getCareerStage() === "elenco" && !state.blackHouseElencoUnlocked && !state.eventsSeen.includes("joaoValioBlackHouseElenco") && bestSeViraNos5 >= 4) {
state.routeInviteState.joaoValioBlackHouseElenco.pending = true;
}
if (activeEvent || pendingEvent) return;
const routeInviteOrder = ["cincoPiadas", "joaoValioSeVira", "pauloAraujoPague15", "joaoValioBlackHouseElenco"];
for (const eventId of routeInviteOrder) {
if (!canRouteInviteAppearNow(eventId)) continue;
const event = eventPool.find((entry) => entry.id === eventId);
if (!event) continue;
if (source === "newDay") {
showEvent(event);
} else {
pendingEvent = event;
}
break;
}
}
function hasCareerMilestone(milestoneId) {
return !!(state?.careerMilestones && state.careerMilestones[milestoneId]);
}
function markCareerMilestone(milestoneId) {
ensureCareerProgressState();
if (!state.careerMilestones[milestoneId]) {
state.careerMilestones[milestoneId] = true;
return true;
}
return false;
}
const contentGates = {
showEligible(show, stage = getCareerStage()) {
if (!show) return false;
const requiredStage = show.requiresCareerStage || show.requiresLevel || "open";
return isCareerStageAtLeast(stage, requiredStage);
},
eventEligible(event, stage = getCareerStage()) {
if (!event) return false;
const requiredStage = event.requiresCareerStage || event.requiresLevel || "open";
return isCareerStageAtLeast(stage, requiredStage);
},
dialogEligible(dialog, stage = getCareerStage()) {
if (!dialog) return false;
const requiredStage = dialog.requiresCareerStage || "open";
return isCareerStageAtLeast(stage, requiredStage);
}
};
function isShowUnlockedForCareer(show) {
if (!show || !state) return false;
if (show.isHeadlinerSoloPipeline || show.isSpecialTapeShow || show.requiresCareerStage === "headliner") return false;
if (show.requiresAvatar && !show.requiresAvatar.includes(state.avatar)) return false;
if (show.requiresEmployment && !state.hasEmployment) return false;
if (show.requiresBlackHouseElenco && !state.blackHouseElencoUnlocked) return false;