-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgraph_game.html
1490 lines (1371 loc) · 41.6 KB
/
graph_game.html
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>
<head>
<title>Graph Game</title>
<link rel="icon" href="res/favicon.ico">
<script type="text/javascript">
// Config
const kLinkFactor = 0.5;
const kFastFreeze = true;
const kRepelForce = kFastFreeze ? -0.001 : -0.0001;
const kAttractForce = kFastFreeze ? 0.1 : 0.01;
const kDamping = kFastFreeze ? 0.8 : 0.2;
const kUpdateItrs = kFastFreeze ? 10 : 1;
const kFreezeThreshold = kFastFreeze ? 1e-4 : 1e-6;
const kAiTestingMode = false;
const kAiTestingRuns = 1000;
const kAiTestingPhils = ['Foolish AI', 'Easy AI', 'Easy H1 AI', 'Easy H2 AI', 'Easy H3 AI', 'Medium AI', 'Medium H1 AI', 'Medium H2 AI', 'Medium H3 AI'];
const kAiTestingEmmys = kAiTestingPhils;
const kAiTestingGraphSize = 12;
const kAiDefaultHeurVer = kAiTestingMode ? 0 : 3;
const kAiHeurRecursive = 3;
const kAiHeurDegree = 1;
const kAiHeurAdjClr = 1;
const kAiHeurColor = 10;
const kAiColorCalcRand = 1;
const tau = 2 * Math.PI;
function randInt(n) {
return Math.floor(n * Math.random());
}
function randPos() {
return 2 * Math.random() - 1;
}
function swap(a, i, j) {
const x = a[i];
a[i] = a[j];
a[j] = x;
}
async function wait(seconds) {
return new Promise((resolve, reject) => {
window.setTimeout(resolve, 1000 * seconds);
});
}
function randPermutation(n) {
const a = [];
for (let i = 0; i < n; ++i) a.push(i);
for (let i = 0; i < n; ++i) {
swap(a, i, randInt(n - i) + i);
}
return a;
}
function clamp(x, hi = 1, lo = 0) {
return x <= lo ? lo : x >= hi ? hi : x;
}
function fmod(x, y = 1) {
const z = x / y;
return (z - Math.floor(z)) * y;
}
function popSwap(a, i) {
const x = a[i];
const y = a.pop();
if (i < a.length) a[i] = y;
return x;
}
function rgb2str(r, g, b) {
const ch = x => {
const s = Math.floor(clamp(x * 256, 255)).toString(16);
if (s.length > 2) return 'ff';
if (s.length == 0) return '00';
if (s.length == 1) return '0' + s;
return s;
}
return `#${ch(r)}${ch(g)}${ch(b)}ff`;
}
function hsv2rgb(h, s = 1, v = 1) {
const i = fmod(h) * 6.0;
const c = v * s;
const m = v - c;
const x = c * (1 - Math.abs(fmod(i, 2) - 1)) + m;
const d = c + m;
if (i < 1) return rgb2str(d, x, m);
if (i < 2) return rgb2str(x, d, m);
if (i < 3) return rgb2str(m, d, x);
if (i < 4) return rgb2str(m, x, d);
if (i < 5) return rgb2str(x, m, d);
return rgb2str(d, m, x);
}
function newElement(type, parent, classes = [], text = null) {
const n = document.createElement(type);
if (text != null) n.innerText = text;
for (const cls of classes) n.classList.add(cls);
if (parent != null) parent.appendChild(n);
return n;
}
function newDiv(parent, classes = [], text = null) {
return newElement('div', parent, classes, text);
}
function newSelect(parent, classes = [], options = []) {
const sel = newElement('select', parent, classes);
for (const opt of options) {
newElement('option', sel, [], opt).setAttribute('value', opt);
}
return sel;
}
function newSlider(parent, classes = [], min = 0, max = 100, step = 1) {
const slider = newElement('input', parent, classes);
slider.setAttribute('type', 'range');
slider.setAttribute('min', min);
slider.setAttribute('max', max);
slider.setAttribute('step', step);
slider.setAttribute('value', min);
return slider;
}
function newCanvas(parent, classes = [], width = 100, height = 100) {
const slider = newElement('canvas', parent, classes);
slider.setAttribute('width', width);
slider.setAttribute('height', height);
return slider;
}
function newBtn(
parent, classes = [], text = null, onclick = null) {
const btn = newDiv(parent, classes, text);
if (onclick != null) btn.addEventListener('click', onclick);
return btn;
}
function emptyDiv(n) {
while (n.hasChildNodes()) n.removeChild(n.lastChild);
}
let game = null;
function onLoad() {
game = new Game(document.getElementById('game'));
if (kAiTestingMode) {
game.transitionToAiTestingMode();
} else {
game.transitionToSetup();
}
}
window.addEventListener('load', onLoad);
class Move {
constructor(nodeId, color) {
this.nodeId = nodeId;
this.color = color;
}
}
class HumanCtrl {
constructor(graph, isPhil, ui, doMove) {
newDiv(ui, ['game-status'], `It's ${isPhil ? 'Phil' : 'Emmy'}'s turn`);
newDiv(ui, [], '1) Choose a color ⮟');
const clrRow = newDiv(ui, ['game-ctrl-clr-row']);
const clrBtns = [];
let selectedClr = null;
const setClr = i => {
for (const btn of clrBtns) btn.classList.remove('selected');
selectedClr = (selectedClr == i) ? null : i;
if (selectedClr != null) clrBtns[selectedClr].classList.add('selected');
};
for (let i = 0; i < graph.numColors; ++i) {
const btn = newBtn(clrRow, ['game-ctrl-clr'], null, () => setClr(i));
btn.style.backgroundColor = graph.colors[i];
clrBtns.push(btn);
}
newDiv(ui, [], '2) Choose an empty node ⮞');
const applyRow = newDiv(ui, ['game-ctrl-row']);
newDiv(applyRow, [], '3)');
let error = null;
const fillBtn = newBtn(applyRow, ['game-ctrl-fill'], '[FILL NODE]', () => {
error.innerText = '';
if (selectedClr == null) {
error.innerText = 'You have to choose a color first.';
} else if (graph.selectedNode == null) {
error.innerText = 'You have to choose a node first.';
} else {
const move = new Move(graph.selectedNode, selectedClr);
if (!graph.isValidMove(move)) {
error.innerText =
'The node must be a different color to all its neighbors.';
} else {
setClr(null);
doMove(move);
}
}
});
error = newDiv(ui, ['game-ctrl-error']);
}
onTurn() {}
}
function aiCalculateScoreImplForPhil(graph, heurVer, isColorCalc) {
const status = graph.getStatus();
if (status != -1) {
return status == 1 ? Infinity : -Infinity;
}
if (heurVer == 0) return 0.1 * Math.random();
// Sum the score of each node. Node score is proportional to its degree. If a
// node is full or has no empty neighbors, that score is positive. Otherwise
// it's negative.
let score = (isColorCalc ? kAiColorCalcRand : 1e-9) * Math.random();
const size = graph.nodes.length;
for (const n of graph.nodes) {
let inPlay = n.isEmpty() && n.hasEmptyNeighbors();
let degreeScore = n.links.size / size;
score += kAiHeurDegree * (inPlay ? -degreeScore : degreeScore);
}
if (heurVer == 1) return score;
// Number of colors adjacent to each node is negative.
const temp = [];
for (const n of graph.nodes) {
for (let i = 0; i < graph.numColors; ++i) temp[i] = 0;
for (const m of n.links) temp[m.clr] = 1;
let clrScore = 0;
for (let i = 0; i < graph.numColors; ++i) clrScore += temp[i];
score += -kAiHeurAdjClr * clrScore / graph.numColors;
}
if (heurVer == 2) return score;
// Number of colors in use is negative.
for (let i = 0; i < graph.numColors; ++i) {
if (graph.nodesPerColor[i] != 0) {
score += -kAiHeurColor / graph.numColors;
}
}
return score;
}
function aiCalculateScore(graph, move, isPhil, heurVer, isColorCalc = false) {
// Invariant: Must leave graph how it was found.
graph.doMove(move);
const score = aiCalculateScoreImplForPhil(graph, heurVer, isColorCalc);
graph.undoMove(move);
return isPhil ? score : -score;
};
function aiCombineScores(score, recScore) {
if (!isFinite(score)) return score;
recScore = -recScore;
if (!isFinite(recScore)) return recScore;
return score + kAiHeurRecursive * recScore;
};
class AiCtrl {
constructor(kind, graph, isPhilCtrl, ui, doMove) {
const maxDepth = {
'Foolish AI': -1,
'Easy AI': 0,
'Easy H1 AI': 0,
'Easy H2 AI': 0,
'Easy H3 AI': 0,
'Medium AI': 2,
'Medium H1 AI': 2,
'Medium H2 AI': 2,
'Medium H3 AI': 2,
'Hard AI': 4,
'Hard H1 AI': 4,
'Hard H2 AI': 4,
'Hard H3 AI': 4,
}[kind];
const heurVer = {
'Easy H1 AI': 1,
'Medium H1 AI': 1,
'Hard H1 AI': 1,
'Easy H2 AI': 2,
'Medium H2 AI': 2,
'Hard H2 AI': 2,
'Easy H3 AI': 3,
'Medium H3 AI': 3,
'Hard H3 AI': 3,
}[kind] ?? kAiDefaultHeurVer;
let setStatus = null;
let setMood = null;
let setMoodValue = null;
if (ui) {
const status = newDiv(ui, ['game-status']);
setStatus = (s) => {
status.innerText =`${isPhilCtrl ? 'Phil' : 'Emmy'} is ${s}...`;
};
const clrRow = newDiv(ui, ['game-ctrl-clr-row']);
for (let i = 0; i < graph.numColors; ++i) {
const btn = newDiv(clrRow, ['game-ctrl-clr-ai']);
btn.style.backgroundColor = graph.colors[i];
}
const happyMoods = ['🙂', '😉', '🤭', '😄', '🤣', '😎', '🥳'];
const neutralMoods = ['🤨', '🤔', '😑', '😐', '🧐', '😯', '😪'];
const sadMoods = ['😅', '😬', '😵', '😒', '🥺', '😭', '💀'];
const moodRow = newDiv(ui, ['ai-mood-row']);
const mood = newDiv(moodRow, ['ai-mood']);
setMood = (m) => mood.innerText = m;
setMoodValue = (x) => {
const neutralRange = 10;
const maxRange = 1200;
const y = (Math.abs(x) - neutralRange) / (maxRange - neutralRange);
if (y <= 0) {
setMood(neutralMoods[randInt(neutralMoods.length)]);
return;
}
const moods = x < 0 ? sadMoods : happyMoods;
if (!isFinite(x)) {
setMood(moods[moods.length - 1]);
return;
}
const z = (y * (moods.length - 1)) + (randInt(2) - 1);
setMood(moods[clamp(Math.floor(z), moods.length - 2)]);
};
setMoodValue(0);
}
if (maxDepth == -1) {
this.onTurn = async () => {
if (ui) {
setStatus('"thinking"');
setMood('🤪');
await wait(1);
}
const moves = [];
graph.forEachValidMove((node, color) => {
moves.push(new Move(node, color));
});
const move = moves[randInt(moves.length)];
if (ui) {
setStatus('coloring');
setMood('🤠');
await wait(1);
}
doMove(move);
};
} else {
this.onTurn = async () => {
if (ui) {
setStatus('thinking');
await wait(0);
}
// Returns [Move, Score]
const getTime = () => performance.now() / 1000;
let lastPause = getTime();
let lastPauseEnd = lastPause;
const runAi = async (depth, isPhil) => {
// Pause to allow a frame to render, to prevent browser freezing.
// Rate is between 1Hz and 100Hz, with the goal of 80% CPU time.
const t = getTime();
const nextPause = lastPauseEnd + Math.max(0.01,
Math.min(1, (lastPauseEnd - lastPause) * 4));
if (t > nextPause) {
// console.log(`Utilization ${
// Math.floor(100 * (t - lastPauseEnd) / (t - lastPause))}% ${
// Math.floor(1 / (t - lastPause))}Hz`);
lastPause = t;
await wait(0);
lastPauseEnd = getTime();
}
const mss = []; // Array{Tuple{Move, Score}}
graph.forEachUsefulMove((node, color) => {
// Invariant: Must leave graph how it was found.
const move = new Move(node, color);
const score = aiCalculateScore(graph, move, isPhil, heurVer);
if (score != -Infinity) mss.push([move, score]);
});
if (mss.length == 0) {
// No useful moves, so do a random move.
const moves = [];
graph.forEachValidMove((node, color) => {
moves.push(new Move(node, color));
});
const move = moves[randInt(moves.length)];
return [move, aiCalculateScore(graph, move, isPhil, heurVer)];
}
for (const [move, score] of mss) {
// Bail early to avoid recursion if there's a winning move.
if (score == Infinity) return [move, score];
}
if (depth > 0) {
for (let i = 0; i < mss.length; ++i) {
// Invariant: Must leave graph how it was found.
const [move, score] = mss[i];
if (!isFinite(score)) continue;
graph.doMove(move);
const [revMove, recScore] = await runAi(depth - 1, !isPhil);
const combinedScore = aiCombineScores(score, recScore);
graph.undoMove(move);
mss[i] = [move, combinedScore];
}
}
let bestIndex = 0;
let bestScore = mss[0][1];
for (let i = 1; i < mss.length; ++i) {
const [move, score] = mss[i];
if (score > bestScore) {
bestScore = score;
bestIndex = i;
}
}
return mss[bestIndex];
};
const [move, score] = await runAi(maxDepth, isPhilCtrl);
if (ui) {
console.log(move, score);
const thinkTime = getTime() - lastPause;
if (thinkTime < 1) await wait(1 - thinkTime);
setStatus('coloring');
setMoodValue(score);
await wait(1);
}
doMove(move);
};
}
}
}
class SyncAiCtrl {
constructor(graph, isPhilCtrl, doMove) {
/*this.onTurn = () => {
const moves = [];
graph.forEachValidMove((node, color) => {
moves.push(new Move(node, color));
});
const move = moves[randInt(moves.length)];
doMove(move);
};*/
const maxDepth = 0;
const heurVer = 3;
this.onTurn = () => {
// Returns [Move, Score]
const runAi = (depth, isPhil) => {
const mss = []; // Array{Tuple{Move, Score}}
graph.forEachUsefulMove((node, color) => {
// Invariant: Must leave graph how it was found.
const move = new Move(node, color);
const score = aiCalculateScore(graph, move, isPhil, heurVer, true);
if (score != -Infinity) mss.push([move, score]);
});
if (mss.length == 0) {
// No useful moves, so do a random move.
const moves = [];
graph.forEachValidMove((node, color) => {
moves.push(new Move(node, color));
});
const move = moves[randInt(moves.length)];
return [move, aiCalculateScore(graph, move, isPhil, heurVer, true)];
}
for (const [move, score] of mss) {
// Bail early to avoid recursion if there's a winning move.
if (score == Infinity) return [move, score];
}
if (depth > 0) {
for (let i = 0; i < mss.length; ++i) {
// Invariant: Must leave graph how it was found.
const [move, score] = mss[i];
if (!isFinite(score)) continue;
graph.doMove(move);
const [revMove, recScore] = runAi(depth - 1, !isPhil);
const combinedScore = aiCombineScores(score, recScore);
graph.undoMove(move);
mss[i] = [move, combinedScore];
}
}
let bestIndex = 0;
let bestScore = mss[0][1];
for (let i = 1; i < mss.length; ++i) {
const [move, score] = mss[i];
if (score > bestScore) {
bestScore = score;
bestIndex = i;
}
}
return mss[bestIndex];
};
const [move, score] = runAi(maxDepth, isPhilCtrl);
doMove(move);
};
}
}
class GraphNode {
constructor(id, total) {
this.id = id;
this.color = -1;
this.links = new Set();
this.resetPos(total);
}
resetPos(total) {
const t = tau * this.id / total;
this.px = Math.cos(t);
this.py = Math.sin(t);
// this.px = randPos();
// this.py = randPos();
this.vx = 0;
this.vy = 0;
}
link(other) {
if (this == other) return false;
if (this.links.has(other)) return false;
this.links.add(other);
other.links.add(this);
return true;
}
isEmpty() {
return this.color == -1;
}
hasEmptyNeighbors() {
for (const m of this.links) {
if (m.isEmpty()) return true;
}
return false;
}
}
class Graph {
constructor() {
this.zoom = 1;
this.camx = 0;
this.camy = 0;
this.heldNode = null;
this.selectedNode = null;
this.culpritNode = null;
this.nodes = [];
this.numColors = 0;
this.colors = [];
this.nodesPerColor = [];
this.frozen = false;
}
createNodes(size) {
this.frozen = false;
this.nodes = [];
for (let i = 0; i < size; ++i) {
this.nodes.push(new GraphNode(i, size));
}
}
fillColors() {
this.colors = [];
this.nodesPerColor = [];
const offset = Math.random();
for (let i = 0; i < this.numColors; ++i) {
this.colors.push(hsv2rgb(offset + i / this.numColors));
this.nodesPerColor.push(0);
}
}
newDenseGraph(size) {
// Straigtforward random graph generator.
while (true) {
// Create nodes.
this.nodes = [];
for (let i = 0; i < size; ++i) this.nodes.push(new GraphNode(i, size));
// Calculate number of links to create.
const minLinks = size - 1;
const maxLinks = size * (size - 1) / 2;
let remainingLinks = kLinkFactor * (maxLinks - minLinks) + minLinks;
const randLink = from => {
let to = from;
while (to == from) to = randInt(size);
if (this.nodes[from].link(this.nodes[to])) {
--remainingLinks;
}
};
// Start by creating one link from each node.
for (let i = 0; i < size; ++i) randLink(i);
// Then continue generating random links until we've made the right number.
while (remainingLinks > 0) randLink(randInt(size));
// If we have any disconnected components, start over.
const visited = new Set();
this.dfs(this.nodes[0], visited);
if (visited.size == this.nodes.length) break;
}
// Calculate the number of colors we want.
this.chooseNumColors(this.maxLinksPerNode());
this.fillColors();
}
maxLinksPerNode() {
let x = 0;
for (const n of this.nodes) {
x = Math.max(x, n.links.size);
}
return x;
}
newPlanarGraph(size) {
// A region is defined by the ordered list of points that bound it. The
// order of the list matters because the edges that bound the region are
// between each adjacent node in the list, and the first and last node too.
// Start with a single point.
const regions = [[0]];
// const nodePos = [[1, 0]];
// Create new nodes by subdividing the regions.
for (let i = 1; i < size; ++i) {
// Pick a random region, and pull it out of the list.
const r = popSwap(regions, randInt(regions.length));
// Place the new node in the center of the region.
/*if (i <= 2) {
nodePos.push([-0.5, i == 1 ? 0.707 : -0.707]);
} else {
// Find the center.
let cx = 1e-6 * randPos();
let cy = 1e-6 * randPos();
for (const i of r) {
cx += nodePos[i][0];
cy += nodePos[i][1];
}
nodePos.push([cx / r.length, cy / r.length]);
}*/
// We're going to add a node inside this region, and connect it to a
// random number of the surrounding nodes (at least 1).
const p = randPermutation(r.length);
p.length = 1 + randInt(r.length);
p.sort();
for (let j = 0; j < p.length; ++j) {
const k0 = p[j];
const k1 = p[(j + 1) % p.length];
// Cut r from r[k0] to r[k1].
const s = [r[k1], i, r[k0]];
let k = k0;
while (true) {
k = (k + 1) % r.length;
s.push(r[k]);
if (k == k1) break;
}
regions.push(s);
}
}
// Create nodes.
this.createNodes(size);
// for (let i = 0; i < size; ++i) {
// this.nodes[i].px = nodePos[i][0];
// this.nodes[i].py = nodePos[i][1];
// }
// Turn the region set into links.
for (const r of regions) {
for (let i = 0; i < r.length; ++i) {
const k0 = r[i];
const k1 = r[(i + 1) % r.length];
this.nodes[k0].link(this.nodes[k1]);
}
}
// Choose the right number of colors for this graph.
this.chooseNumColors(4);
this.fillColors();
}
newCompleteGraph(size) {
this.createNodes(size);
for (const n of this.nodes) {
for (const m of this.nodes) {
n.link(m);
}
}
this.numColors = size;
this.fillColors();
}
newLineGraph(size, loop) {
this.createNodes(size);
const end = loop ? size : size - 1;
for (let i = 0; i < end; ++i) {
this.nodes[i].link(this.nodes[(i + 1) % size]);
}
this.numColors = 2;
this.fillColors();
}
newTreeGraph(size) {
this.createNodes(size);
for (let i = 1; i < size; ++i) {
while (true) {
const r = randInt(size);
if (r == i) continue;
const visited = new Set();
this.dfs(this.nodes[r], visited);
if (visited.has(this.nodes[i])) continue;
this.nodes[i].link(this.nodes[r]);
break;
}
}
this.chooseNumColors(3);
this.fillColors();
}
chooseNumColors(guess) {
// If Phil wins more than half of the games, there are too many colors. If
// Emmy wins more than half of the games, there are too few colors. So
// starting with our initial guess, go up and down searching for the closest
// to an equal win rate we can find.
const kTestGames = 100;
const kTargWins = kTestGames / 2;
const rates = [];
const runTest = n => {
if (rates[n] != null) return;
this.numColors = n;
let philWins = 0;
for (let i = 0; i < kTestGames; ++i) {
philWins += this.runTestGame();
}
rates[n] = philWins;
};
const score = philWins => {
// 50% is best. For rates near 50%, bias slightly towards Phil. Further
// away, the bias gets stronger. 100% is scores the same as 17%.
const x = philWins / kTestGames;
const y = Math.sqrt(x) - Math.sqrt(0.5);
return y * y;
};
const runTests = d => {
for (let n = guess; ; n += d) {
if (n < 2 || n > this.nodes.length) break;
runTest(n);
const pr = rates[n - d];
if (pr == null) continue;
const r = rates[n];
const sr = score(r);
const sp = score(pr);
if (sr > sp || (r == (d > 0 ? kTestGames : 0))) break;
}
};
runTests(1);
runTests(-1);
console.log(rates);
let mins = kTestGames;
let mini = -1;
for (let i = 0; i < rates.length; ++i) {
const r = rates[i];
if (r == null) continue;
const s = score(r);
if (s < mins) {
mins = s;
mini = i;
}
}
this.numColors = mini;
const philWinRate = rates[mini] / kTestGames;
console.log(
`Phil win rate for this graph: ${philWinRate * 100}%.`,
`Using ${this.numColors} colors.`);
}
runTestGame() {
let onTurn = null;
let status = -2;
const move = (isPhil, move) => {
this.doMove(move);
status = this.getStatus();
if (status == -1) onTurn(isPhil);
};
const phil = new SyncAiCtrl(this, true, m => move(true, m));
const emmy = new SyncAiCtrl(this, false, m => move(false, m));
onTurn = (isPhil) => (isPhil ? emmy : phil).onTurn();
phil.onTurn();
this.resetColors();
return status;
}
resetColors() {
for (const n of this.nodes) n.color = -1;
for (let i = 0; i < this.nodesPerColor.length; ++i) {
this.nodesPerColor[i] = 0;
}
}
dfs(node, visited) {
if (visited.has(node)) return;
visited.add(node);
for (const m of node.links) this.dfs(m, visited);
}
resetPos() {
this.frozen = false;
for (const n of this.nodes) n.resetPos(this.nodes.length);
}
update() {
for (let i = 0; i < kUpdateItrs; ++i) {
// Stop updating if we've reached equilibrium.
if (this.frozen) return;
this.updateImpl();
}
}
updateImpl() {
// Calculate the forces.
this.frozen = true;
const size = this.nodes.length;
for (let i = 0; i < size; ++i) {
const n = this.nodes[i];
// Apply a weak spring force towards the origin.
const dist = Math.sqrt(n.px * n.px + n.py * n.py);
const ux = n.px / dist;
const uy = n.py / dist;
const fa = -kAttractForce * Math.sqrt(dist);
n.vx += fa * ux;
n.vy += fa * uy;
for (let j = 0; j < size; ++j) {
if (i == j) continue;
const m = this.nodes[j];
const dx = m.px - n.px;
const dy = m.py - n.py;
const dist = Math.sqrt(dx * dx + dy * dy);
const ux = dx / dist;
const uy = dy / dist;
// Push the nodes apart, as if they're same pole magnets.
const fr = kRepelForce / (dist * dist);
n.vx += fr * ux;
n.vy += fr * uy;
if (n.links.has(m)) {
// Pull the nodes together, as if they're joined by springs.
const fa = kAttractForce * dist;
n.vx += fa * ux;
n.vy += fa * uy;
}
}
// Damping.
n.vx *= 1 - kDamping;
n.vy *= 1 - kDamping;
// Check if we've reached equilibrium.
if (n.vx > kFreezeThreshold || n.vy > kFreezeThreshold) {
this.frozen = false;
}
}
// Apply the forces, and calculate the bounding box.
let minx = Infinity;
let maxx = -Infinity;
let miny = Infinity;
let maxy = -Infinity;
for (let i = 0; i < size; ++i) {
const n = this.nodes[i];
n.px += n.vx;
n.py += n.vy;
minx = Math.min(minx, n.px);
maxx = Math.max(maxx, n.px);
miny = Math.min(miny, n.py);
maxy = Math.max(maxy, n.py);
}
// Zoom and center.
this.zoom = 0.52 * Math.max(maxx - minx, maxy - miny);
this.camx = 0.5 * (minx + maxx);
this.camy = 0.5 * (miny + maxy);
if (this.frozen) console.log('FREEZE!', this.zoom);
}
draw(drawLink, drawNode) {
// Draw all the links.
const tx = x => (x - this.camx) / this.zoom;
const ty = y => (y - this.camy) / this.zoom;
const size = this.nodes.length;
const nodeClr = n => n.isEmpty() ? '#444' : this.colors[n.color];
for (let i = 1; i < size; ++i) {
const n = this.nodes[i];
for (let j = 0; j < i; ++j) {
const m = this.nodes[j];
if (n.links.has(m)) {
let clrn = nodeClr(n);
let clrm = nodeClr(m);
if (this.selectedNode == i || this.selectedNode == j) {
clrn = clrm = '#FFF';
} else if (n.isEmpty()) {
clrn = clrm;
} else if (m.isEmpty()) {
clrm = clrn;
}
drawLink(tx(n.px), ty(n.py), tx(m.px), ty(m.py), clrn, clrm);
}
}
}
// Draw all the nodes.
for (let i = 0; i < size; ++i) {
const n = this.nodes[i];
const c = (this.selectedNode == i || this.culpritNode == i) ?
'#FFF' : nodeClr(n);
drawNode(tx(n.px), ty(n.py), c);
}
}
onClickDown(rawx, rawy, hitrad) {
const px = this.camx + rawx * this.zoom;
const py = this.camy + rawy * this.zoom;
let minr = Infinity;
let mini = -1;
for (let i = 0; i < this.nodes.length; ++i) {
const n = this.nodes[i];
const dx = px - n.px;
const dy = py - n.py;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minr) {
minr = dist;
mini = i;
}
}
if (minr < hitrad * this.zoom) {
this.heldNode = mini;
this.selectedNode = (this.nodes[mini].color == -1) ? mini : null;
} else {
this.heldNode = null;
this.selectedNode = null;
}
}
onClickMove(rawx, rawy) {
if (this.heldNode == null) return;
const px = this.camx + rawx * this.zoom;
const py = this.camy + rawy * this.zoom;
this.nodes[this.heldNode].px = px;
this.nodes[this.heldNode].py = py;
}
onClickUp() {
this.heldNode = null;
}
isValidMove(move) {
// Move is valid if the target node is empty and all its neighbors have a
// different color to the target color.
const n = this.nodes[move.nodeId];
if (n.color != -1) return false;
for (const m of n.links) {
if (m.color == move.color) return false;
}
return true;
}
doMove(move) {
// console.log(move);
console.assert(this.nodes[move.nodeId].color == -1);
this.nodes[move.nodeId].color = move.color;
this.nodesPerColor[move.color] += 1;
}
undoMove(move) {
console.assert(this.nodes[move.nodeId].color == move.color);
this.nodes[move.nodeId].color = -1;
this.nodesPerColor[move.color] -= 1;
}
// Returns -1 if game is not over, 0 if Emmy won, and 1 if Phil won.
getStatus(uiMode = false) {
// If all nodes are filled, Phil has won. Otherwise, if any node has no
// valid moves, Emmy has won (and that node is the culprit). Otherwise, if
// all empty nodes have only full neighbors, Phil has won (but in uiMode we
// ignore this case). Otherwise, the game is not over.
if (uiMode) this.culpritNode = null;
let anyEmpty = false;
let anyEmptyWithEmptyNeighbors = false;