-
Notifications
You must be signed in to change notification settings - Fork 1
/
observablehq-labyrinth.js
1463 lines (1389 loc) · 42.9 KB
/
observablehq-labyrinth.js
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
// URL: https://beta.observablehq.com/@forresto/labyrinth
// Title: Labyrinth
// Author: Forrest Oliphant (@forresto)
// Version: 1790
// Runtime version: 1
const m0 = {
id: "6b688f41041a357a@1790",
variables: [
{
inputs: ["md"],
value: (function(md){return(
md`# Labyrinth
tldr:`
)})
},
{
name: "tldr",
inputs: ["boardToPathEl","tldrBoard","tldrCols"],
value: (function(boardToPathEl,tldrBoard,tldrCols){return(
boardToPathEl(tldrBoard, tldrCols, 9)
)})
},
{
name: "tldrCols",
inputs: ["width"],
value: (function(width){return(
Math.floor(width / 28 / 2) * 2 + 1
)})
},
{
name: "tldrBoard",
inputs: ["solveAsync","makeInitialBoard","tldrCols"],
value: (function(solveAsync,makeInitialBoard,tldrCols){return(
solveAsync('hello', makeInitialBoard(tldrCols, 9), tldrCols, 9)
)})
},
{
inputs: ["md"],
value: (function(md){return(
md`## Fun with space-filling curves
> "Then it seemed like falling into a labyrinth: we thought we were at the finish, but our way bent round and we found ourselves as it were back at the beginning, and just as far from that which we were seeking at first." ... Thus the present-day notion of a labyrinth as a place where one can lose [his] way must be set aside. It is a confusing path, hard to follow without a thread, but, provided [the traverser] is not devoured at the midpoint, it leads surely, despite twists and turns, back to the beginning.
– Socrates describing the labyrinthine line of a logical argument in Plato's dialogue Euthydemus
I've been doing a [few versions](https://twitter.com/forresto/status/879959151727837184) of this generative Labyrinth in the past few years. Each time I learn something new. I'm going to attempt to make a growing animated version, as a way to try _Observable_ & literate programming.
![photo cut labyrinth experiment](https://pbs.twimg.com/media/DDY-JqvXUAAKaS6.jpg:large)
`
)})
},
{
inputs: ["md"],
value: (function(md){return(
md`
## How should we represent the data
Instead of starting with svg or canvas, I'm going to start by building up data that describes the labyrinth. I can then translate that same data to canvas, svg, or a string to visualize the process.
The last time that I made code to draw a labyrinth, the data for the intial board and path looked something like this:
\`\`\`
→→↓
↑ ↓
↑←←
\`\`\`
Each space in the path (or board) points to the next. To decide if the labyrinth can grow in a particular direction, a segment in the path has to check its surroundings.
\`\`\`
→→↓
→↑ ↓
↑←←←
\`\`\`
Each mutation to the path is optionally symmetrical.
\`\`\`
→↓
→→→↓ →→→↓ →↑→↓
→↑ ↓← →↑ ↓← →↑ ↓←
↑←←← ↑←↓← ↑←↓←
↑← ↑←
\`\`\`
I want to do things a little differently this time, though. I'm wondering if I could make something that could be more general than just 90° turns filling a square.
Or maybe, instead of the "linked-loop" data that I've been working with, I can try thinking in terms of [tiles](https://trasevol.dog/2017/09/01/di19/).
\`\`\`
╔╗
╔╬╝
╚╝
\`\`\`
`
)})
},
{
inputs: ["md"],
value: (function(md){return(
md`# Initial setup
## Index constants
Kinda wierd but...`
)})
},
{
name: "KEY",
value: (function(){return(
0
)})
},
{
name: "CHAR",
value: (function(){return(
1
)})
},
{
name: "OVER",
value: (function(){return(
2
)})
},
{
name: "RIGHT",
value: (function(){return(
3
)})
},
{
name: "UNDER",
value: (function(){return(
4
)})
},
{
name: "LEFT",
value: (function(){return(
5
)})
},
{
name: "ROTATED",
value: (function(){return(
6
)})
},
{
inputs: ["md"],
value: (function(md){return(
md`## TILES
I think this is like a simple [Tracery](http://www.tracery.io/) grammer or _Wave Form Collapse_ dictionary. Each tile decribes _what it will change to_ if the path is extended from it. For example, "right bottom (\`╔\`)" extended to the left will become "right bottom left (\`<╦\`)".
`//SPACE = navigator.userAgent.toLowerCase().indexOf('android') > -1 ? '─' : ' '
)})
},
{
name: "TILES",
inputs: ["SPACE"],
value: (function(SPACE){return(
[
['EMPTY', SPACE],
// key, char, turns to if expand up, right, down, left, rotated 180°
['O', '◽︎', 'T', 'R', 'B', 'L', 'O'],
['T', '╨', null, 'TR', 'TB', 'TL', 'B'],
['R', '╞', 'TR', null, 'RB', 'RL', 'L'],
['B', '╥', 'TB', 'RB', null, 'BL', 'T'],
['L', '╡', 'TL', 'RL', 'BL', null, 'R'],
['RB', '╔', 'TRB', null, null, 'RBL', 'TL'],
['BL', '╗', 'TBL', 'RBL', null, null, 'TR'],
['TR', '╚', null, null, 'TRB', 'TRL', 'BL'],
['TL', '╝', null, 'TRL', 'TBL', null, 'RB'],
['TB', '║', null, 'TRB', null, 'TBL', 'TB'],
['RL', '═', 'TRL', null, 'RBL', null, 'RL'],
['TRB', '╠', null, null, null, 'TRBL', 'TBL'],
['TBL', '╣', null, 'TRBL', null, null, 'TRB'],
['TRL', '╩', null, null, 'TRBL', null, 'RBL'],
['RBL', '╦', 'TRBL', null, null, null, 'TRL'],
['TRBL', '╬', null, null, null, null, 'TRBL'],
['NEG', SPACE],
]
)})
},
{
inputs: ["md"],
value: (function(md){return(
md`The index constants above and the \`TILE_INDEX\` below make it easier to answer questions like "if I extend the path to the left here, what does the tile to the right turn to?"
`
)})
},
{
name: "TILE_INDEX",
inputs: ["TILES","KEY"],
value: (function(TILES,KEY)
{
const tileIndexes = {}
TILES.forEach((tile, index) => {
tileIndexes[tile[KEY]] = index
})
return tileIndexes;
}
)
},
{
name: "viewof boardSize",
inputs: ["html"],
value: (function(html){return(
html`<input type="number" value="5" min="5" max="101" step="2">`
)})
},
{
name: "boardSize",
inputs: ["Generators","viewof boardSize"],
value: (G, _) => G.input(_)
},
{
name: "makeInitialBoard",
inputs: ["TILE_INDEX"],
value: (function(TILE_INDEX){return(
function (w, h = w) {
const length = w * h
const board = Array(length)
.fill(TILE_INDEX.EMPTY)
// Start loop in middle of board
board[Math.floor(length / 2)] = TILE_INDEX.O
return board
}
)})
},
{
name: "initialBoard",
inputs: ["makeInitialBoard","boardSize"],
value: (function(makeInitialBoard,boardSize){return(
makeInitialBoard(boardSize)
)})
},
{
inputs: ["md"],
value: (function(md){return(
md`## Logging
For quick visual debugging`
)})
},
{
name: "boardToString",
inputs: ["boardSize","TILES","CHAR"],
value: (function(boardSize,TILES,CHAR){return(
function boardToString (board, w = boardSize) {
let str = ""
if (!board || !board.forEach) return str
board.forEach((tile, index) => {
str += TILES[tile][CHAR]
if ((index+1) % w === 0) {
str += "\n"
}
})
return str
}
)})
},
{
name: "boardToEl",
inputs: ["boardSize","html","boardToString"],
value: (function(boardSize,html,boardToString){return(
function (board, w = boardSize, h = w) {
return html`<pre style="font-size: 25px; line-height: 23px; padding: 0; border: 1px #eee solid; display: inline-block; height: ${h * 23 + 2}px; overflow-y: hidden;"}>${boardToString(board, w)}</pre>`
}
)})
},
{
name: "demoBoard",
value: (function(){return(
[
6, 5, 6, 15, 7, 3, 7,
8, 11, 9, 10, 8, 11, 9,
3, 11, 7, 10, 6, 11, 5,
4, 3, 16, 16, 16, 5, 4,
12, 5, 2, 10, 2, 3, 13,
8, 15, 5, 10, 3, 15, 9,
0, 8, 11, 14, 11, 9, 0
]
)})
},
{
name: "boardToElDemo",
inputs: ["boardToEl","demoBoard"],
value: (function(boardToEl,demoBoard){return(
boardToEl(demoBoard, 7)
)})
},
{
inputs: ["md"],
value: (function(md){return(
md`### 🤔 Second order?
The "walls" in that string are actually the path... maybe expanding it would give a sense of the path better.`
)})
},
{
name: "boardToPathString",
inputs: ["SPACE","boardSize"],
value: (function(SPACE,boardSize)
{
const fourChars =[
[SPACE+SPACE
,SPACE+SPACE], // Space
['╔╗'
,'╚╝'], // O
['║║'
,'╚╝'], // T
['╔═'
,'╚═'], // R
['╔╗'
,'║║'], // B
['═╗'
,'═╝'], // L
['╔═'
,'║╔'], // RB
['═╗'
,'╗║'], // BL
['║╚'
,'╚═'], // TR
['╝║'
,'═╝'], // TL
['║║'
,'║║'], // TB
['══'
,'══'], // RL
['║╚'
,'║╔'], // TRB
['╝║'
,'╗║'], // TBL
['╝╚'
,'══'], // TRL
['══'
,'╗╔'], // RBL
['╝╚'
,'╗╔'], // TRBL
[SPACE+SPACE
,SPACE+SPACE], // NEG
];
return function (board, w = boardSize) {
let arr = [];
let str = ""
for (let i = 0, len = board.length; i < len; i++) {
const tile = board[i];
const row = Math.floor(i / w)
for (let r = 0; r < 2; r++) {
const strIndex = row * 2 + r
if (!arr[strIndex]) {
arr[strIndex] = ""
}
arr[strIndex] += fourChars[tile][r]
}
}
return arr.join("\n")
}
}
)
},
{
name: "boardToPathEl",
inputs: ["boardSize","html","boardToPathString"],
value: (function(boardSize,html,boardToPathString){return(
function (board, w = boardSize, h = w) {
return html`<pre style="font-size: 20px; line-height: 15px; padding: 0; border: 1px #eee solid; display: inline-block; height: ${h * 2 * 15 + 2}px; overflow-y: hidden;"}>${boardToPathString(board, w)}</pre>`
}
)})
},
{
inputs: ["boardToPathEl","demoBoard"],
value: (function(boardToPathEl,demoBoard){return(
boardToPathEl(demoBoard, 7)
)})
},
{
inputs: ["md"],
value: (function(md){return(
md`### Monospace hack
Some systems don't size the box-drawing chararcters at the same width as other characters in a monospace element (ಠ_ಠ). Measure these to check, and decide if \`SPACE\` needs to be another box-drawing character:`
)})
},
{
name: "spaceEl",
inputs: ["html"],
value: (function(html){return(
html`<span style="font-family: monospace;">_</span>`
)})
},
{
name: "boxEl",
inputs: ["html"],
value: (function(html){return(
html`<span style="font-family: monospace;">╬</span>`
)})
},
{
name: "SPACE",
inputs: ["spaceEl","boxEl"],
value: (function(spaceEl,boxEl){return(
spaceEl.getBoundingClientRect().width === boxEl.getBoundingClientRect().width ? ' ' : '─'
)})
},
{
inputs: ["md"],
value: (function(md){return(
md`## Find possible directions to grow
We want all possibilities for a given board step before choosing one with the seeded random number generator. I'm ending up with something like a limited version of the Wave Form Collapse method:
> The neighboring tiles’ possibilities are reduced, according to their compatibility with their newly set neighbor, and then their neighbors’ tiles possibilities are reduced, etc until no more possibilities can be reduced.
– [Rémy 'Trasevol_Dog' Devaux](https://trasevol.dog/2017/09/01/di19/)
`
)})
},
{
name: "findMutations",
inputs: ["boardSize","TILE_INDEX","TILES","OVER","UNDER","LEFT","RIGHT"],
value: (function(boardSize,TILE_INDEX,TILES,OVER,UNDER,LEFT,RIGHT){return(
function findMutations (board, w = boardSize, h = w) {
const potentials = []
for (let index = 0, len = board.length; index < len; index++) {
const tile = board[index];
if (tile !== TILE_INDEX.EMPTY) {
continue;
}
const row = Math.floor(index / w)
const col = index % w
// Can this tile connect with the one under it?
if (row < h - 1) {
const underIndex = index + w
const under = TILES[board[underIndex]]
if (under[OVER]) {
// A mutation is represented as [this index, this tile, that index, that change tile]
potentials.push([index, UNDER, underIndex, TILE_INDEX[under[OVER]]])
}
}
// Over
if (row > 0) {
const overIndex = index - w
const over = TILES[board[overIndex]]
if (over[UNDER]) {
potentials.push([index, OVER, overIndex, TILE_INDEX[over[UNDER]]])
}
}
// Right
if (col < w - 1) {
const rightIndex = index + 1
const rightward = TILES[board[rightIndex]]
if (rightward[LEFT]){
potentials.push([index, RIGHT, rightIndex, TILE_INDEX[rightward[LEFT]]])
}
}
// Left
if (col > 0) {
const leftIndex = index - 1
const leftward = TILES[board[leftIndex]]
if (leftward[RIGHT]){
potentials.push([index, LEFT, leftIndex, TILE_INDEX[leftward[RIGHT]]])
}
}
};
return potentials;
}
)})
},
{
inputs: ["md"],
value: (function(md){return(
md`## Test it, step by step`
)})
},
{
name: "initialMutations",
inputs: ["findMutations","initialBoard"],
value: (function(findMutations,initialBoard){return(
findMutations(initialBoard)
)})
},
{
name: "stepCloneBoard",
inputs: ["findMutations"],
value: (function(findMutations){return(
function (board, randomGen) {
const mutations = findMutations(board)
const mutation = mutations[randomGen(mutations.length)]
const out = board.slice()
out[mutation[0]] = mutation[1]
out[mutation[2]] = mutation[3]
return out;
}
)})
},
{
inputs: ["md"],
value: (function(md){return(
md`Change seed to change the demos:`
)})
},
{
name: "viewof demoStepSeed",
inputs: ["html"],
value: (function(html){return(
html`<input type="text" value="hello">`
)})
},
{
name: "demoStepSeed",
inputs: ["Generators","viewof demoStepSeed"],
value: (G, _) => G.input(_)
},
{
name: "demoStepGen",
inputs: ["makeRandomGenerator","demoStepSeed"],
value: (function(makeRandomGenerator,demoStepSeed){return(
makeRandomGenerator(demoStepSeed)
)})
},
{
name: "firstStep",
inputs: ["stepCloneBoard","initialBoard","demoStepGen"],
value: (function(stepCloneBoard,initialBoard,demoStepGen){return(
stepCloneBoard(initialBoard, demoStepGen)
)})
},
{
name: "firstStepEl",
inputs: ["boardToEl","firstStep"],
value: (function(boardToEl,firstStep){return(
boardToEl(firstStep)
)})
},
{
name: "secondStep",
inputs: ["stepCloneBoard","firstStep","demoStepGen"],
value: (function(stepCloneBoard,firstStep,demoStepGen){return(
stepCloneBoard(firstStep, demoStepGen)
)})
},
{
name: "secondStepEl",
inputs: ["boardToEl","secondStep"],
value: (function(boardToEl,secondStep){return(
boardToEl(secondStep)
)})
},
{
name: "twelveSteps",
inputs: ["makeRandomGenerator","demoStepSeed","initialBoard","boardToEl","stepCloneBoard","html"],
value: (function(makeRandomGenerator,demoStepSeed,initialBoard,boardToEl,stepCloneBoard,html)
{
const stepGen = makeRandomGenerator(demoStepSeed)
let board = initialBoard
const boardEls = [boardToEl(board)]
for (let i=0; i < 11; i++) {
board = stepCloneBoard(board, stepGen)
boardEls.push(boardToEl(board))
}
return html`<div>${boardEls}</div>`
}
)
},
{
inputs: ["md"],
value: (function(md){return(
md`# Solve a board with a seed
Seems like that works 😄 ... let's try to fill a whole board. When you change the seed the board should change.`
)})
},
{
name: "viewof boardDemoSeed",
inputs: ["html"],
value: (function(html){return(
html`<input type="text" value="hello">`
)})
},
{
name: "boardDemoSeed",
inputs: ["Generators","viewof boardDemoSeed"],
value: (G, _) => G.input(_)
},
{
name: "viewof boardDemoSize",
inputs: ["html"],
value: (function(html){return(
html`<input type="number" value="9" min="3" max="101" step="1">`
)})
},
{
name: "boardDemoSize",
inputs: ["Generators","viewof boardDemoSize"],
value: (G, _) => G.input(_)
},
{
name: "solveSync",
inputs: ["makeRandomGenerator","findMutations"],
value: (function(makeRandomGenerator,findMutations){return(
function solveSync (seed, board, w, h = w) {
const random = makeRandomGenerator(seed)
let mutations = findMutations(board, w, h)
while (mutations.length) {
const mutation = mutations[random(mutations.length)]
board[mutation[0]] = mutation[1]
board[mutation[2]] = mutation[3]
mutations = findMutations(board, w, h)
}
return board
}
)})
},
{
name: "solvedEl",
inputs: ["boardToPathEl","solveSync","boardDemoSeed","makeInitialBoard","boardDemoSize"],
value: (function(boardToPathEl,solveSync,boardDemoSeed,makeInitialBoard,boardDemoSize){return(
boardToPathEl(solveSync(boardDemoSeed, makeInitialBoard(boardDemoSize), boardDemoSize), boardDemoSize)
)})
},
{
inputs: ["md"],
value: (function(md){return(
md`Import \`makeRandomGenerator\`: a seeded random number generator ([random-seed](https://www.npmjs.com/package/random-seed) on npm, [demos and viz on Observable](https://beta.observablehq.com/@forresto/random-seed)):`
)})
},
{
from: "@forresto/random-seed",
name: "makeRandomGenerator",
remote: "makeRandomGenerator"
},
{
name: "viewof inputSeed",
inputs: ["html"],
value: (function(html){return(
html`<input type="text" value="hello">`
)})
},
{
name: "inputSeed",
inputs: ["Generators","viewof inputSeed"],
value: (G, _) => G.input(_)
},
{
inputs: ["md"],
value: (function(md){return(
md`# Asynchronous generation and animation
Part of the inspiration to do another version of this generative thing was [Mike Bostock's Introduction to Asynchronous Iteration](https://beta.observablehq.com/@mbostock/introduction-to-asynchronous-iteration) article. I haven't gotten a chance to use these concepts in my everyday programming so far.
Also, it's fun to watch a labyrinth grow from the initial seed. Solving the labyrinth gets noticeably slow at sizes >30, so we might as well animate the solving instead of freezing the browser.
Change the seed to see it animate:
`
)})
},
{
name: "viewof asyncDemoSeed",
inputs: ["html"],
value: (function(html){return(
html`<input type="text" value="hello">`
)})
},
{
name: "asyncDemoSeed",
inputs: ["Generators","viewof asyncDemoSeed"],
value: (G, _) => G.input(_)
},
{
name: "viewof asyncDemoSize",
inputs: ["html"],
value: (function(html){return(
html`<input type="number" value="9" min="3" max="101" step="1">`
)})
},
{
name: "asyncDemoSize",
inputs: ["Generators","viewof asyncDemoSize"],
value: (G, _) => G.input(_)
},
{
name: "solveAsync",
inputs: ["makeRandomGenerator","findMutations"],
value: (function(makeRandomGenerator,findMutations){return(
async function* solveAsync (seed, board, w, h = w) {
const random = makeRandomGenerator(seed)
let mutations = findMutations(board, w, h)
while (mutations.length) {
const mutation = mutations[random(mutations.length)]
board[mutation[0]] = mutation[1]
board[mutation[2]] = mutation[3]
mutations = findMutations(board, w, h)
// This is optional... Observable already throttles to rAF
// await Promises.delay(1000/60)
yield board
}
}
)})
},
{
inputs: ["makeInitialBoard","asyncDemoSize","pauser","boardToPathEl","solveAsync","asyncDemoSeed"],
value: (async function*(makeInitialBoard,asyncDemoSize,pauser,boardToPathEl,solveAsync,asyncDemoSeed)
{
let board = makeInitialBoard(asyncDemoSize)
yield* pauser(boardToPathEl(board, asyncDemoSize));
const boardGen = solveAsync(asyncDemoSeed, board, asyncDemoSize)
while (true) {
const {done, value} = await boardGen.next();
if (done) return;
yield boardToPathEl(value, asyncDemoSize);
}
}
)
},
{
inputs: ["md"],
value: (function(md){return(
md`## Hey
It works 🎉
Future ideas:
* [x] symmetry
* [ ] nice rendering
* [ ] speed
* don't find all mutations for each step, rather start on a random tile?
* or a generator for mutations to only need to calculate the one we want?
* more than 1 step per animation frame? 👈 would be easy but make it harder to see the growth.
* [ ] non-square tiles
* [ ] non-planar board
* [x] https://beta.observablehq.com/@tmcw/pauser to start animations once cell is in view
`
)})
},
{
name: "pauser",
value: (function(){return(
function* pauser(element) {
// From https://beta.observablehq.com/@tmcw/pauser to make the animations below start on scroll
yield element;
// Just in case the element is too tall
element.parentNode.style.maxHeight = '5vh'
element.parentNode.style.overflow = 'auto'
// Some browsers (Safari) don't support this feature yet, so fall back
// to how this notebook would work without pauser doing its thing.
if (!window.IntersectionObserver) return;
yield new Promise(resolve => {
let observer = (new window.IntersectionObserver(([entry]) => {
entry.isIntersecting && (observer.disconnect(), resolve(element))
}, { threshold: 0.9 }));
observer.observe(element.parentNode)
});
}
)})
},
{
inputs: ["md"],
value: (function(md){return(
md`# Multiple paths in one board
This would not work with my last labyrith drawing code, which was built around one "linked-loop" path. Starting from tiles in this version, it's free.
Change the seed:
`
)})
},
{
name: "viewof multipleDemoSeed",
inputs: ["html"],
value: (function(html){return(
html`<input type="text" value="hello">`
)})
},
{
name: "multipleDemoSeed",
inputs: ["Generators","viewof multipleDemoSeed"],
value: (G, _) => G.input(_)
},
{
name: "viewof multipleDemoW",
inputs: ["html","width"],
value: (function(html,width){return(
html`<input type="number" value="${Math.floor(width / 19 / 2) * 2 + 1}" min="3" max="101" step="1">`
)})
},
{
name: "multipleDemoW",
inputs: ["Generators","viewof multipleDemoW"],
value: (G, _) => G.input(_)
},
{
name: "viewof multipleDemoH",
inputs: ["html"],
value: (function(html){return(
html`<input type="number" value="17" min="3" max="101" step="1">`
)})
},
{
name: "multipleDemoH",
inputs: ["Generators","viewof multipleDemoH"],
value: (G, _) => G.input(_)
},
{
name: "makeMultipleStartBoard",
inputs: ["makeInitialBoard"],
value: (function(makeInitialBoard){return(
function (w, h) {
const b = makeInitialBoard(w, h)
b[0] = 1
b[w - 1] = 1
b[b.length - 1] = 1
b[b.length - w] = 1
return b;
}
)})
},
{
inputs: ["makeMultipleStartBoard","multipleDemoW","multipleDemoH","pauser","boardToEl","solveAsync","multipleDemoSeed"],
value: (async function*(makeMultipleStartBoard,multipleDemoW,multipleDemoH,pauser,boardToEl,solveAsync,multipleDemoSeed)
{
let board = makeMultipleStartBoard(multipleDemoW, multipleDemoH)
yield* pauser(boardToEl(board, multipleDemoW, multipleDemoH));
const boardGen = solveAsync(multipleDemoSeed, board, multipleDemoW, multipleDemoH)
while (true) {
const {done, value} = await boardGen.next();
if (done) return;
yield boardToEl(value, multipleDemoW, multipleDemoH);
}
}
)
},
{
inputs: ["md"],
value: (function(md){return(
md`# Outside in
Instead of a seed in the middle, start with a (double) path around the outside.
`
)})
},
{
name: "makeInitialBoardPathAround",
inputs: ["TILE_INDEX"],
value: (function(TILE_INDEX){return(
function makeInitialBoardPathAround (w, h = w) {
const length = w * h
const board = [];
for (let i = 0; i < length; i++) {
if (i === 0) {
board[i] = TILE_INDEX.RB
} else if (i === w - 1) {
board[i] = TILE_INDEX.BL
} else if (i === length - w) {
board[i] = TILE_INDEX.TR
} else if (i === length - 1) {
board[i] = TILE_INDEX.TL
} else if (i < w || i > length - w) {
board[i] = TILE_INDEX.RL
} else if (i % w === 0 || (i + 1) % w === 0){
board[i] = TILE_INDEX.TB
} else {
board[i] = 0
}
}
return board
}
)})
},
{
name: "viewof outDemoSeed",
inputs: ["html"],
value: (function(html){return(
html`<input type="text" value="hello">`
)})
},
{
name: "outDemoSeed",
inputs: ["Generators","viewof outDemoSeed"],
value: (G, _) => G.input(_)
},
{
name: "viewof outDemoSize",
inputs: ["html"],
value: (function(html){return(
html`<input type="number" value="13" min="3" max="101" step="1">`
)})
},
{
name: "outDemoSize",
inputs: ["Generators","viewof outDemoSize"],
value: (G, _) => G.input(_)
},
{
inputs: ["makeInitialBoardPathAround","outDemoSize","pauser","boardToPathEl","solveAsync","outDemoSeed"],
value: (async function*(makeInitialBoardPathAround,outDemoSize,pauser,boardToPathEl,solveAsync,outDemoSeed)
{
let board = makeInitialBoardPathAround(outDemoSize)
yield* pauser(boardToPathEl(board, outDemoSize));
const boardGen = solveAsync(outDemoSeed, board, outDemoSize)
while (true) {
const {done, value} = await boardGen.next();
if (done) return;
yield boardToPathEl(value, outDemoSize);
}
}
)
},
{
inputs: ["md"],
value: (function(md){return(
md`# Negative space
By adding a tile type that isn't considered empty, the labyrinth will fill in around it.
`
)})
},
{
name: "viewof negDemoWidth",
inputs: ["html"],
value: (function(html){return(
html`<input type="number" value="11" min="3" max="101" step="1">`
)})
},
{
name: "negDemoWidth",
inputs: ["Generators","viewof negDemoWidth"],
value: (G, _) => G.input(_)
},
{
name: "viewof negDemoHeight",
inputs: ["html"],
value: (function(html){return(
html`<input type="number" value="9" min="3" max="101" step="1">`
)})
},
{
name: "negDemoHeight",
inputs: ["Generators","viewof negDemoHeight"],
value: (G, _) => G.input(_)
},
{
inputs: ["md"],
value: (function(md){return(
md`
* Click to toggle negative space
* Shift-click to toggle path starts
`
)})
},
{
name: "viewof negSpace",
inputs: ["negDemoWidth","negDemoHeight","TILE_INDEX","html"],
value: (function(negDemoWidth,negDemoHeight,TILE_INDEX,html)
{
const board = Array(negDemoWidth * negDemoHeight).fill(TILE_INDEX.EMPTY)
board[0] = TILE_INDEX.O
const middle = Math.floor(board.length / 2)
board[middle] = TILE_INDEX.NEG
board[middle - 1] = TILE_INDEX.NEG
board[middle + 1] = TILE_INDEX.NEG
board[middle - negDemoWidth] = TILE_INDEX.NEG
board[middle + negDemoWidth] = TILE_INDEX.NEG
function toString (board, width) {
return board.map((t, i) => {
let char = ''
switch (t) {
case TILE_INDEX.O:
char = '🔘'
break
case TILE_INDEX.NEG:
char = '⬛️'
break
default:
char = '⬜️'
}
if (i > 0 && ((i + 1) % width) === 0) char += "\n"
return char
}).join('')
}
const el = html`<pre style="display: inline-block; font-size: 20px; line-height: 1; margin: 0; padding: 0; cursor: pointer;">${toString(board, negDemoWidth)}</pre>`
el.onclick = (event) => {
const {layerX, layerY, shiftKey} = event;
const {width, height} = el.getBoundingClientRect();
const row = Math.floor(layerY / height * negDemoHeight)
const col = Math.floor((layerX - 10) / width * negDemoWidth)
const index = row * negDemoWidth + col
if (board[index] === undefined) return
if (shiftKey) {