-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.html
874 lines (701 loc) · 28.6 KB
/
index.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
<!DOCTYPE html>
<html>
<head>
<title> Implementing Snake in Bacon.js </title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="bacon.js"> </script>
<script type="text/javascript" src="tickscheduler.js"></script>
<script type="text/javascript">
window.sc = new TickScheduler()
window.oldTimer = Bacon.scheduler
Bacon.scheduler = window.sc
</script>
<link href="tmp.css" rel="stylesheet" type="text/css">
<link href="snake.css" rel="stylesheet" type="text/css">
<link href="marble.css" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Droid+Sans+Mono' rel='stylesheet' type='text/css'>
<script type="text/javascript">
var clicky_site_ids = clicky_site_ids || [];
clicky_site_ids.push(100617914);
(function() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = '//static.getclicky.com/js';
( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( s );
})();
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-41227591-1', 'philipnilsson.github.io');
ga('send', 'pageview');
</script>
</head>
<body>
<div class="header">
<div id="header-text-wrapper">
<h1> Badness 10k
<a href="https://twitter.com/ali_pang">
<img width="40px" src="https://abs.twimg.com/a/1377795275/images/resources/twitter-bird-dark-bgs.png" style="float: right"/>
<p style="font-size: small; float: right; color: #dddddd"> Follow me on twitter. </p>
</a>
</h1>
</div>
</div>
<article class="content">
<h2> Implementing Snake in Bacon.js </h2>
<p class="intro"> In this post we're going to explore the awesome
reactive programming
library <a href="https://github.com/raimohanska/bacon.js">
Bacon.js</a> by implementing the classic game Snake, which you may
have played on your Nokia back in the good old days, before this
modern fad of "smart" phones that break when you drop them on the
floor.</p>
<div style="float: right; margin-left: 1em">
<img border="0" width="320" src="https://raw.github.com/baconjs/bacon.js/master/logo.png" style="float: right;">
</div>
<p> Bacon.js is a javascript library for doing reactive programming,
much like Microsoft's Rx. The fundamental abstraction here are
observable event streams. Streams are similar to promises, except
that they represent a series of multiple events. Using streams
allows simple expression of behaviour that span over time and
multiple events </p>
<p> Writing a game with streams is a great way to get more familiar
with the event stream abstraction. You can go on to use it to
structure any asynchronous programming task, such as your ajax or
node callbacks. </p>
<p> <i> Note: In this post I'll be using typescript notation for
lambdas, e.g. the addition function will be written </i> <code> (x,y) => x +
y.</code> </p>
<h3> Marble diagrams </h3>
<p> When dealing with streams of events we often document the result
of operations in terms of marble diagrams. Below is a marble diagram
for the <code>merge</code> operation, that takes two event
streams, <code> </code> and <code> b </code> and
produces a stream containing the events from both streams. </p>
<style type="text/css">
h3 {
color: #404040;
margin-top: 1em;
}
</style>
<div class="bacon-marble">
<div class="bacon-input" x-bacon-input="Bacon.sequentially(200, [9,0,2,0,0,3]).filter(function(x) { return x })"> </div>
<div class="bacon-input" x-bacon-input="Bacon.sequentially(200, [0,1,0,12,8,0]).filter(function(x) { return x })"> </div>
<div class="bacon-output" x-bacon-output="function(a,b) { return a.merge(b) }"></div>
</div>
<div class="bacon-label"> <code> a.merge(b) </code> <br /> </div>
<h3> Getting a hold of events </h3>
<p>The first thing we need to do is get our hands some events so we
have something to play with. For starters we'll skip the keyboard
events and timers and just use buttons, so we can step through the
game easily.</p>
<p>Bacon.js provides a single integration point with jQuery via
the <code>$.fn.asEventStream</code> function. This takes the event
name and creates a corresponding event stream as so:
<pre class="inline"> var clicks = $('#myButton').asEventStream('click')
</pre>
<p> This, of course, gives us a stream of events that occur each time
we click <code>myButton</code>. The contents of the events will be jQuery
click-events. </p>
<h3> Subscribing </h3>
<p> In order to actually do anything with these events we need to <i>
subscribe </i> to the event stream. We can do this with
the <code>onValue</code> method. This takes a callback to execute
for each event from the stream. </p>
<pre class="inline">
clicks.onValue(() => alert('clicked!'))
</pre>
<p>It might seem confusing that we're already talking about
callbacks. Bacon.js is supposed to let us escape from callback
hell. However, Bacon lets us manage event streams through
various <i> combinators </i>, like the already
mentioned <code>merge</code>. We will look at these next. For now
we are at least separating the concerns of defining what events
take place, and how we react to them. </p>
<p> Here's an example of what we've learned so far, just doing some
simple DOM manipulation with jQuery. Of course, this could have been
just as easily implemented using a callback.</p>
<style type="text/css">
.example {
padding: 1em;
margin: 0.5em 0;
}
.ex {
margin-top: 1em;
padding: 1em;
background-color: rgb(239,240,242);
clear: both;
}
pre {
padding: 1em 1em;
margin: 1em 0;
}
.inline {
border: none;
background-color: rgb(239,240,242);
}
h1, h3, h3 {
font-weight: normal;
clear: both;
}
pre, code {
word-wrap: normal;
}
code {
color: #0000aa;
}
</style>
<div class="ex" id="example1">
<div class="example">
<button id="go"> Click me! </button>
<div class="output"> </div>
</div>
<script type="text/javascript">
var go = $('#go').asEventStream('click');
go.onValue(function() { $('#example1 .output').append('clicked! '); })
</script>
<pre>var go = $('#clickMe').asEventStream('click');
go.onValue (
() => $('#output').append('clicked!'))
</pre>
</div>
<p> Ok, so hardly amazing. The point of Bacon is to use combinators to
structure event streams, so lets take a look at some. </p>
<h3> Map </h3>
<p> One of the simplest combinators in Bacon is <code>map</code>. This
lets us apply a function to the values inside a stream. In the code
above we didn't look at the value inside the stream at any point, but
that value would have been a jQuery event, as it came
from <code>asEventStream</code>.
</p>
<div class="bacon-marble">
<div class="bacon-input" x-bacon-input="Bacon.sequentially(200, [1,2,3,4,5])"> </div>
<div class="bacon-output" x-bacon-output="function(a) { return a.map(function(x) { return x + 1}) }"></div>
</div>
<div class="bacon-label"> <code> stream.map(x => x + 1) </code> <br /> </div>
<p> If the argument to <code>map</code> is not a function, Bacon will
assume you mean the constant function which returns that value. This
is often useful in combination with <code>asEventStream</code> as
we're often not interested in the actual jQuery event. </p>
<div class="bacon-marble">
<div class="bacon-input" x-bacon-input="Bacon.sequentially(200, [1,2,3,4,5])"> </div>
<div class="bacon-output" x-bacon-output="function(a) { return a.map('x') }"></div>
</div>
<div class="bacon-label"> <code> stream.map('x') </code> <br /> </div>
<h3> Scan </h3>
<p> Bacon's <code>scan</code> combinator lets us accumulate
values. This works a lot like javascript's <code>reduce</code> over
arrays, except its asynchronous and produces multiple values over
time. To use it, we provide an initial value, and a function to
combine values. The stream now contains the aggregated value at each
point.</p>
<div class="bacon-marble">
<div class="bacon-input" x-bacon-input="Bacon.sequentially(200, [1,2,3,4,5])"> </div>
<div class="bacon-output" x-bacon-output="function(a) { return a.scan(0, function(x,y) { return x + y }) }"></div>
</div>
<div class="bacon-label"> <code> stream.scan(0, (x,y) => x + y) </code> <br /> </div>
Scan lets us implement map-reduce style functions over time. This
class of functions include things like taking a sum, minimum or
maximum, or accumulating function effects.
<div class="ex" id="example2">
<div class="example">
<button> Count up </button>
<div class="output"> </div>
<script type="text/javascript">
var clicks = $('#example2 button').asEventStream('click')
var counter = clicks
.map(1)
.scan(0, function(x,y) { return x + y })
counter.onValue(function(x) { $('#example2 .output').html(x) })
</script>
</div>
<pre>
var clicks = $('#example2 button').asEventStream('click')
var counter = clicks
.map(1)
.scan(0, (x,y) => x + y)
counter.onValue(x => $('#example2 .output').html(x))
</pre>
</div>
<p> Here we use <code>map</code> to create an event stream of ones for
each click event. We then chain the <code>scan</code> combinator to
create a new event stream containing the accumulated sum.</p>
<h3> Merge</h3>
<p> We've already seen the merge combinator. To remind you, it merges
two event-streams into one containing the events from both
streams. </p>
<div class="bacon-marble">
<div class="bacon-input" x-bacon-input="Bacon.sequentially(200, [9,0,2,0,0,3]).filter(function(x) { return x })"> </div>
<div class="bacon-input" x-bacon-input="Bacon.sequentially(200, [0,1,0,12,8,0]).filter(function(x) { return x })"> </div>
<div class="bacon-output" x-bacon-output="function(a,b) { return a.merge(b) }"></div>
</div>
<div class="bacon-label"> <code> streamA.merge(streamB) </code> <br /> </div>
<h3> Scanning function effects </h3>
<p>
Ok, se lets begin our first effort towards implementing the game. One
of the most common patterns when using Observables is to
use <code>scan</code> to accumulate effects of functions. What this
means, is that we create an event stream that <i> contain functions as
its values. </i>
</p>
<p>Here's a marble diagram containing the functions <code>
double</code> and <code>inc</code>, that doubles and increments its
arguments, where we scan with function application.</p>
<script type="text/javascript">
var double = function(x) { return x * 2 }
double.describe = "double"
var inc = function(x) { return x + 1 }
inc.describe = "inc"
</script>
<div class="bacon-marble">
<div class="bacon-input" x-bacon-input="Bacon.sequentially(200, [double,inc,inc,double,inc])"> </div>
<div class="bacon-output" x-bacon-output="function(a) { return a.scan(2, function(x,f) { return f(x) }) }"></div>
</div>
<div class="bacon-label"> <code> stream.scan(2, (x,f) => f(x)) </code> <br /> </div>
<p> We'll start off by defining the functions we'd like to
accumulate. We're going to want to be able to control the snake by
changing directions, so we'll define functions for that. </p>
<pre class="inline">function rotateLeft(pos) {
return new Vector2(pos.y, -pos.x)
}
function rotateRight(pos) {
return new Vector2(-pos.y, pos.x)
}</pre>
<p>We introduce two buttons for rotating left and right, and get
the click event streams. </p>
A stream is needed that contains e.g.
the <i>function</i> <code>rotateLeft</code> for each time the user
clicks the left button.
We accomplish this by using <code>map</code>. However, we don't want
Bacon to apply that function, so we supply the lambda <code>() =>
rotateLeft</code>.
<pre class="inline">
var lefts = $("button.left").asEventStream('click')
var rights = $("button.right").asEventStream('click')
var actions =
lefts.map(() => rotateLeft).merge(
rights.map(() => rotateRight))
</pre>
<p>We now accumulate the effects of the rotations from a starting
value, <code>startDirection</code>. </p>
<pre class="inline">
var startDirection = new Vector2(0,1)
var direction = actions.scan(startDirection, (x, f) => f(x))
</pre>
<h3> SampledBy </h3>
<p> Sometimes we want to take the events from one stream, but receive
events according to another signal. We can do this through the use
of the <code>sampledBy</code> combinator. </p>
<div class="bacon-marble">
<div class="bacon-input" x-bacon-input="Bacon.sequentially(200, [1,2,0,5,0,12,1,0]).filter(function(x){return x}).toProperty(10)"> </div>
<div class="bacon-input" x-bacon-input="Bacon.sequentially(200, [0,0,'t',0,'t',0,0,'t']).filter(function(x){return x})"> </div>
<div class="bacon-output" x-bacon-output="function(a,b) { return a.sampledBy(b) }"></div>
</div>
<div class="bacon-label"> <code> streamA.sampledBy(streamB) </code> <br /> </div>
<p> Technically, Bacon requires you to
<p>Back to the game: In order to get a current position, we need to
accumulate the current direction. We'd like to advance the game on
a timed signal, we're going to call <code>tick</code>. Lets again
define it as the input of a button, before changing it to a timer
later.</p>
<pre class="inline">
var tick = $('#tick').asEventStream('click')
</pre>
<p>Now we'd like to advance the position in the
current <code>direction</code>, but with the advances timed
according to the <code>tick</code> stream. We make use of
the <code>sampledBy</code> combinator.</p>
<pre class="inline">
var currentDirection = direction.sampledBy(tick)
</pre>
<p> Of course, to get a current position, we now simply scan the
current direction from a starting postion, <code>startPosition</code>. </p>
<pre class="inline">
var startPosition = new Vector2(0,0)
var position = currentDirection.scan(
startPosition, (x, y) => x.add(y))
</pre>
We'll finally visualize what's going on by drawing out the current
position. We'll map the single position into an array before passing
it to the snake-drawing routine, as this expects an array.
<pre class="inline">
position.map(Array).onValue(drawSnake)
</pre>
Here's the Bacon code so far.
<div class="ex" id="example3">
<script type="text/javascript">
var gameX = 7;
var gameY = 7;
function drawGame(sel) {
var game = $(sel)
for (var i = 0; i < gameX; i++) {
var row = $('<div/>').addClass('row')
game.append(row)
for (var j = 0; j < gameY; j++)
row.append($('<div/>').addClass('cell'))
}
}
function drawSnake(sel) {
var game = $(sel)
return function(ps) {
game.find('.cell').removeClass('snake')
for (var i in ps) {
game.find('.row:eq('+ps[i].y+')').find('.cell:eq('+ps[i].x+')').addClass('snake')
}
}
}
function drawApple(sel) {
var game = $(sel)
return function(p) {
game.find('.cell').removeClass('apple')
game.find('.row:eq('+p.y+')').find('.cell:eq('+p.x+')').addClass('apple')
}
}
function Vector2(x, y) {
this.x = x; this.y = y;
this.describe = x + ', ' + y
this.equals = function(p) { return this.x === p.x && this.y === p.y }
this.add = function(p) { return new Vector2((this.x + p.x + gameX) % gameX, (this.y + p.y + gameX) % gameX) }
}
randomPos = function() {
return new Vector2(Math.floor(Math.random() * 5), Math.floor(Math.random() * 5))
}
function rotateRight(pos) {
return new Vector2(-pos.y, pos.x)
}
function rotateLeft(pos) {
return new Vector2(pos.y, -pos.x)
}
</script>
<div class="example">
<button class="left" > Left </button>
<button class="right" > Right </button>
<button class="tick" > Tick </button>
<div>Direction: <span class="dir"></span></div>
<div>Position: <span class="pos"></span></div>
<div><div class="game"></div></div>
<script type="text/javascript">
var makeGame = function(selector, bindKeyTimer) {
var ex = $(selector)
if (!bindKeyTimer) {
var lefts = ex.find('.left').asEventStream('click')
var rights = ex.find('.right').asEventStream('click')
var tick = ex.find('.tick').asEventStream('click')
}
else {
var keys = $(document).asEventStream('keydown').map('.keyCode')
var lefts = keys.filter(function(x) { return x === 37 })
var rights = keys.filter(function(x) { return x === 39 })
var tick = Bacon.interval(300)
}
var actions =
lefts.map(function() { return rotateLeft }).merge(
rights.map(function() { return rotateRight }))
var startDirection = new Vector2(0,1),
startPosition = new Vector2(0,0)
var direction = actions.scan(startDirection, function(x, f) { return f(x) })
var position = direction
.sampledBy(tick)
.scan(startPosition, function(x,y) { return x.add(y) });
direction.onValue(function(x) { ex.find('.dir').html(x.describe) })
position.onValue(function(x) { ex.find('.pos').html(x.describe) })
drawGame(selector + ' .game')
return position;
}
var pos = makeGame('#example3')
pos.map(Array).onValue(drawSnake('#example3 .game'))
</script>
</div>
<pre>
var lefts = $('#example3 .left').asEventStream('click'),
rights = $('#example3 .right').asEventStream('click'),
tick = $('#example3 .tick').asEventStream('click')
var actions =
lefts.map(() => rotateLeft).merge(
rights.map(() => rotateRight))
var startDirection = new Vector2(0,1),
startPosition = new Vector2(0,0)
var direction = actions.scan(startDirection, (x, f) => f(x) )
var position = direction
.sampledBy(tick)
.scan(startPosition, (x,y) => x.add(y));
position.map(Array).onValue(drawSnake)
</pre>
</div>
<h3> SlidingWindow </h3>
<p>Bacon already has a combinator for creating a sliding (or should we
say slithering, hur hur) window of the nth latest values. Lets try
and apply it.</p>
<div id="example4" class="ex">
<div class="example">
<button class="left" > Left </button>
<button class="right" > Right </button>
<button class="tick" > Tick </button>
<div><div class="game"></div></div>
</div>
<pre>
var snake = position.slidingWindow(3)
snake.onValue(drawSnake)</pre>
</div>
<script type="text/javascript">
var pos = makeGame('#example4')
pos.slidingWindow(3).onValue(drawSnake('#example4 .game'))
</script>
<p>Ok, so pretty cool, though it only gets us so far, as there is no way
to increase the length. We'll need to implement the possibility of
eating fruit.</p>
<h3> Filter </h3>
The filter combinator, like map is much like the operation on arrays,
and filters out events according to a predicate.
<div class="bacon-marble">
<div class="bacon-input" x-bacon-input="Bacon.sequentially(200, [9,1,2,10,2,3])"> </div>
<div class="bacon-output" x-bacon-output="function(a) { return a.filter(function(x) { return x > 2 }) }"></div>
</div>
<div class="bacon-label"> <code> stream.filter(x => x > 2) </code> </div>
<h3> Take / Skip </h3>
<p> The <code>take</code> and <code>skip</code> combinators allows you
to take or skip a certain number of elements from the start of an
event stream, much in the same way as array slicing.</p>
<div class="bacon-marble">
<div class="bacon-input" x-bacon-input="Bacon.sequentially(200, [9,1,2,10,2,3])"> </div>
<div class="bacon-output" x-bacon-output="function(a) { return a.skip(3) }"></div>
</div>
<div class="bacon-label"> <code> stream.skip(3) </code> </div>
<h3> Event Switching </h3>
If you're following along so far you might figure we'd implement
something along the lines of the following.
<pre class="inline">
var applePos = new Vector2(3,3)
var apple = position
.filter(p => p.equals(applePos))
.take(1)
</pre>
<p>This gets us the first event where the position of the snake is the
same as the position of the apple. But how do we proceed from there?
At this point we must somehow "move" the position of the apple, but as
Bacon is essentially a functional library, we have no way of doing so
in terms of side-effects, which would be more familiar to most
programmers. </p>
<p> The solution to this problem will come in terms of event
switching, a common and very important idiom in reactive
programming. Essentially this lets implement functionality on the type
<i>"when x happens, start doing Y"</i>. x here will be an event, and Y will
be an event-stream of the new events you're interested in. </p>
<p> Of course, the event <code>x</code> will in turn come from some
event-stream <code>X</code>, as much of the point of Bacon is that we
don't write program in terms of individual events.
Event switching is implemented in Bacon primarily through the
function <code>flatMapLatest</code></p>
<h3> FlatMapLatest </h3>
<p>The <code>flatMapLatest</code> combinator takes an
event-stream <code>X</code>, and from each event <code>x</code> in it,
maps it to a new event-stream <code>f(x)</code>, for a specified
function <code>f</code>.</p>
<div class="bacon-marble">
<div class="bacon-input" x-bacon-input="Bacon.sequentially(400, [9,1,2,10]).filter(function(x) { return x })"> </div>
<div class="bacon-output" x-bacon-output="function(a) { return a.flatMapLatest(function(x) { return Bacon.sequentially(150,[x,x+1,x+2]) }) }"></div>
</div>
<div class="bacon-label"> <code> stream.flatMapLatest(x => Bacon.sequentially(100, [x, x+1, x+2]) </code> </div>
<p> Here we map each numeric event <code>x</code> to the event-stream <code>[x, x+1,
x+2]</code>. However, the delays are set such that the next event from
the source stream occurs before the <code>x+2</code> event, so it is
skipped. Only on the last event <code>10</code>, there are no more
events from the source stream, so all the events for <code>10, 11,
12</code> appear in the output stream</p>
<p>Essentially, when an event <code>x</code> occurs in stream <code>X</code>, the
resulting stream "switches" to <code>f(x)</code>.</p>
<p>Now, one solution to our problem is to define an event-stream that
is recursive in terms of itself. As javascript does not have
laziness, we simply promote the apple stream to an argument-less
function returning a stream, and pass that function
to <code>flatMapLatest</code>
</p>
<pre class="inline">
function apple() {
var applePos = randomPos()
return
position
.filter(p => p.equals(applePos))
.take(1)
.flatMapLatest(apple)
.toProperty(applePos)
}
</pre>
<p> That is, whenever the snake eats the apple, we switch to a new
event-stream, which is the same stream as before, but with the apple
in a new randomized position. We also call <code>toProperty</code>,
which starts the stream with the apple's position. Without this, there
would be no values in the stream. </p>
<p> Note that we define the entire behaviour of the apple value
here. In a more imperative setting, this value would be updated
from a multitude of places in the code as a reaction to the
appropriate event. This has some advantages, and some drawbacks in
it being less natural to a developer more used to imperative programming. </p>
<p> In fact, event streams are quite similar to values in a
spreadsheet, where we might write something like <code>A1 = B1 +
C2</code>. The value <code>A1</code> defines <i>itself</i> in
terms of other cells in the spreadsheet, and is never updated from
an external location.</p>
<p> Here's what we have so far. </p>
<div id="example5" class="ex">
<div class="example">
<button class="left" > Left </button>
<button class="right" > Right </button>
<button class="tick" > Tick </button>
<div> <div class="game"></div> </div>
</div>
</div>
<script type="text/javascript">
(function() {
var pos = makeGame('#example5')
var apple = function() {
var applePos = randomPos()
return pos.
filter(function(x) { return x.equals(applePos) }).
take(1).
flatMapLatest(apple).
toProperty(applePos)
}
pos.slidingWindow(3).onValue(drawSnake('#example5 .game'))
apple().onValue(drawApple('#example5 .game'))
})()
</script>
<h3> Increasing the length </h3>
<p> Ok, so each time we eat an apple we want to increase the length of
the snake by one. We want something like
the <code>slidingWindow</code> combinator, except we want the window
size to grow dynamically according to some other stream, but such a
combinator does not exist in Bacon. Time to create our own combinator!
</p>
<h3> Implementing custom combinators </h3>
<p> One typically adds to the Bacon prototype in order to be able to use
the nice DSL style we're accustomed to. </p>
<p> Here's how we implement a custom combinator in Bacon. We're going
to take as argument an observable that decides the length of the
window. </p>
<pre class="inline">
Bacon.Observable.prototype.slidingWindowBy = function(lengthObs) {
var self = this
return new Bacon.EventStream(sink => {
var buf = []
var length = 0
self.onValue(x => {
buf.unshift(x)
buf = buf.slice(0, length)
sink(new Bacon.Next(buf))
})
lengthObs.onValue(n => {
length = n
})
})
}
</pre>
<p> What we do is simply to return a new event-stream. As argument to
the constructor, we give a parameter <code>sink</code> that is a
function. We send new events by invoking this function with the next
value. Bacon has three type of
events, <code>Next</code>, <code>End</code>
and <code>Error</code>. Right now we're only interested in
the <code>Next</code> type of events, which we specify by create a
new <code>Bacon.Next</code> event to wrap the value that we want to
send, in this case the current "window".
</p>
<p>
When we get a length value, we do nothing except for updating the
length value, and so we don't call the sink function with anything.
</p>
<p> This is of course quite a bit of code for something fairly simple,
but I hope you appreciate how we've nicely encapsulated a pattern
here, that is easily re-usable later if we'd like. This is typical
of coding in this style. Abstracting over <i> streams </i> of events
allow us to encapsulate many more behaviours than if we limit
ourselves to something like promises. </p>
<p> So below is our, for now, final version of the game. The remaining
features are left as an exercise for the reader to familiarize herself
further with Bacon.js. </p>
<p> Hope you enjoyed following along in this tutorial. Here's out
final version of the game with code. If you want to cheat and
check out the finished version, you can play
it <a href="http://philipnilsson.github.io/Snake-Bacon/">here.</a>
</p>
<div id="example6" class="ex">
<p style="font-size: small"> Use left/right to steer. You can't die in this version,
try finishing the game yourself. </p>
<div class="example">
<button class="start" > Start </button>
<div><div class="game"></div></div>
</div>
<pre>
var lefts = $('#example3 .left').asEventStream('click'),
rights = $('#example3 .right').asEventStream('click'),
tick = $('#example3 .tick').asEventStream('click')
var actions =
lefts.map(() => rotateLeft).merge(
rights.map(() => rotateRight))
var startDirection = new Vector2(0,1),
startPosition = new Vector2(0,0)
var direction = actions.scan(startDirection, (x,f) => f(x))
var position = direction
.sampledBy(tick)
.scan(startPosition, function(x,y) { return x.add(y) });
function apple() {
var applePos = randomPos()
return
position
.filter(p => p.equals(applePos))
.take(1)
.flatMapLatest(apple)
.toProperty(applePos)
}
var appl = apple()
var length = appl.map(1).scan(1, (x,y) => x + y )
pos.slidingWindowBy(length)
.onValue(drawSnake)
appl.onValue(drawApple)
</pre>
</div>
<script type="text/javascript">
var gameStarted = false;
$('#example6 .start').click(function() {
if (gameStarted)
return;
gameStarted = true;
Bacon.scheduler = window.oldTimer;
Bacon.Observable.prototype.slidingWindowBy = function(lengthObs) {
var self = this
return new Bacon.EventStream(function(sink) {
var buf = []
var length = 0
lengthObs.onValue(function(n) {
length = n
})
self.onValue(function(x) {
buf.unshift(x)
buf = buf.slice(0, length)
sink(new Bacon.Next(buf))
})
return function() { }
})
}
var pos = makeGame('#example6', true)
var apple = function() {
var applePos = randomPos()
return pos.
filter(function(x) { return x.equals(applePos) }).
take(1).
flatMapLatest(apple).
toProperty(applePos)
}
var appl = apple()
pos.slidingWindowBy(appl.map(1).scan(1, function(x,y) { return x + y })).onValue(drawSnake('#example6 .game'))
appl.onValue(drawApple('#example6 .game'))
})
</script>
<script type="text/javascript" src="marble.js"></script>
</article>
</body>
</html>