This repository has been archived by the owner on Nov 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tileworld.ts
937 lines (878 loc) · 33.7 KB
/
tileworld.ts
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
// which direction is the sprite moving
enum TileDir {
//% block="--"
None,
//% block="Left"
Left,
//% block="Right"
Right,
//% block="Up"
Up,
//% block="Down"
Down
}
//% blockId=tiledir block="$dir"
function _tileDir(dir: TileDir): number {
return dir;
}
enum ResultSet {
//% block="has no"
Zero,
//% block="has a"
One,
//% block="has only"
Only
}
enum Membership {
//% block="one of"
OneOf,
//% block="not one of"
NotOneOf
}
enum Spritely {
//% block="fixed"
Fixed,
//% block="movable"
Movable
}
//% weight=1000 color="#442255" icon="\uf45c"
//% groups='["Tiles", "Events", "Assertions", "Actions"]'
//% blockGap=8
namespace TileWorld {
enum CallBackKind {
Stationary = TileDir.Down + 1,
Transition
}
const tileBits = 4;
// a sprite that moves by tiles, but only in one of four directions
class TileSprite extends Sprite implements Tile {
// which tile map code does this sprite represent?
private code: number;
// which direction is the target
private dir: TileDir;
// previous sprite coord value
private old: number;
// the next tile target
private next: number;
// have we received a stop request?
private stop: boolean;
// notification
private tileSpriteEvent: (ts: TileSprite, n: CallBackKind) => void;
//
constructor(world: TileWorld, code: number, image: Image, kind: number) {
super(image);
const scene = game.currentScene();
scene.physicsEngine.addSprite(this);
this.setKind(kind);
this.code = code;
this.dir = TileDir.None;
this.tileSpriteEvent = undefined;
this.stop = false;
}
//
moveOne(dir: number) {
if (this.dir == TileDir.None) {
this.stop = false;
if (dir == TileDir.Left || dir == TileDir.Right)
this.moveInX(dir);
else if (dir == TileDir.Up || dir == TileDir.Down)
this.moveInY(dir);
}
}
// stop at current tile
deadStop() {
if (this.dir == TileDir.Left || this.dir == TileDir.Right) {
this.reachedTargetX(this.centerIt(this.x), 0, false)
} else {
this.reachedTargetY(this.centerIt(this.y), 0, false)
}
}
// back to previous tile
knockBack() {
if ((this.dir == TileDir.Left || this.dir == TileDir.Right) &&
this.old != this.getColumn()) {
this.x = this.centerIt(this.old << tileBits)
} else if ((this.dir == TileDir.Up || this.dir == TileDir.Down) &&
this.old != this.getRow()) {
this.y = this.centerIt(this.old << tileBits)
}
this.deadStop()
}
//
getCode() { return this.code }
getDirection() { return this.dir }
getColumn() { return this.x >> tileBits }
getRow() { return this.y >> tileBits }
// notify client on entering tile
onTileSpriteEvent(handler: (ts: TileSprite, d: number) => void) {
this.tileSpriteEvent = handler
}
// call from game update loop
updateInMotion() {
if (this.dir == TileDir.None)
return false;
// have we crossed into a new tile?
if (this.tileSpriteEvent) {
if (this.dir == TileDir.Left || this.dir == TileDir.Right) {
if (this.old != this.getColumn()) {
this.tileSpriteEvent(this, CallBackKind.Transition)
}
this.old = this.getColumn()
} else if (this.dir == TileDir.Up || this.dir == TileDir.Down) {
if (this.old != this.getRow()) {
this.tileSpriteEvent(this, CallBackKind.Transition)
}
this.old = this.getRow()
}
}
// have we reached the target?
let size = 1 << tileBits
if (this.dir == TileDir.Left && this.x <= this.next) {
return this.reachedTargetX(this.next, -size);
} else if (this.dir == TileDir.Right && this.x >= this.next) {
return this.reachedTargetX(this.next, size);
} else if (this.dir == TileDir.Up && this.y <= this.next) {
return this.reachedTargetY(this.next, -size);
} else if (this.dir == TileDir.Down && this.y >= this.next) {
return this.reachedTargetY(this.next, size);
}
return false;
}
//
updateStationary() {
if (this.tileSpriteEvent && this.dir == TileDir.None) {
this.tileSpriteEvent(this, CallBackKind.Stationary);
}
}
//
private moveInX(dir: TileDir) {
let size = 1 << tileBits;
let sign = dir == TileDir.Left ? -1 : 1;
this.next = this.x + sign * size;
this.old = this.getColumn();
this.dir = dir;
this.vx = sign * 100;
}
private moveInY(dir: TileDir) {
let size = 1 << tileBits;
let sign = dir == TileDir.Up ? -1 : 1
this.next = this.y + sign * size;
this.old = this.getRow();
this.dir = dir;
this.vy = sign * 100;
}
private reachedTargetX(x: number, step: number, reentrant: boolean = true) {
this.x = x;
this.vx = 0;
let lastDir = this.dir
this.dir = TileDir.None
if (this.tileSpriteEvent && reentrant) {
this.tileSpriteEvent(this, <number>lastDir);
}
this.old = this.getColumn();
return true;
}
private reachedTargetY(y: number, step: number, reentrant: boolean = true) {
this.y = y
this.vy = 0
let lastDir = this.dir
this.dir = TileDir.None
if (this.tileSpriteEvent && reentrant) {
this.tileSpriteEvent(this, <number>lastDir)
}
this.old = this.getRow()
return true
}
private centerIt(n: number) {
return ((n >> tileBits) << tileBits) + (1 << (tileBits - 1))
}
}
// tileworld actions
enum TheActions { Move, Remove, Create, Stop, KnockBack, SetTile }
class ClosedAction {
constructor(public self: boolean, public action: TheActions, public args: any[]) { }
}
// the tile world manages tile sprites
class TileWorld {
// what tile code to put behind a sprite?
private backgroundTile: number;
private tileKind: number;
// the current tile map (no sprites)
private tileMap: Image;
// fill in with sprites
private spriteMap: Image;
// note tiles with more than one sprite
private multiples: Image;
// which codes map to sprites?
private spriteCodes: number[];
// map codes to kinds
private codeToKind: number[];
// the sprites, divided up by codes
private sprites: TileSprite[][];
// event handlers
private onPushHandlers: { [index:number]: ((ts: TileSprite, d: TileDir) => void)[] };
private moveIntoHandlers: { [index:number]: ((ts: TileSprite) => void)[] };
private atRestHandlers: { [index:number]: ((ts: TileSprite) => void)[] };
//
constructor() {
this.backgroundTile = -1
this.sprites = []
this.codeToKind = []
this.spriteCodes = []
this.onPushHandlers = {}
this.moveIntoHandlers = {}
this.atRestHandlers = {}
this.tileKind = SpriteKind.create()
}
// methods for defining map and sprites
setMap(tileMap: Image) {
this.tileMap = tileMap.clone();
this.spriteMap = tileMap.clone();
this.multiples = tileMap.clone();
scene.setTileMap(this.tileMap)
game.onUpdate(() => { this.update(); })
}
//
setBackgroundTile(backgroundTile: number) {
this.backgroundTile = backgroundTile
}
//
setCode(curs: Tile, code: number) {
this.tileMap.setPixel(curs.getColumn(), curs.getRow(), code)
}
getCode(curs: Tile) {
return this.tileMap.getPixel(curs.getColumn(), curs.getRow())
}
getKindFromCode(code: number) {
return this.codeToKind[code]
}
addTiles(code: number, art: Image, kind: number) {
let tiles = scene.getTilesByType(code)
this.codeToKind[code] = kind;
scene.setTile(code, art);
}
//
addTileSprites(code: number, art:Image, kind: number) {
let tiles = scene.getTilesByType(code)
scene.setTile(code, art);
this.spriteCodes.push(code);
this.codeToKind[code] = kind;
this.initHandlers(kind)
this.sprites[code] = []
for (let value of tiles) {
let tileSprite = new TileSprite(this, code, art, kind)
this.hookupHandlers(tileSprite)
this.sprites[code].push(tileSprite)
value.place(tileSprite)
}
// remove from tile map
if (this.backgroundTile != -1) {
for (let y = 0; y < this.tileMap.height; y++) {
for (let x = 0; x < this.tileMap.width; x++) {
let pixel = this.tileMap.getPixel(x, y)
if (code == pixel)
this.tileMap.setPixel(x, y, this.backgroundTile)
}
}
}
}
getSpritesCount(code: number) {
if (this.sprites[code])
return this.sprites[code].length
return 0
}
createTileSpriteAt(code: number, cursor: Tile) {
//let tileSprite = new TileSprite(this, code, art, kind)
//this.hookupHandlers(tileSprite)
//this.sprites[code].push(tileSprite)
}
// register event handlers
ifAtRest(kind: number, h: (ts: TileSprite) => void) {
if (!this.atRestHandlers[kind]) this.atRestHandlers[kind] = []
this.atRestHandlers[kind].push(h);
}
onPushRequest(kind: number, h: (ts: TileSprite, d: TileDir) => void) {
if (!this.onPushHandlers[kind]) this.onPushHandlers[kind] = [];
this.onPushHandlers[kind].push(h);
}
onMoveInto(kind: number, h: (ts: TileSprite) => void) {
if (!this.moveIntoHandlers[kind]) this.moveIntoHandlers[kind] = [];
this.moveIntoHandlers[kind].push(h);
}
public isFixedCode(codeKind: number) {
return codeKind < this.tileKind && this.spriteCodes.indexOf(codeKind) == -1
}
// how many fixed/movable sprites of codeKind are at a location?
// returns -1 if result needs to consult actual sprite list at location
countCodeKindAt(codeKind: number, cursor: Cursor) {
let col = cursor.getColumn(), row = cursor.getRow()
let tileMapCode = this.tileMap.getPixel(col, row)
let spriteMapCode = this.spriteMap.getPixel(col, row)
if (this.isFixedCode(codeKind))
return (codeKind == tileMapCode) ? 1 : 0
else if (this.multiples.getPixel(col, row))
return -1
else if (codeKind < this.tileKind)
return (codeKind == spriteMapCode) ? 1 : 0
else {
let tileMapKind = this.codeToKind[tileMapCode]
let spriteMapKind = this.codeToKind[spriteMapCode]
return (codeKind == tileMapKind ? 1 : 0) + (tileMapCode == spriteMapCode ? 0 : (codeKind == spriteMapKind ? 1 : 0))
}
}
hasMovableSprite(cursor: Cursor) {
let tileMapCode = this.tileMap.getPixel(cursor.getColumn(), cursor.getRow())
let spriteMapCode = this.spriteMap.getPixel(cursor.getColumn(), cursor.getRow())
return spriteMapCode != tileMapCode
}
// is the underlying tile at a location of codeKind?
tileIs(codeKind: number, cursor: Cursor) {
let targetCodeKind = this.tileMap.getPixel(cursor.getColumn(), cursor.getRow())
if (codeKind < this.tileKind)
return targetCodeKind == codeKind
else
return this.codeToKind[targetCodeKind] == codeKind
}
// get all the sprites of codeKind at an (optional) location
getSprites(codeKind: number, cursor: Cursor = null) {
if (cursor) {
return this._getSpritesCursor(codeKind, cursor);
} else
return this._getSprites(codeKind)
}
//
removeSprite(s: TileSprite) {
// TODO: we may want to consider a two phase process where we
// TODO: disable the TileSprite and leave Sprite intact
this.sprites[s.getCode()].removeElement(s)
s.destroy()
}
private _getSpritesCursor(codeKind: number, cursor: Cursor) {
let ss = this._getSprites(codeKind)
if (ss)
return ss.filter((t: TileSprite) =>
t.getColumn() == cursor.getColumn() && t.getRow() == cursor.getRow())
else
return null
}
private _getSprites(codeKind: number): any[] {
if (codeKind < this.tileKind && this.spriteCodes.indexOf(codeKind) != -1) {
return this.sprites[codeKind]
} else if (codeKind > this.tileKind) {
if (game.currentScene().spritesByKind[codeKind])
return game.currentScene().spritesByKind[codeKind].sprites()
}
return null;
}
//
private motionEventFired = false;
private actions: ClosedAction[] = [];
private update() {
this.motionEventFired = false;
// first recompute the map
this.spriteMap.copyFrom(this.tileMap)
this.multiples.fill(0)
this.sprites.forEach((arr, code) => {
if (arr) {
arr.forEach((sprite) => {
let col = sprite.getColumn(), row = sprite.getRow()
let here = this.spriteMap.getPixel(col, row)
if (this.spriteCodes.indexOf(here) != -1 && !this.multiples.getPixel(col, row)) {
// we have more than 1 sprite at (col,row)
this.multiples.setPixel(col, row, 1)
} else {
// no sprite at this tile yet
this.spriteMap.setPixel(col, row, code)
}
})
}
})
let transitionToStopped: TileSprite[] = []
// 1. update the moving sprites, keeping track of
// which moving sprites transition to stationary
this.sprites.forEach((arr) => {
if (arr) arr.forEach((sprite) => {
if (sprite.updateInMotion())
transitionToStopped.push(sprite)
})
})
// 2. update the stationary sprites (that were not previously moving)
if (this.motionEventFired) {
this.sprites.forEach((arr) => {
if (arr) { arr.forEach((sprite) => {
//if (transitionToStopped.indexOf(sprite) == -1)
sprite.updateStationary()
}) }
})
}
// do all the actions
this.actions.forEach((a) => this.processAction(a))
this.actions = []
}
public addAction(self: boolean, action: TheActions, args: any[]) {
let a = new ClosedAction(self, action, args)
// resolve conflicts on motion
if (a.action == TheActions.Move) {
if (a.self) {
// remove non-self moves on same sprite
let filter = this.actions.filter(b => !(b.action == TheActions.Move && b.args[0] == a.args[0] && !b.self))
this.actions = filter
} else {
// don't add if a self move on same sprite
if (this.actions.find(b => (b.action == TheActions.Move && b.args[0] == a.args[0] && b.self)))
return;
}
}
this.actions.push(a)
}
private processAction(a: ClosedAction) {
switch (a.action) {
case TheActions.Move: {
(<TileSprite>a.args[0]).moveOne(a.args[1])
break;
}
case TheActions.Stop: {
(<TileSprite>a.args[0]).deadStop()
break;
}
case TheActions.KnockBack: {
(<TileSprite>a.args[0]).knockBack()
break;
}
case TheActions.Remove: {
this.removeSprite(a.args[0])
break;
}
case TheActions.Create: {
this.createTileSpriteAt(a.args[0], a.args[1])
break;
}
case TheActions.SetTile: {
this.setCode(a.args[0], a.args[1])
break;
}
}
}
// handlers
private initHandlers(kind: number) {
if (!this.atRestHandlers[kind]) this.atRestHandlers[kind] = []
if (!this.onPushHandlers[kind]) this.onPushHandlers[kind] = []
if (!this.moveIntoHandlers[kind]) this.moveIntoHandlers[kind] = []
}
private invokeHandlers(s: TileSprite, dir: number, intercept: boolean) {
if (dir == CallBackKind.Stationary) {
this.atRestHandlers[s.kind()].forEach((h) => { h(s) });
} else if (dir == CallBackKind.Transition) {
this.motionEventFired = true
this.moveIntoHandlers[s.kind()].forEach((h) => { h(s) });
} else {
this.motionEventFired = true
// process requests out of band
if (intercept) {
let r = this.interceptRequests.find(r => r.sprite == s && r.dir == dir)
if (r) {
dir = r.next;
// restore default behavior
r.next = r.dir
}
}
this.onPushHandlers[s.kind()].forEach((h) => { h(s, dir) });
}
}
private hookupHandlers(s: TileSprite) {
s.onTileSpriteEvent((s, d) => this.invokeHandlers(s,d,true))
}
// support for key stroke handling
private interceptRequests: { sprite: TileSprite, dir: TileDir, next: TileDir}[] = [];
private getRequest(sprite: TileSprite, dir: TileDir) {
let r = this.interceptRequests.find(r => r.sprite == sprite && r.dir == dir)
if (!r) {
r = { sprite: sprite, dir: dir, next: dir };
this.interceptRequests.push(r)
}
return r
}
requestPush(sprite: TileSprite, dir: TileDir) {
// is the sprite moving?
if (sprite.getDirection() == TileDir.None) {
// no - generate push request
this.invokeHandlers(sprite, dir, false);
let r = this.getRequest(sprite, dir);
// set default next direction
r.next = dir;
} else {
// yes - update the next direction for sprite
let r = this.getRequest(sprite, sprite.getDirection());
r.next = dir;
}
}
requestStop(sprite: TileSprite, dir: TileDir) {
let r = this.getRequest(sprite, dir)
// if no change to direction, then stop
if (r.next == dir) {
r.next = TileDir.None;
}
}
}
class BindController {
private sprite: TileSprite;
private world: TileWorld;
constructor() { }
private requestMove(dir: TileDir) {
this.world.requestPush(this.sprite, dir)
}
private requestStop(dir: TileDir) {
this.world.requestStop(this.sprite, dir)
}
// basic movement for tile sprite
bindToController(w: TileWorld, s: TileSprite) {
this.world = w;
this.sprite = s;
scene.cameraFollowSprite(s)
controller.left.onEvent(ControllerButtonEvent.Pressed, () => {
this.requestMove(TileDir.Left)
})
controller.left.onEvent(ControllerButtonEvent.Released, () => {
this.requestStop(TileDir.Left)
})
controller.right.onEvent(ControllerButtonEvent.Pressed, () => {
this.requestMove(TileDir.Right)
})
controller.right.onEvent(ControllerButtonEvent.Released, () => {
this.requestStop(TileDir.Right)
})
controller.up.onEvent(ControllerButtonEvent.Pressed, () => {
this.requestMove(TileDir.Up)
})
controller.up.onEvent(ControllerButtonEvent.Released, () => {
this.requestStop(TileDir.Up)
})
controller.down.onEvent(ControllerButtonEvent.Pressed, () => {
this.requestMove(TileDir.Down)
})
controller.down.onEvent(ControllerButtonEvent.Released, () => {
this.requestStop(TileDir.Down)
})
}
}
// helpers
export interface Tile {
getColumn(): number;
getRow(): number;
}
// a cursor is just a coordinate
class Cursor implements Tile {
private col: number;
private row: number;
constructor(s: Tile, dir: TileDir, dir2: TileDir = TileDir.None) {
this.col = s.getColumn();
this.row = s.getRow();
this.move(dir);
this.move(dir2)
}
private move(dir: TileDir) {
switch (dir) {
case TileDir.Left: this.col--; break;
case TileDir.Right: this.col++; break;
case TileDir.Up: this.row--; break;
case TileDir.Down: this.row++; break;
}
}
public getColumn() { return this.col }
public getRow() { return this.row }
}
// for assertion checking
class CheckFailed { }
let checkFailed = new CheckFailed();
function check(expr: boolean) {
if (!expr) {
throw checkFailed;
}
}
// state here supports blocks
let myWorld = new TileWorld();
let myPlayerController = new BindController()
// keep track of sprites passed down through active handler
// so user code doesn't need to refer to it.
let active: TileSprite[] = [];
// for current handler, track the sprites targeted by asserytions
let targets: { [index:number]: TileSprite } = {};
function getTargetSprite(dir: TileDir) {
return targets[dir]
}
function enterHandler(t: TileSprite) {
active.push(t);
targets = {};
}
function exitHandler(t: TileSprite) {
active.pop();
targets = {}
}
/**
* Set the map for placing tiles in the scene
* @param map
*/
//% blockId=TWsettilemap block="set tile map to %map=tilemap_image_picker"
//% group="Tiles"
export function setTileMap(map: Image) {
myWorld.setMap(map)
}
/**
* Set the background tile
* @param color
*/
//% group="Tiles"
//% blockId=TWsetbackgroundtile block="set background tile to %color=colorindexpicker"
export function setBackgroundTile(code: number) {
myWorld.setBackgroundTile(code)
}
/**
* Map a color to a 16x16 tile image and sprite kind.
* @param code
* @param image
* @param moving
* @param kind
*/
//% blockId=TWaddsprite block="map $code=colorindexpicker to $moving sprite $image=tile_image_picker as $kind=spritekind"
//% group="Tiles"
//% inlineInputMode=inline
export function addSprite(code: number, image: Image, moving: Spritely, kind: number) {
if (moving == Spritely.Fixed)
myWorld.addTiles(code, image, kind)
else
myWorld.addTileSprites(code, image, kind)
}
/**
* Move sprite with buttons
* @param color
*/
//% group="Tiles"
//% blockId=TWmoveButtons block="push $kind=spritekind on dpad"
export function moveWithButtons(kind: number) {
let sprites = game.currentScene().spritesByKind[kind].sprites()
if (sprites && sprites.length > 0) {
let first = sprites[0]
if (first instanceof TileSprite) {
myPlayerController.bindToController(myWorld, first)
}
}
}
//% blockId=TWgettilecode block="get code at $dir=tiledir"
//% group="Tiles"
export function getCode(dir: number) {
let sprite = getCurrentSprite()
if (sprite) {
let cursor = new Cursor(sprite, dir);
return myWorld.getCode(cursor)
}
return 0;
}
// notifications
/**
* Act on a sprite that is resting on a tile
* @param body code to execute
*/
//% group="Events" color="#444488"
//% blockId=TWontilestationary block="at rest $kind=spritekind"
//% blockAllowMultiple=1 draggableParameters="reporter"
export function onChangeAround(kind: number, h: () => void) {
myWorld.ifAtRest(kind, (t) => {
try {
enterHandler(t)
h()
} catch (e) {
} finally {
exitHandler(t)
}
});
}
/**
* Sprite is at center of tile and received request to move
* @param body code to execute
*/
//% group="Events" color="#444488"
//% blockId=TWontilearrived block="on push $kind=spritekind $dir"
//% blockAllowMultiple=1 draggableParameters="reporter"
export function onMoveRequest(kind: number, h: (dir: TileDir) => void) {
myWorld.onPushRequest(kind, (t, d) => {
try {
enterHandler(t)
h(d)
} catch (e) {
} finally {
exitHandler(t)
}
})
}
/**
* Sprite is moving into a tile
* @param body code to execute
*/
//% group="Events" color="#444488"
//% blockId=TWontiletransition block="if $kind=spritekind moves into tile"
//% blockAllowMultiple=1 draggableParameters="reporter"
export function onMovedInto(kind: number, h: () => void) {
myWorld.onMoveInto(kind, (t) => {
try {
enterHandler(t)
h()
} catch (e) {
} finally {
exitHandler(t)
}
})
}
/**
* Get the currently active sprite
*/
//% group="Tiles"
//% blockId=TWgetsprite block="get current sprite"
export function getCurrentSprite(): TileSprite {
if (active.length > 0)
return active[active.length-1]
else
return null
}
//% group="Tiles"
//% blockId=TWgetspritecount block="get sprite count $code=colorindexpicker"
export function getSpriteCount(code: number): number {
return myWorld.getSpritesCount(code)
}
// Assertions
//% blockId=TWhascode block="tile $dir=tiledir $dir2=tiledir $size $code=colorindexpicker"
//% group="Assertions" color="#448844" inlineInputMode=inline
export function hasCode(code: number, dir: number = TileDir.None, dir2: number = TileDir.None, size: ResultSet = ResultSet.Zero) {
let sprite = getCurrentSprite()
if (sprite) {
let delta = (dir == TileDir.None && dir2 == TileDir.None) ? (code == sprite.getCode() ? -1 : 0) : 0
supportHas(code, true, dir, dir2, size, sprite, delta)
}
}
//% blockId=TWhaskind block="tile $dir=tiledir $dir2=tiledir $size $kind=spritekind"
//% group="Assertions" color="#448844" inlineInputMode=inline
export function hasKind(kind: number, dir: number = TileDir.None, dir2: number = TileDir.None, size: ResultSet = ResultSet.Zero) {
let sprite = getCurrentSprite()
if (sprite) {
let delta = (dir == TileDir.None && dir2 == TileDir.None) ? (kind == sprite.kind() ? -1 : 0) : 0
supportHas(kind, false, dir, dir2, size, sprite, delta)
}
}
// record the sprite, but not two steps away
function recordSprite(sprites: TileSprite[], dir: TileDir, dir2: TileDir) {
if (sprites && sprites.length > 0) {
if (dir == TileDir.None || dir2 == TileDir.None) {
let theDir = (dir == TileDir.None) ? dir2 : dir
targets[theDir] = sprites[0]
}
}
}
function supportHas(codeKind: number, code: boolean, dir: TileDir, dir2: TileDir,
size: ResultSet, sprite: TileSprite, delta: number) {
let cursor = new Cursor(sprite, dir, dir2)
let approxCount = myWorld.countCodeKindAt(codeKind, cursor)
if (size == ResultSet.Zero || size == ResultSet.One) {
if (approxCount + delta >= 0) {
check(size == ResultSet.Zero ? approxCount + delta == 0 : approxCount + delta > 0)
recordSprite(myWorld.getSprites(codeKind, cursor), dir, dir2)
return;
}
} else if (size == ResultSet.Only) {
// this only applies to fixed sprites, so count is accurate
check(!myWorld.hasMovableSprite(cursor) && approxCount == 1)
return;
}
// assert(!myWorld.isFixedCode(codeKind))
let sprites = myWorld.getSprites(codeKind, cursor)
let kindOfFixed = myWorld.getKindFromCode(myWorld.getCode(cursor))
let count = (sprites ? sprites.length : 0) + (code ? 0 : (kindOfFixed == codeKind ? 1 : 0))
if (size == ResultSet.Zero) {
check(count + delta == 0)
} else if (size == ResultSet.One) {
check(count + delta > 0)
recordSprite(sprites, dir, dir2)
}
}
/**
* Check if a direction is one of several values.
*/
//% group="Assertions" color="#448844"
//% blockId=TWisoneof block="assert %dir=variables_get(dir) $cmp %c1 %c2"
//% inlineInputMode=inline
export function _isOneOf(dir: number, cmp: Membership = Membership.OneOf, c1: TileDir, c2: TileDir) {
if (cmp == Membership.OneOf)
check(dir == c1 || dir == c2)
else
check(dir != c1 && dir != c2)
}
// Actions
// request sprite to move in specified direction
//% blockId=TWmoveself block="move $dir=tiledir self"
//% group="Actions" color="#88CC44"
export function moveSelf(dir: number) {
let sprite = getCurrentSprite()
if (sprite) {
myWorld.addAction(true, TheActions.Move, [sprite,dir])
}
}
// request sprite to move in specified direction
//% blockId=TWmoveother block="move $dir=tiledir other at $otherdir=tiledir"
//% group="Actions" color="#88CC44"
export function moveOther(otherdir: number, dir: number) {
let sprite = getTargetSprite(otherdir)
if (sprite) {
myWorld.addAction(false, TheActions.Move, [sprite, dir])
}
}
//% blockId=TWknockbackother block="knock back other $otherdir=tiledir"
//% group="Actions" color="#88CC44"
export function knockBackOther(otherdir: number) {
let sprite = getTargetSprite(otherdir)
if (sprite && sprite.getDirection() != TileDir.None) {
myWorld.addAction(false, TheActions.KnockBack, [sprite])
}
}
//% blockId=TWstopother block="stop other $otherdir=tiledir"
//% group="Actions" color="#88CC44"
export function stopOther(otherdir: number) {
let sprite = getTargetSprite(otherdir)
if (sprite && sprite.getDirection() != TileDir.None) {
myWorld.addAction(false, TheActions.Stop, [sprite])
}
}
//% blockId=TWremoveSelf block="remove self"
//% group="Actions" color="#88CC44"
export function removeSelf() {
let sprite = getCurrentSprite()
if (sprite) {
myWorld.addAction(true, TheActions.Remove, [sprite])
}
}
//% blockId=TWremoveother block="remove other at $otherdir=tiledir"
//% group="Actions" color="#88CC44"
export function removeOther(otherdir: number) {
let sprite = getTargetSprite(otherdir)
if (sprite) {
myWorld.addAction(false, TheActions.Remove, [sprite])
}
}
// direction-based
// - set tile code
// - create sprite
//% blockId=TWsettilecode block="set code $code=colorindexpicker at $dir=tiledir"
//% group="Actions" color="#88CC44"
export function setCode(code: number, dir: number) {
let sprite = getCurrentSprite()
if (sprite) {
let cursor = new Cursor(sprite, dir);
myWorld.addAction(false, TheActions.SetTile, [cursor, code])
}
}
//% blockId=TWcreatesprite block="create sprite $code=colorindexpicker at $dir=tiledir"
//% group="Actions" color="#88CC44"
export function createSprite(code: number, dir: number) {
let sprite = getCurrentSprite()
if (sprite) {
myWorld.addAction(false, TheActions.Create, [code, new Cursor(sprite, dir)])
}
}
}