-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3mt.html
More file actions
1054 lines (923 loc) · 52.2 KB
/
Copy path3mt.html
File metadata and controls
1054 lines (923 loc) · 52.2 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hedonic Game</title>
<script src="https://cdn.tailwindcss.com"></script>
<!-- Include p5.js and the Matter.js physics engine -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.9.0/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Inter', sans-serif;
touch-action: manipulation;
}
#canvas-container canvas {
display: block;
margin: auto;
}
.message-box {
transition: opacity 0.5s, transform 0.5s;
}
.control-btn {
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.25rem;
line-height: 1;
}
/* Custom Slider Styles */
#resolution-slider {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 8px;
/* The background is now set dynamically by JavaScript */
border-radius: 9999px;
outline: none;
opacity: 0.9;
transition: opacity .2s;
}
#resolution-slider:hover {
opacity: 1;
}
#resolution-slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 24px;
height: 24px;
background: #cbd5e1; /* slate-300 */
cursor: pointer;
border-radius: 50%;
border: 3px solid #475569; /* slate-600 */
}
#resolution-slider::-moz-range-thumb {
width: 24px;
height: 24px;
background: #cbd5e1;
cursor: pointer;
border-radius: 50%;
border: 3px solid #475569;
}
/* New Custom Tooltip Style */
.tooltip {
position: fixed;
padding: 20px 24px;
background-color: #111827; /* gray-900 */
color: #d1d5db; /* gray-300 */
border-radius: 8px;
border: 1px solid #374151; /* gray-700 */
font-size: 1.125rem;
line-height: 1.6rem;
pointer-events: none;
opacity: 0;
transition: opacity 0.2s;
z-index: 50;
/* max-width removed to allow the tooltip to expand with its content */
}
</style>
</head>
<body class="bg-[#1B1C1D] text-gray-300 flex flex-col min-h-screen items-center justify-center p-4">
<div class="w-full max-w-2xl mx-auto">
<!-- Language Selector -->
<div class="absolute top-4 right-4">
<select id="language-selector" class="bg-gray-700 text-white text-sm rounded-md p-1 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500">
<option value="en">English</option>
<option value="pt-BR">Português (Brasil)</option>
</select>
</div>
<h1 data-translate="title" class="text-3xl font-bold text-center text-gray-200 mb-2">Hedonic Game</h1>
<p data-translate="subtitle" class="text-center text-gray-400 mb-4">Resolve frustration in community detection</p>
<!-- NEW Controls Layout -->
<div class="flex items-start justify-center gap-4 mb-8">
<!-- Left Pan Controls -->
<div class="bg-gray-900 p-4 rounded-xl shadow-lg flex-1 space-y-3">
<div class="flex items-center justify-between">
<div class="flex items-center space-x-3">
<div class="flex items-center space-x-1.5" data-translate-tooltip="tooltipFriends">
<span data-translate="friends" class="font-medium text-blue-400 text-sm w-16 cursor-help">Friends</span>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="text-gray-500"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>
</div>
<span id="control-left-friends-count" class="font-bold text-lg text-blue-400 w-8 text-center">0</span>
</div>
<div class="flex items-center space-x-2">
<button id="remove-left-friend-btn" class="control-btn bg-gray-700 text-white font-bold rounded-full hover:bg-gray-600 transition">-</button>
<button id="add-left-friend-btn" class="control-btn bg-blue-600 text-white font-bold rounded-full hover:bg-blue-700 transition">+</button>
</div>
</div>
<div class="flex items-center justify-between">
<div class="flex items-center space-x-3">
<div class="flex items-center space-x-1.5" data-translate-tooltip="tooltipFoes">
<span data-translate="foes" class="font-medium text-red-400 text-sm w-16 cursor-help">Foes</span>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="text-gray-500"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>
</div>
<span id="control-left-foes-count" class="font-bold text-lg text-red-400 w-8 text-center">0</span>
</div>
<div class="flex items-center space-x-2">
<button id="remove-left-foe-btn" class="control-btn bg-gray-700 text-white font-bold rounded-full hover:bg-gray-600 transition">-</button>
<button id="add-left-foe-btn" class="control-btn bg-red-600 text-white font-bold rounded-full hover:bg-red-700 transition">+</button>
</div>
</div>
<div class="flex items-center justify-between pt-2 border-t border-gray-700/50">
<div class="flex items-center space-x-1.5" data-translate-tooltip="tooltipWeight">
<span data-translate="weight" class="font-medium text-green-400 text-sm cursor-help">Weight</span>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="text-gray-500"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>
</div>
<div class="flex items-center space-x-2 text-right">
<span id="control-left-pan-formula" class="font-mono text-gray-400 text-xs whitespace-nowrap"></span>
<span class="text-gray-400 font-semibold">=</span>
<span id="control-left-pan-weight" class="font-bold text-lg text-green-400 w-14 text-right">0.00</span>
</div>
</div>
</div>
<!-- Central Reset Button -->
<div class="flex-shrink-0 pt-8">
<button id="reset-btn" class="p-2 rounded-full text-gray-500 hover:text-blue-400 hover:bg-gray-700 transition" data-translate-title="resetTitle">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M1 4v6h6"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/>
</svg>
</button>
</div>
<!-- Right Pan Controls -->
<div class="bg-gray-900 p-4 rounded-xl shadow-lg flex-1 space-y-3">
<div class="flex items-center justify-between">
<div class="flex items-center space-x-3">
<div class="flex items-center space-x-1.5" data-translate-tooltip="tooltipFriends">
<span data-translate="friends" class="font-medium text-blue-400 text-sm w-16 cursor-help">Friends</span>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="text-gray-500"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>
</div>
<span id="control-right-friends-count" class="font-bold text-lg text-blue-400 w-8 text-center">0</span>
</div>
<div class="flex items-center space-x-2">
<button id="remove-right-friend-btn" class="control-btn bg-gray-700 text-white font-bold rounded-full hover:bg-gray-600 transition">-</button>
<button id="add-right-friend-btn" class="control-btn bg-blue-600 text-white font-bold rounded-full hover:bg-blue-700 transition">+</button>
</div>
</div>
<div class="flex items-center justify-between">
<div class="flex items-center space-x-3">
<div class="flex items-center space-x-1.5" data-translate-tooltip="tooltipFoes">
<span data-translate="foes" class="font-medium text-red-400 text-sm w-16 cursor-help">Foes</span>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="text-gray-500"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>
</div>
<span id="control-right-foes-count" class="font-bold text-lg text-red-400 w-8 text-center">0</span>
</div>
<div class="flex items-center space-x-2">
<button id="remove-right-foe-btn" class="control-btn bg-gray-700 text-white font-bold rounded-full hover:bg-gray-600 transition">-</button>
<button id="add-right-foe-btn" class="control-btn bg-red-600 text-white font-bold rounded-full hover:bg-red-700 transition">+</button>
</div>
</div>
<div class="flex items-center justify-between pt-2 border-t border-gray-700/50">
<div class="flex items-center space-x-1.5" data-translate-tooltip="tooltipWeight">
<span data-translate="weight" class="font-medium text-green-400 text-sm cursor-help">Weight</span>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="text-gray-500"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>
</div>
<div class="flex items-center space-x-2 text-right">
<span id="control-right-pan-formula" class="font-mono text-gray-400 text-xs whitespace-nowrap"></span>
<span class="text-gray-400 font-semibold">=</span>
<span id="control-right-pan-weight" class="font-bold text-lg text-green-400 w-14 text-right">0.00</span>
</div>
</div>
</div>
</div>
<!-- The Canvas Container for p5.js -->
<div id="canvas-container" class="relative h-[400px]"></div>
<!-- Resolution & Familiarity Index -->
<div id="resolution-slider-container" class="mt-8 bg-gray-800 p-4 rounded-lg">
<div class="flex justify-between items-center text-sm text-gray-400 mb-3">
<div class="flex-1 text-left">
<span data-translate="profitPerFriend" class="whitespace-nowrap">Profit per Friend (1-r): </span><span id="profit-value" class="font-bold text-blue-400">0.50</span>
</div>
<div class="flex-shrink-0">
<p data-translate="resolution" class="text-lg font-medium text-gray-400 text-center">Resolution</p>
</div>
<div class="flex-1 text-right">
<span data-translate="costPerFoe" class="whitespace-nowrap ml-4">Cost per Foe (r): </span><span id="cost-value" class="font-bold text-red-400">0.50</span>
</div>
</div>
<div class="flex justify-center mb-3">
<button id="magnet-toggle-btn" class="p-1 rounded-full text-gray-500 hover:text-blue-400 hover:bg-gray-700 transition" data-translate-title="magnetTitle">
<svg id="magnet-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M19 20v-5a7 7 0 1 0-14 0v5"></path><path d="M5 20h4"></path><path d="M15 20h4"></path>
</svg>
</button>
</div>
<div class="relative w-full h-6 flex items-center">
<!-- Brackets Container -->
<div class="absolute top-[-16px] left-0 w-full h-4 pointer-events-none flex">
<svg id="cost-bracket-svg" class="h-full text-red-400" preserveAspectRatio="none" viewBox="0 0 100 15">
<path d="M0,15 Q50,0 100,15" stroke="currentColor" stroke-width="1.5" fill="none" vector-effect="non-scaling-stroke"></path>
</svg>
<svg id="profit-bracket-svg" class="h-full text-blue-400" preserveAspectRatio="none" viewBox="0 0 100 15">
<path d="M0,15 Q50,0 100,15" stroke="currentColor" stroke-width="1.5" fill="none" vector-effect="non-scaling-stroke"></path>
</svg>
</div>
<!-- Arc Labels Container -->
<div class="absolute top-[-40px] left-0 w-full h-8 pointer-events-none flex">
<!-- Cost Label (Red Arc) -->
<div id="cost-arc-label" class="absolute top-0 text-xs font-medium text-red-400 bg-gray-900 px-2 py-1 rounded border border-red-400/30 transition-all duration-300">
Cost (r)
</div>
<!-- Profit Label (Blue Arc) -->
<div id="profit-arc-label" class="absolute top-0 text-xs font-medium text-blue-400 bg-gray-900 px-2 py-1 rounded border border-blue-400/30 transition-all duration-300">
Profit (1-r)
</div>
</div>
<input type="range" id="resolution-slider" min="0" max="1" step="0.01" value="0.5">
<div id="familiarity-marker" class="absolute top-1/2 w-4 h-4 bg-teal-400 rounded-full -translate-y-1/2 -translate-x-1/2 pointer-events-none hidden ring-2 ring-gray-900 shadow-lg"></div>
</div>
<div class="flex justify-between text-xs text-gray-400 mt-1 px-1">
<span>0.0</span>
<span>1.0</span>
</div>
<!-- NEW Familiarity Index Section -->
<div class="relative mt-2 pt-0 h-16 text-center">
<!-- This container holds all the dynamic elements and moves left/right -->
<div id="familiarity-dynamic-container" class="absolute top-2 left-1/2 -translate-x-1/2 transition-all duration-300 hidden flex flex-col items-center">
<!-- Pointer Triangle -->
<div class="w-0 h-0" style="border-left: 6px solid transparent; border-right: 6px solid transparent; border-bottom: 8px solid #2dd4bf;"></div>
<!-- Value (now below pointer) -->
<div id="familiarity-index-value" class="mt-1 font-bold text-teal-400 text-base whitespace-nowrap">0.000</div>
<!-- Title with Tooltip (now below value) -->
<div class="mt-1 flex items-center space-x-1 whitespace-nowrap" data-translate-tooltip="tooltipFamiliarity">
<span data-translate="familiarityIndex" class="text-xs text-gray-400 cursor-help">Familiarity Index</span>
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="text-gray-500"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>
</div>
</div>
</div>
</div>
</div>
<!-- Message Box for notifications -->
<div id="message-box" class="message-box fixed top-5 right-5 bg-green-500 text-white px-6 py-3 rounded-lg shadow-xl opacity-0 translate-y-4 pointer-events-none">
Message
</div>
<!-- The new custom tooltip element -->
<div id="tooltip" class="tooltip"></div>
<script>
// Configure MathJax
window.MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
displayMath: [['$$', '$$'], ['\\[', '\\]']]
},
options: {
skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre']
}
};
// --- Translation Data ---
const translations = {
'en': {
title: 'Hedonic Game',
subtitle: 'Resolve frustration in community detection',
friends: 'Friends',
foes: 'Foes',
weight: 'Weight',
resetTitle: 'Reset Scale',
resolution: 'Resolution',
profitPerFriend: 'Profit per Friend (1-r): ',
costPerFoe: 'Cost per Foe (r): ',
magnetTitle: 'Toggle Magnet Mode',
familiarityIndex: 'Familiarity Index',
tooltipFriends: 'Number of connections in community.',
tooltipFoes: 'Number of non-connections in community.',
tooltipWeight: 'The hedonic value in the community. Calculated as: (Friends × Profit) - (Foes × Cost)',
tooltipFamiliarity: '$\\dfrac{\\text{rightFriends} \\, - \\, \\text{leftFriends}}{\\left(\\text{rightFriends} \\, - \\, \\text{leftFriends}\\right) \\, + \\, \\left(\\text{rightFoes} \\, - \\, \\text{leftFoes}\\right)}$',
msgReset: 'Scale has been reset.',
msgMagnetOn: 'Magnet mode enabled.',
msgMagnetOff: 'Magnet mode disabled.',
legendAngel: 'Social preference\ntowards more friends',
legendDevil: 'Antisocial preference\ntowards fewer foes'
},
'pt-BR': {
title: 'Jogo Hedônico',
subtitle: 'Resolva a frustração na detecção de comunidades',
friends: 'Amigos',
foes: 'Desafetos',
weight: 'Peso',
resetTitle: 'Resetar Balança',
resolution: 'Resolução',
profitPerFriend: 'Lucro por Amigo (1-r): ',
costPerFoe: 'Custo por Desafeto (r): ',
magnetTitle: 'Ativar/Desativar Modo Ímã',
familiarityIndex: 'Índice de Familiaridade',
tooltipFriends: 'Número de conexões na comunidade.',
tooltipFoes: 'Número de não-conexões na comunidade.',
tooltipWeight: 'O valor hedônico na comunidade. Calculado como: (Amigos × Lucro) - (Desafetos × Custo)',
tooltipFamiliarity: '$\\dfrac{\\text{AmigosDireita} \\, - \\, \\text{AmigosEsquerda}}{\\left(\\text{AmigosDireita} \\, - \\, \\text{AmigosEsquerda}\\right) \\, + \\, \\left(\\text{DesafetosDireita} \\, - \\, \\text{DesafetosEsquerda}\\right)}$',
msgReset: 'Balança resetada.',
msgMagnetOn: 'Modo ímã ativado.',
msgMagnetOff: 'Modo ímã desativado.',
legendAngel: 'Preferência social\npor mais amigos',
legendDevil: 'Preferência antissocial\npor menos desafetos'
}
};
let currentLanguage = 'en';
// --- Global State & HTML References ---
let leftTotalWeight = 0;
let rightTotalWeight = 0;
let leftFriends = 0;
let leftFoes = 0;
let rightFriends = 0;
let rightFoes = 0;
let resolution = 0.5;
let magnetModeEnabled = false;
// Control Count displays
const controlLeftFriendsEl = document.getElementById('control-left-friends-count');
const controlLeftFoesEl = document.getElementById('control-left-foes-count');
const controlRightFriendsEl = document.getElementById('control-right-friends-count');
const controlRightFoesEl = document.getElementById('control-right-foes-count');
// Weight displays
const controlLeftPanWeightEl = document.getElementById('control-left-pan-weight');
const controlRightPanWeightEl = document.getElementById('control-right-pan-weight');
const controlLeftPanFormulaEl = document.getElementById('control-left-pan-formula');
const controlRightPanFormulaEl = document.getElementById('control-right-pan-formula');
// NEW Familiarity Index elements
const familiarityDynamicContainer = document.getElementById('familiarity-dynamic-container');
const familiarityIndexValue = document.getElementById('familiarity-index-value');
// Resolution Slider
const resolutionSlider = document.getElementById('resolution-slider');
const profitValueEl = document.getElementById('profit-value');
const costValueEl = document.getElementById('cost-value');
const familiarityMarkerEl = document.getElementById('familiarity-marker');
const magnetToggleBtn = document.getElementById('magnet-toggle-btn');
const magnetIcon = document.getElementById('magnet-icon');
const costBracketSvg = document.getElementById('cost-bracket-svg');
const profitBracketSvg = document.getElementById('profit-bracket-svg');
// Button References
const addLeftFriendBtn = document.getElementById('add-left-friend-btn');
const removeLeftFriendBtn = document.getElementById('remove-left-friend-btn');
const addLeftFoeBtn = document.getElementById('add-left-foe-btn');
const removeLeftFoeBtn = document.getElementById('remove-left-foe-btn');
const addRightFriendBtn = document.getElementById('add-right-friend-btn');
const removeRightFriendBtn = document.getElementById('remove-right-friend-btn');
const addRightFoeBtn = document.getElementById('add-right-foe-btn');
const removeRightFoeBtn = document.getElementById('remove-right-foe-btn');
const resetBtn = document.getElementById('reset-btn');
const messageBox = document.getElementById('message-box');
const tooltipEl = document.getElementById('tooltip');
const languageSelector = document.getElementById('language-selector');
// --- p5.js Sketch with Matter.js integration ---
const sketch = (p) => {
// Matter.js modules
const Engine = Matter.Engine,
World = Matter.World,
Bodies = Matter.Bodies,
Body = Matter.Body,
Composite = Matter.Composite;
let engine;
let world;
// Scale physics properties
const MAX_ANGLE = 25;
let currentAngle = 0;
let targetAngle = 0;
// Bodies storage
let leftPan, rightPan;
const weightBodies = [];
// Pan positions (will be updated in draw loop)
let leftHangerPos, rightHangerPos;
const friendColor = '#3b82f6';
const foeColor = '#ef4444';
// --- Global Control Functions ---
p.addWeight = (side, type) => {
const hangerX = p.width / 2 + (side === 'left' ? -180 : 180);
const x = hangerX + p.random(-20, 20);
const y = 100; // Drop from above
const radius = 7.5;
const body = Bodies.circle(x, y, radius, {
restitution: 0.4, // Bounciness reduced
friction: 0.2, // A bit more friction
density: 0.1,
label: type // 'friend' or 'foe'
});
weightBodies.push(body);
World.add(world, body);
};
p.removeWeight = (side, type) => {
// Find the last added body of the correct type on the correct side
let bodyToRemove = null;
for (let i = weightBodies.length - 1; i >= 0; i--) {
const body = weightBodies[i];
const onCorrectSide = (side === 'left' && body.position.x < p.width / 2) || (side === 'right' && body.position.x > p.width / 2);
if (body.label === type && onCorrectSide) {
bodyToRemove = body;
weightBodies.splice(i, 1);
break;
}
}
if (bodyToRemove) {
World.remove(world, bodyToRemove);
}
};
p.resetWeights = () => {
World.clear(world, false); // Clear bodies but keep engine
weightBodies.length = 0;
createPanBodies(); // Recreate pan bodies
};
p.setTargetAngle = (angle) => {
targetAngle = p.constrain(angle, -MAX_ANGLE, MAX_ANGLE);
};
p.setup = () => {
const container = document.getElementById('canvas-container');
const canvas = p.createCanvas(500, 400);
canvas.parent(container);
p.angleMode(p.DEGREES);
// Initialize Matter.js engine
engine = Engine.create();
world = engine.world;
engine.world.gravity.y = 1.5; // A bit stronger gravity
createPanBodies();
};
const createPanBodies = () => {
// Create pans as compound bodies (buckets) with invisible walls
const panOptions = { isStatic: true, friction: 0.5, restitution: 0.1 };
const panWidth = 120;
const panThickness = 10;
const wallHeight = 80;
const wallThickness = 10;
// --- Left Pan Bucket ---
const panX_left = p.width / 2 - 180;
const panY_initial = 280; // This is just a starting position
const leftPanFloor = Bodies.rectangle(panX_left, panY_initial, panWidth, panThickness, panOptions);
const leftPanWall1 = Bodies.rectangle(panX_left - panWidth / 2 + wallThickness / 2, panY_initial - wallHeight / 2, wallThickness, wallHeight, panOptions);
const leftPanWall2 = Bodies.rectangle(panX_left + panWidth / 2 - wallThickness / 2, panY_initial - wallHeight / 2, wallThickness, wallHeight, panOptions);
leftPan = Body.create({
parts: [leftPanFloor, leftPanWall1, leftPanWall2],
isStatic: true
});
// --- Right Pan Bucket ---
const panX_right = p.width / 2 + 180;
const rightPanFloor = Bodies.rectangle(panX_right, panY_initial, panWidth, panThickness, panOptions);
const rightPanWall1 = Bodies.rectangle(panX_right - panWidth / 2 + wallThickness / 2, panY_initial - wallHeight / 2, wallThickness, wallHeight, panOptions);
const rightPanWall2 = Bodies.rectangle(panX_right + panWidth / 2 - wallThickness / 2, panY_initial - wallHeight / 2, wallThickness, wallHeight, panOptions);
rightPan = Body.create({
parts: [rightPanFloor, rightPanWall1, rightPanWall2],
isStatic: true
});
World.add(world, [leftPan, rightPan]);
}
p.draw = () => {
p.background('#1B1C1D');
Engine.update(engine); // Update the physics engine
// Smoothly interpolate the visual angle
currentAngle = p.lerp(currentAngle, targetAngle, 0.08);
// Calculate pan positions first, so other functions can use them
const pivotY = 130;
const pivotX = p.width / 2;
const hangerDist = 180;
leftHangerPos = {
x: pivotX + hangerDist * -1 * p.cos(currentAngle),
y: pivotY + hangerDist * -1 * p.sin(currentAngle)
};
rightHangerPos = {
x: pivotX + hangerDist * p.cos(currentAngle),
y: pivotY + hangerDist * p.sin(currentAngle)
};
drawLegend();
drawStand();
drawBeamAndPans(currentAngle);
drawWeights();
};
const drawLegend = () => {
// Determine angel side based on friend counts
let angelSide = 'center';
if (leftFriends > rightFriends) angelSide = 'left';
else if (rightFriends > leftFriends) angelSide = 'right';
// Determine devil side based on foe counts
let devilSide = 'center';
if (leftFoes < rightFoes) devilSide = 'left';
else if (rightFoes < leftFoes) devilSide = 'right';
// --- Angel Legend Logic ---
let angelLegendX, angelIconY, angelTextY;
const defaultIconY = 30;
const defaultTextY = defaultIconY + 25;
angelIconY = defaultIconY;
angelTextY = defaultTextY;
if (angelSide === 'left') angelLegendX = p.width * 0.25;
else if (angelSide === 'right') angelLegendX = p.width * 0.75;
else angelLegendX = p.width * 0.5;
// CORRECTED LOGIC: Check if the pan on the legend's side is UP
// Positive angle means left side is UP
if (angelSide === 'left' && currentAngle > 5) {
angelIconY = leftHangerPos.y + 190;
angelTextY = angelIconY + 25;
}
// Negative angle means right side is UP
if (angelSide === 'right' && currentAngle < -5) {
angelIconY = rightHangerPos.y + 190;
angelTextY = angelIconY + 25;
}
// --- Devil Legend Logic ---
let devilLegendX, devilIconY, devilTextY;
devilIconY = defaultIconY;
devilTextY = defaultTextY;
if (devilSide === 'left') devilLegendX = p.width * 0.25;
else if (devilSide === 'right') devilLegendX = p.width * 0.75;
else devilLegendX = p.width * 0.5;
// CORRECTED LOGIC: Check if the pan on the legend's side is UP
if (devilSide === 'left' && currentAngle > 5) {
devilIconY = leftHangerPos.y + 190;
devilTextY = devilIconY + 25;
}
if (devilSide === 'right' && currentAngle < -5) {
devilIconY = rightHangerPos.y + 190;
devilTextY = devilIconY + 25;
}
// --- Handle horizontal overlaps for legends ---
if (Math.abs(angelLegendX - devilLegendX) < 10 && Math.abs(angelIconY - devilIconY) < 10) {
if (angelSide === 'center' && devilSide === 'center') {
angelLegendX = p.width * 0.25;
devilLegendX = p.width * 0.75;
} else if (angelSide === 'left') { // Both on the left
angelLegendX = p.width * 0.12; // Push further to the edge
devilLegendX = p.width * 0.38; // Push further towards the center
} else if (angelSide === 'right') { // Both on the right
angelLegendX = p.width * 0.62; // Push further towards the center
devilLegendX = p.width * 0.88; // Push further to the edge
}
}
// --- Draw Angel Legend ---
p.push();
p.textAlign(p.CENTER, p.TOP);
p.fill(209, 213, 219); // gray-300
p.textSize(11);
p.text(translations[currentLanguage].legendAngel, angelLegendX, angelTextY);
drawAngel(angelLegendX, angelIconY);
p.pop();
// --- Draw Devil Legend ---
p.push();
p.textAlign(p.CENTER, p.TOP);
p.fill(209, 213, 219); // gray-300
p.textSize(11);
p.text(translations[currentLanguage].legendDevil, devilLegendX, devilTextY);
drawDevil(devilLegendX, devilIconY);
p.pop();
};
const drawStand = () => {
p.noStroke();
p.fill('#c9b037');
p.rect(p.width/2 - 100, 380, 200, 20, 10);
p.rect(p.width/2 - 12.5, 130, 25, 250, 10, 10, 0, 0);
};
const drawAngel = (x, y) => {
p.push();
p.translate(x, y);
p.noStroke();
p.stroke(255, 255, 0);
p.strokeWeight(2);
p.noFill();
p.ellipse(0, -15, 15, 5);
p.noStroke();
p.fill(34, 211, 238);
p.circle(0, 0, 20);
p.pop();
};
const drawDevil = (x, y) => {
p.push();
p.translate(x, y);
p.noStroke();
p.fill(255, 100, 100);
p.circle(0, 0, 20);
p.fill(100);
p.triangle(-8, -8, -15, -15, -3, -10);
p.triangle(8, -8, 15, -15, 3, -10);
p.pop();
};
const drawBeamAndPans = (angle) => {
const pivotY = 130;
const pivotX = p.width / 2;
const beamLength = 450;
const hangerDist = 180;
// Update Physics pan bodies to match the visual beam
Body.setPosition(leftPan, { x: leftHangerPos.x, y: leftHangerPos.y + 140 });
Body.setAngle(leftPan, 0); // Keep pans level
Body.setPosition(rightPan, { x: rightHangerPos.x, y: rightHangerPos.y + 140 });
Body.setAngle(rightPan, 0); // Keep pans level
// Draw Visuals
p.push();
p.translate(pivotX, pivotY);
p.rotate(angle);
p.noStroke();
p.fill('#a88a44');
p.rect(-beamLength / 2, -10, beamLength, 20, 10);
p.triangle(0, -10, -20, -40, 20, -40);
p.triangle(-hangerDist, 0, -hangerDist-10, -15, -hangerDist+10, -15);
p.triangle(hangerDist, 0, hangerDist-10, -15, hangerDist+10, -15);
// --- Main Creature Drawing (on the beam) ---
let angelX = 0;
if (leftFriends > rightFriends) angelX = -hangerDist;
else if (rightFriends > leftFriends) angelX = hangerDist;
let devilX = 0;
if (leftFoes < rightFoes) devilX = -hangerDist;
else if (rightFoes < leftFoes) devilX = hangerDist;
if (angelX === devilX) { angelX -= 20; devilX += 20; }
// These creatures are ALWAYS drawn above the beam
drawAngel(angelX, -25);
drawDevil(devilX, -25);
p.pop();
// Draw pans and strings at their new positions
drawPanVisuals(leftHangerPos.x, leftHangerPos.y, 120);
drawPanVisuals(rightHangerPos.x, rightHangerPos.y, 120);
};
const drawPanVisuals = (hangerX, hangerY, panWidth) => {
const panY = hangerY + 140;
const panEdgeOffset = panWidth / 2 - 10;
p.strokeWeight(2);
p.stroke('#a88a44');
p.line(hangerX, hangerY, hangerX - panEdgeOffset, panY);
p.line(hangerX, hangerY, hangerX + panEdgeOffset, panY);
p.noStroke();
p.fill('#c9b037');
p.arc(hangerX, panY, panWidth, 80, 0, 180, p.CHORD);
};
const drawWeights = () => {
p.noStroke();
for (const body of weightBodies) {
const pos = body.position;
const angle = body.angle;
p.push();
p.translate(pos.x, pos.y);
p.rotate(p.degrees(angle));
p.fill(body.label === 'friend' ? friendColor : foeColor);
p.circle(0, 0, body.circleRadius * 2);
p.pop();
}
};
};
let p5Sketch = new p5(sketch);
// --- Bridge between HTML and p5.js ---
function updateBrackets() {
const costPercentage = resolution * 100;
const profitPercentage = (1 - resolution) * 100;
// Cost bracket (red 'r') on the left
costBracketSvg.style.width = `${costPercentage}%`;
// Profit bracket (blue '1-r') on the right
profitBracketSvg.style.width = `${profitPercentage}%`;
// Update arc label positions
updateArcLabels();
}
function updateArcLabels() {
const costLabel = document.getElementById('cost-arc-label');
const profitLabel = document.getElementById('profit-arc-label');
// Calculate positions based on resolution
const costPercentage = resolution * 100;
const profitPercentage = (1 - resolution) * 100;
// Position cost label at the center of the red arc
const costLabelPosition = (costPercentage / 2);
costLabel.style.left = `${costLabelPosition}%`;
costLabel.style.transform = 'translateX(-50%)';
// Position profit label at the center of the blue arc
const profitLabelPosition = costPercentage + (profitPercentage / 2);
profitLabel.style.left = `${profitLabelPosition}%`;
profitLabel.style.transform = 'translateX(-50%)';
}
function updatePanWeights() {
const profit = (1 - resolution).toFixed(2);
const cost = resolution.toFixed(2);
const leftWeight = leftFriends * (1 - resolution) - leftFoes * resolution;
const rightWeight = rightFriends * (1 - resolution) - rightFoes * resolution;
// Update the main result display in controls
controlLeftPanWeightEl.textContent = leftWeight.toFixed(2);
controlRightPanWeightEl.textContent = rightWeight.toFixed(2);
// Update the formula display in controls
const leftFormulaHTML = `(<span class="text-blue-400">${leftFriends}</span>×<span class="text-blue-400">${profit}</span>) - (<span class="text-red-400">${leftFoes}</span>×<span class="text-red-400">${cost}</span>)`;
controlLeftPanFormulaEl.innerHTML = leftFormulaHTML;
const rightFormulaHTML = `(<span class="text-blue-400">${rightFriends}</span>×<span class="text-blue-400">${profit}</span>) - (<span class="text-red-400">${rightFoes}</span>×<span class="text-red-400">${cost}</span>)`;
controlRightPanFormulaEl.innerHTML = rightFormulaHTML;
}
function updateProfitAndCost() {
profitValueEl.previousSibling.textContent = translations[currentLanguage].profitPerFriend;
profitValueEl.textContent = (1 - resolution).toFixed(2);
costValueEl.previousSibling.textContent = translations[currentLanguage].costPerFoe;
costValueEl.textContent = resolution.toFixed(2);
}
function updateFamiliarityIndex() {
const defaultSliderBg = '#4b5563'; // A neutral gray color
const friendColor = '#3b82f6';
const foeColor = '#ef4444';
if (leftTotalWeight === 0 && rightTotalWeight === 0) {
familiarityDynamicContainer.classList.add('hidden');
familiarityMarkerEl.classList.add('hidden');
resolutionSlider.style.background = defaultSliderBg;
return;
}
const df = rightFriends - leftFriends;
const ds = rightFoes - leftFoes;
const sumDiff = df + ds;
if (sumDiff === 0) {
familiarityDynamicContainer.classList.add('hidden');
familiarityMarkerEl.classList.add('hidden');
resolutionSlider.style.background = defaultSliderBg;
} else {
const index = df / sumDiff;
familiarityIndexValue.textContent = index.toFixed(3);
if (index > 1) {
familiarityDynamicContainer.classList.add('hidden');
familiarityMarkerEl.classList.add('hidden');
resolutionSlider.style.background = friendColor; // Solid blue
} else if (index < 0) {
familiarityDynamicContainer.classList.add('hidden');
familiarityMarkerEl.classList.add('hidden');
resolutionSlider.style.background = foeColor; // Solid red
} else { // This handles the case where index is between 0 and 1
familiarityDynamicContainer.classList.remove('hidden');
familiarityMarkerEl.classList.remove('hidden');
const thumbWidth = 24;
const markerPosition = `calc(${index} * (100% - ${thumbWidth}px) + ${thumbWidth / 2}px)`;
familiarityMarkerEl.style.left = markerPosition;
familiarityDynamicContainer.style.left = markerPosition;
// Set slider background based on the familiarity index
const percentage = index * 100;
resolutionSlider.style.background = `linear-gradient(to right, ${friendColor} ${percentage}%, ${foeColor} ${percentage}%)`;
}
}
}
function updateScale() {
leftTotalWeight = leftFriends + leftFoes;
rightTotalWeight = rightFriends + rightFoes;
const leftWeight = leftFriends * (1 - resolution) - leftFoes * resolution;
const rightWeight = rightFriends * (1 - resolution) - rightFoes * resolution;
const diff = rightWeight - leftWeight;
const angle = diff * 3;
p5Sketch.setTargetAngle(angle);
controlLeftFriendsEl.textContent = leftFriends;
controlLeftFoesEl.textContent = leftFoes;
controlRightFriendsEl.textContent = rightFriends;
controlRightFoesEl.textContent = rightFoes;
updatePanWeights();
updateFamiliarityIndex();
}
function addObject(side, type) {
if (side === 'left') {
if (type === 'friend') leftFriends++; else leftFoes++;
} else {
if (type === 'friend') rightFriends++; else rightFoes++;
}
p5Sketch.addWeight(side, type);
updateScale();
}
function removeObject(side, type) {
let canRemove = false;
if (side === 'left') {
if (type === 'friend' && leftFriends > 0) { leftFriends--; canRemove = true; }
else if (type === 'foe' && leftFoes > 0) { leftFoes--; canRemove = true; }
} else {
if (type === 'friend' && rightFriends > 0) { rightFriends--; canRemove = true; }
else if (type === 'foe' && rightFoes > 0) { rightFoes--; canRemove = true; }
}
if (canRemove) {
p5Sketch.removeWeight(side, type);
updateScale();
}
}
function resetScale() {
leftTotalWeight = 0;
rightTotalWeight = 0;
leftFriends = 0;
leftFoes = 0;
rightFriends = 0;
rightFoes = 0;
resolution = 0.5;
resolutionSlider.value = 0.5;
updateProfitAndCost();
p5Sketch.resetWeights();
updateScale();
updateBrackets();
showMessage(translations[currentLanguage].msgReset, 'bg-blue-500');
}
function showMessage(text, color = 'bg-green-500') {
messageBox.textContent = text;
messageBox.className = `message-box fixed top-5 right-5 text-white px-6 py-3 rounded-lg shadow-xl opacity-0 translate-y-4 pointer-events-none ${color}`;
setTimeout(() => messageBox.classList.remove('opacity-0', 'translate-y-4'), 10);
setTimeout(() => messageBox.classList.add('opacity-0', 'translate-y-4'), 2500);
}
function setLanguage(lang) {
currentLanguage = lang;
const langData = translations[lang];
document.querySelectorAll('[data-translate]').forEach(el => {
const key = el.getAttribute('data-translate');
if (langData[key]) {
el.textContent = langData[key];
}
});
document.querySelectorAll('[data-translate-tooltip]').forEach(el => {
const key = el.getAttribute('data-translate-tooltip');
if (langData[key]) {
// Set the tooltip on the element itself
el.dataset.tooltip = langData[key];
}
});
document.querySelectorAll('[data-translate-title]').forEach(el => {
const key = el.getAttribute('data-translate-title');
if (langData[key]) {
el.title = langData[key];
}
});
updateProfitAndCost();
updatePanWeights();
document.title = langData.title;
}
// --- Event Listeners ---
languageSelector.addEventListener('change', (e) => {
setLanguage(e.target.value);
});
magnetToggleBtn.addEventListener('click', () => {
magnetModeEnabled = !magnetModeEnabled;
magnetIcon.classList.toggle('text-blue-400', magnetModeEnabled);
magnetIcon.classList.toggle('text-gray-500', !magnetModeEnabled);
const msg = magnetModeEnabled ? translations[currentLanguage].msgMagnetOn : translations[currentLanguage].msgMagnetOff;
showMessage(msg, magnetModeEnabled ? 'bg-green-500' : 'bg-red-500');
});
resolutionSlider.addEventListener('input', (e) => {
let sliderValue = parseFloat(e.target.value);
if (magnetModeEnabled) {
const familiarityIndex = parseFloat(familiarityIndexValue.textContent);
if (!isNaN(familiarityIndex) && familiarityIndex >= 0 && familiarityIndex <= 1) {
const snapThreshold = 0.05;
if (Math.abs(sliderValue - familiarityIndex) < snapThreshold) {
sliderValue = familiarityIndex;
e.target.value = sliderValue;
}
}
}
resolution = sliderValue;
updateProfitAndCost();
updateScale();
updateBrackets();
});
addLeftFriendBtn.addEventListener('click', () => addObject('left', 'friend'));
removeLeftFriendBtn.addEventListener('click', () => removeObject('left', 'friend'));
addLeftFoeBtn.addEventListener('click', () => addObject('left', 'foe'));
removeLeftFoeBtn.addEventListener('click', () => removeObject('left', 'foe'));
addRightFriendBtn.addEventListener('click', () => addObject('right', 'friend'));
removeRightFriendBtn.addEventListener('click', () => removeObject('right', 'friend'));
addRightFoeBtn.addEventListener('click', () => addObject('right', 'foe'));
removeRightFoeBtn.addEventListener('click', () => removeObject('right', 'foe'));
resetBtn.addEventListener('click', resetScale);
const tooltipTriggers = document.querySelectorAll('[data-translate-tooltip]');
tooltipTriggers.forEach(trigger => {
const positionTooltip = (e) => {
// Force a reflow to get accurate dimensions
tooltipEl.offsetHeight;
const tooltipRect = tooltipEl.getBoundingClientRect();
let x = e.clientX + 12;
let y = e.clientY + 12;
// Check right boundary
if (x + tooltipRect.width > window.innerWidth - 20) {
x = e.clientX - tooltipRect.width - 12;
}
// Check left boundary
if (x < 20) {