-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathSprite.ts
1017 lines (861 loc) · 25.9 KB
/
Sprite.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
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
import Color from "./Color";
import Trigger from "./Trigger";
import Sound, { EffectChain, AudioEffectMap } from "./Sound";
import Costume from "./Costume";
import type { Mouse } from "./Input";
import type Project from "./Project";
import type Watcher from "./Watcher";
import type { Yielding } from "./lib/yielding";
import { effectNames } from "./renderer/effectInfo";
type Effects = {
[x in typeof effectNames[number]]: number;
};
// This is a wrapper to allow the enabled effects in a sprite to be used as a Map key.
// By setting an effect, the bitmask is updated as well.
// This allows the bitmask to be used to uniquely identify a set of enabled effects.
export class _EffectMap implements Effects {
public _bitmask: number;
private _effectValues: Record<typeof effectNames[number], number>;
// TODO: TypeScript can't automatically infer these
public color!: number;
public fisheye!: number;
public whirl!: number;
public pixelate!: number;
public mosaic!: number;
public brightness!: number;
public ghost!: number;
public constructor() {
this._bitmask = 0;
this._effectValues = {
color: 0,
fisheye: 0,
whirl: 0,
pixelate: 0,
mosaic: 0,
brightness: 0,
ghost: 0,
};
for (let i = 0; i < effectNames.length; i++) {
const effectName = effectNames[i];
Object.defineProperty(this, effectName, {
get: () => {
return this._effectValues[effectName];
},
set: (val: number) => {
this._effectValues[effectName] = val;
if (val === 0) {
// If the effect value is 0, meaning it's disabled, set its bit in the bitmask to 0.
this._bitmask = this._bitmask & ~(1 << i);
} else {
// Otherwise, set its bit to 1.
this._bitmask = this._bitmask | (1 << i);
}
},
});
}
}
public _clone(): _EffectMap {
const m = new _EffectMap();
for (const effectName of Object.keys(
this._effectValues
) as (keyof typeof this._effectValues)[]) {
m[effectName] = this[effectName];
}
return m;
}
public clear(): void {
for (const effectName of Object.keys(
this._effectValues
) as (keyof typeof this._effectValues)[]) {
this._effectValues[effectName] = 0;
}
this._bitmask = 0;
}
}
export type SpeechBubbleStyle = "say" | "think";
export type SpeechBubble = {
text: string;
style: SpeechBubbleStyle;
timeout: number | null;
};
type InitialConditions = {
costumeNumber: number;
layerOrder?: number;
};
abstract class SpriteBase {
protected _project!: Project;
protected _costumeNumber: number;
protected _layerOrder: number;
public triggers: Trigger[];
public watchers: Partial<Record<string, Watcher>>;
protected costumes: Costume[];
protected sounds: Sound[];
protected effectChain: EffectChain;
public effects: _EffectMap;
public audioEffects: AudioEffectMap;
protected _vars: object;
public constructor(initialConditions: InitialConditions, vars = {}) {
// TODO: pass project in here, ideally
const { costumeNumber, layerOrder = 0 } = initialConditions;
this._costumeNumber = costumeNumber;
this._layerOrder = layerOrder;
this.triggers = [];
this.watchers = {};
this.costumes = [];
this.sounds = [];
this.effectChain = new EffectChain({
getNonPatchSoundList: this.getSoundsPlayedByMe.bind(this),
});
this.effectChain.connect(Sound.audioContext.destination);
this.effects = new _EffectMap();
this.audioEffects = new AudioEffectMap(this.effectChain);
this._vars = vars;
}
protected getSoundsPlayedByMe(): Sound[] {
return this.sounds.filter((sound) => this.effectChain.isTargetOf(sound));
}
public get stage(): Stage {
return this._project.stage;
}
public get sprites(): Partial<Record<string, Sprite>> {
return this._project.sprites;
}
public get vars(): object {
return this._vars;
}
public get costumeNumber(): number {
return this._costumeNumber;
}
public set costumeNumber(number) {
if (Number.isFinite(number)) {
this._costumeNumber = this.wrapClamp(number, 1, this.costumes.length);
} else {
this._costumeNumber = 0;
}
}
public set costume(costume: number | string | Costume) {
if (costume instanceof Costume) {
const costumeIndex = this.costumes.indexOf(costume);
if (costumeIndex > -1) {
this.costumeNumber = costumeIndex + 1;
}
}
if (typeof costume === "number") {
this.costumeNumber = costume;
return;
}
if (typeof costume === "string") {
const index = this.costumes.findIndex((c) => c.name === costume);
if (index > -1) {
this.costumeNumber = index + 1;
} else {
switch (costume) {
case "next costume":
case "next backdrop": {
this.costumeNumber = this.costumeNumber + 1;
break;
}
case "previous costume":
case "previous backdrop": {
this.costumeNumber = this.costumeNumber - 1;
break;
}
case "random costume":
case "random backdrop": {
// Based on joker314's inclusiveRandIntWithout: https://github.com/LLK/scratch-vm/pull/2011
// Note: We use 1 -> length instead of 0 -> length-1, since we want a 1-indexed result.
const lower = 1;
const upper = this.costumes.length;
const excluded = this.costumeNumber;
const possibleOptions = upper - lower;
let randInt = lower + Math.floor(Math.random() * possibleOptions);
if (randInt >= excluded) {
randInt++;
}
this.costumeNumber = randInt;
break;
}
default: {
if (!Number.isNaN(Number(costume)) && costume.trim().length !== 0) {
this.costumeNumber = Number(costume);
}
}
}
}
}
}
public get costume(): Costume {
return this.costumes[this.costumeNumber - 1];
}
public degToRad(deg: number): number {
return (deg * Math.PI) / 180;
}
public radToDeg(rad: number): number {
return (rad * 180) / Math.PI;
}
public degToScratch(deg: number): number {
return -deg + 90;
}
public scratchToDeg(scratchDir: number): number {
return -scratchDir + 90;
}
public radToScratch(rad: number): number {
return this.degToScratch(this.radToDeg(rad));
}
public scratchToRad(scratchDir: number): number {
return this.degToRad(this.scratchToDeg(scratchDir));
}
// From scratch-vm's math-util.
public scratchTan(angle: number): number {
angle = angle % 360;
switch (angle) {
case -270:
case 90:
return Infinity;
case -90:
case 270:
return -Infinity;
default:
return parseFloat(Math.tan((Math.PI * angle) / 180).toFixed(10));
}
}
// Wrap rotation from -180 to 180.
public normalizeDeg(deg: number): number {
// This is a pretty big math expression, but it's necessary because in JavaScript,
// the % operator means "remainder", not "modulo", and so negative numbers won't "wrap around".
// See https://web.archive.org/web/20090717035140if_/javascript.about.com/od/problemsolving/a/modulobug.htm
return ((((deg + 180) % 360) + 360) % 360) - 180;
}
// Keep a number between two limits, wrapping "extra" into the range.
// wrapClamp(7, 1, 5) == 2
// wrapClamp(0, 1, 5) == 5
// wrapClamp(-11, -10, 6) == 6
// Borrowed from scratch-vm (src/util/math-util.js)
public wrapClamp(n: number, min: number, max: number): number {
const range = max - min + 1;
return n - Math.floor((n - min) / range) * range;
}
// Given a generator function, return a version of it that runs in "warp mode" (no yields).
public warp(procedure: GeneratorFunction): (...args: unknown[]) => void {
const bound = procedure.bind(this);
return (...args) => {
const inst = bound(...args);
while (!inst.next().done);
};
}
// TODO: this should also take strings so rand("0.0", "1.0") returns a random float like Scratch
public random(a: number, b: number): number {
const min = Math.min(a, b);
const max = Math.max(a, b);
if (min % 1 === 0 && max % 1 === 0) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
return Math.random() * (max - min) + min;
}
public *wait(secs: number): Yielding<void> {
const endTime = new Date();
endTime.setMilliseconds(endTime.getMilliseconds() + secs * 1000);
while (new Date() < endTime) {
yield;
}
}
public get mouse(): Mouse {
return this._project.input.mouse;
}
public keyPressed(name: string): boolean {
return this._project.input.keyPressed(name);
}
public get timer(): number {
return this._project.timer;
}
public restartTimer(): void {
this._project.restartTimer();
}
public *startSound(soundName: string): Yielding<void> {
const sound = this.getSound(soundName);
if (sound) {
this.effectChain.applyToSound(sound);
yield* sound.start();
}
}
public *playSoundUntilDone(soundName: string): Yielding<void> {
const sound = this.getSound(soundName);
if (sound) {
sound.connect(this.effectChain.inputNode);
this.effectChain.applyToSound(sound);
yield* sound.playUntilDone();
}
}
public getSound(soundName: string): Sound | undefined {
if (typeof soundName === "number") {
return this.sounds[(soundName - 1) % this.sounds.length];
} else {
return this.sounds.find((s) => s.name === soundName);
}
}
public stopAllSounds(): void {
this._project.stopAllSounds();
}
public stopAllOfMySounds(): void {
for (const sound of this.sounds) {
sound.stop();
}
}
public broadcast(name: string): Promise<void> {
return this._project.fireTrigger(Trigger.BROADCAST, { name });
}
public *broadcastAndWait(name: string): Yielding<void> {
let running = true;
void this.broadcast(name).then(() => {
running = false;
});
while (running) {
yield;
}
}
public clearPen(): void {
this._project.renderer.clearPen();
}
public *askAndWait(question: string): Yielding<void> {
let done = false;
void this._project.askAndWait(question).then(() => {
done = true;
});
while (!done) yield;
}
public get answer(): string | null {
return this._project.answer;
}
public get loudness(): number {
return this._project.loudness;
}
public toNumber(value: unknown): number {
if (typeof value === "number") {
if (isNaN(value)) {
return 0;
}
return value;
}
const n = Number(value);
if (Number.isNaN(n)) {
return 0;
}
return n;
}
public toBoolean(value: unknown): boolean {
if (typeof value === "boolean") {
return value;
}
if (typeof value === "string") {
if (value === "" || value === "0" || value.toLowerCase() === "false") {
return false;
}
return true;
}
return Boolean(value);
}
public toString(value: unknown): string {
return String(value);
}
public stringIncludes(string: string, substring: string): boolean {
return string.toLowerCase().includes(substring.toLowerCase());
}
public arrayIncludes<T>(array: T[], value: T): boolean {
return array.some((item) => this.compare(item, value) === 0);
}
public letterOf(string: string, index: number): string {
if (index < 0 || index >= string.length) {
return "";
}
return string[index];
}
public itemOf<T>(array: T[], index: number): T | "" {
if (index < 0 || index >= array.length) {
return "";
}
return array[index];
}
public indexInArray<T>(array: T[], value: T): number {
return array.findIndex((item) => this.compare(item, value) === 0);
}
public compare(v1: unknown, v2: unknown): number {
if (v1 === v2) {
return 0;
}
let n1 = Number(v1);
let n2 = Number(v2);
if (
(n1 === Infinity && n2 === Infinity) ||
(n1 === -Infinity && n2 === -Infinity)
) {
return 0;
}
if (
n1 === 0 &&
(v1 === null || (typeof v1 === "string" && v1.trim().length === 0))
) {
n1 = NaN;
} else if (
n2 === 0 &&
(v2 === null || (typeof v2 === "string" && v2.trim().length === 0))
) {
n2 = NaN;
}
if (!isNaN(n1) && !isNaN(n2)) {
return n1 - n2;
}
const s1 = String(v1).toLowerCase();
const s2 = String(v2).toLowerCase();
if (s1 === s2) {
return 0;
} else if (s1 < s2) {
return -1;
} else {
return 1;
}
}
}
type RotationStyle =
typeof Sprite["RotationStyle"][keyof typeof Sprite["RotationStyle"]];
type SpriteInitialConditions = {
x: number;
y: number;
direction: number;
rotationStyle?: RotationStyle;
costumeNumber: number;
size: number;
visible: boolean;
penDown?: boolean;
penSize?: number;
penColor?: Color;
};
export class Sprite extends SpriteBase {
private _x: number;
private _y: number;
private _direction: number;
public rotationStyle: RotationStyle;
public size: number;
public visible: boolean;
private parent: this | null;
public clones: this[];
private _penDown: boolean;
public penSize: number;
private _penColor: Color;
public _speechBubble?: SpeechBubble;
public constructor(initialConditions: SpriteInitialConditions, vars = {}) {
super(initialConditions, vars);
const {
x,
y,
direction,
rotationStyle,
costumeNumber,
size,
visible,
penDown,
penSize,
penColor,
} = initialConditions;
this._x = x;
this._y = y;
this._direction = direction;
this.rotationStyle = rotationStyle || Sprite.RotationStyle.ALL_AROUND;
this._costumeNumber = costumeNumber;
this.size = size;
this.visible = visible;
this.parent = null;
this.clones = [];
this._penDown = penDown || false;
this.penSize = penSize || 1;
this._penColor = penColor || Color.rgb(0, 0, 255);
this._speechBubble = {
text: "",
style: "say",
timeout: null,
};
}
public *askAndWait(question: string): Yielding<void> {
if (this._speechBubble) {
this.say("");
}
yield* super.askAndWait(question);
}
public createClone(): void {
const clone = Object.assign(
Object.create(Object.getPrototypeOf(this) as object) as this,
this
);
clone._project = this._project;
clone.triggers = this.triggers.map((trigger) => trigger.clone());
clone.costumes = this.costumes;
clone.sounds = this.sounds;
clone._vars = Object.assign({}, this._vars);
clone._speechBubble = {
text: "",
style: "say",
timeout: null,
};
clone.effects = this.effects._clone();
// Clones inherit audio effects from the original sprite, for some reason.
// Couldn't explain it, but that's the behavior in Scratch 3.0.
// eslint-disable-next-line @typescript-eslint/no-this-alias
let original = this;
while (original.parent) {
original = original.parent;
}
clone.effectChain = original.effectChain.clone({
getNonPatchSoundList: clone.getSoundsPlayedByMe.bind(clone),
});
// Make a new audioEffects interface which acts on the cloned effect chain.
clone.audioEffects = new AudioEffectMap(clone.effectChain);
clone.clones = [];
clone.parent = this;
this.clones.push(clone);
// Trigger CLONE_START:
const triggers = clone.triggers.filter((tr) =>
tr.matches(Trigger.CLONE_START, {}, clone)
);
void this._project._startTriggers(
triggers.map((trigger) => ({ trigger, target: clone }))
);
}
public deleteThisClone(): void {
if (this.parent === null) return;
this.parent.clones = this.parent.clones.filter((clone) => clone !== this);
this._project.runningTriggers = this._project.runningTriggers.filter(
({ target }) => target !== this
);
}
public andClones(): this[] {
return [this, ...this.clones.flatMap((clone) => clone.andClones())];
}
public get direction(): number {
return this._direction;
}
public set direction(dir) {
this._direction = this.normalizeDeg(dir);
}
public goto(x: number, y: number): void {
if (x === this.x && y === this.y) return;
if (this.penDown) {
this._project.renderer.penLine(
{ x: this._x, y: this._y },
{ x, y },
this._penColor,
this.penSize
);
}
this._x = x;
this._y = y;
}
public get x(): number {
return this._x;
}
public set x(x) {
this.goto(x, this._y);
}
public get y(): number {
return this._y;
}
public set y(y) {
this.goto(this._x, y);
}
public move(dist: number): void {
const moveDir = this.scratchToRad(this.direction);
this.goto(
this._x + dist * Math.cos(moveDir),
this._y + dist * Math.sin(moveDir)
);
}
public *glide(seconds: number, x: number, y: number): Yielding<void> {
const interpolate = (a: number, b: number, t: number): number =>
a + (b - a) * t;
const startTime = new Date();
const startX = this._x;
const startY = this._y;
let t;
do {
t = (new Date().getTime() - startTime.getTime()) / (seconds * 1000);
this.goto(interpolate(startX, x, t), interpolate(startY, y, t));
yield;
} while (t < 1);
}
ifOnEdgeBounce() {
const nearestEdge = this.nearestEdge();
if (!nearestEdge) return;
const rad = this.scratchToRad(this.direction);
let dx = Math.cos(rad);
let dy = Math.sin(rad);
switch (nearestEdge) {
case Sprite.Edge.LEFT:
dx = Math.max(0.2, Math.abs(dx));
break;
case Sprite.Edge.RIGHT:
dx = -Math.max(0.2, Math.abs(dx));
break;
case Sprite.Edge.TOP:
dy = -Math.max(0.2, Math.abs(dy));
break;
case Sprite.Edge.BOTTOM:
dy = Math.max(0.2, Math.abs(dy));
break;
}
this.direction = this.radToScratch(Math.atan2(dy, dx));
this.positionInFence();
}
positionInFence() {
// https://github.com/LLK/scratch-vm/blob/develop/src/sprites/rendered-target.js#L949
const fence = this.stage.fence;
const bounds = this._project.renderer.getTightBoundingBox(this);
let dx = 0,
dy = 0;
if (bounds.left < fence.left) {
dx += fence.left - bounds.left;
}
if (bounds.right > fence.right) {
dx += fence.right - bounds.right;
}
if (bounds.top > fence.top) {
dy += fence.top - bounds.top;
}
if (bounds.bottom < fence.bottom) {
dy += fence.bottom - bounds.bottom;
}
this.goto(this.x + dx, this.y + dy);
}
public moveAhead(value: number | Sprite = Infinity): void {
if (typeof value === "number") {
this._project.changeSpriteLayer(this, value);
} else {
this._project.changeSpriteLayer(this, 1, value);
}
}
public moveBehind(value: number | Sprite = Infinity): void {
if (typeof value === "number") {
this._project.changeSpriteLayer(this, -value);
} else {
this._project.changeSpriteLayer(this, -1, value);
}
}
public get penDown(): boolean {
return this._penDown;
}
public set penDown(penDown) {
if (penDown) {
this._project.renderer.penLine(
{ x: this.x, y: this.y },
{ x: this.x, y: this.y },
this._penColor,
this.penSize
);
}
this._penDown = penDown;
}
public get penColor(): Color {
return this._penColor;
}
public set penColor(color: unknown) {
if (color instanceof Color) {
this._penColor = color;
} else {
console.error(
`${String(color)} is not a valid penColor. Try using the Color class!`
);
}
}
public stamp(): void {
this._project.renderer.stamp(this);
}
public touching(
target: "mouse" | "edge" | Sprite | Stage,
fast = false
): boolean {
if (typeof target === "string") {
switch (target) {
case "mouse":
return this._project.renderer.checkPointCollision(
this,
{
x: this.mouse.x,
y: this.mouse.y,
},
fast
);
case "edge": {
const bounds = this._project.renderer.getTightBoundingBox(this);
const stageWidth = this.stage.width;
const stageHeight = this.stage.height;
return (
bounds.left < -stageWidth / 2 ||
bounds.right > stageWidth / 2 ||
bounds.top > stageHeight / 2 ||
bounds.bottom < -stageHeight / 2
);
}
default:
console.error(
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Cannot find target "${target}" in "touching". Did you mean to pass a sprite class instead?`
);
return false;
}
} else if (target instanceof Color) {
return this._project.renderer.checkColorCollision(this, target);
}
return this._project.renderer.checkSpriteCollision(this, target, fast);
}
public colorTouching(color: Color, target: Sprite | Stage): boolean {
if (typeof target === "string") {
console.error(
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Cannot find target "${target}" in "touchingColor". Did you mean to pass a sprite class instead?`
);
return false;
}
if (typeof color === "string") {
console.error(
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Cannot find color "${color}" in "touchingColor". Did you mean to pass a Color instance instead?`
);
return false;
}
if (target instanceof Color) {
// "Color is touching color"
return this._project.renderer.checkColorCollision(this, target, color);
} else {
// "Color is touching sprite" (not implemented in Scratch!)
return this._project.renderer.checkSpriteCollision(
this,
target,
false,
color
);
}
}
nearestEdge() {
const bounds = this._project.renderer.getTightBoundingBox(this);
const { width: stageWidth, height: stageHeight } = this.stage;
const distLeft = Math.max(0, stageWidth / 2 + bounds.left);
const distTop = Math.max(0, stageHeight / 2 - bounds.top);
const distRight = Math.max(0, stageWidth / 2 - bounds.right);
const distBottom = Math.max(0, stageHeight / 2 + bounds.bottom);
// Find the nearest edge.
let nearestEdge = null;
let minDist = Infinity;
if (distLeft < minDist) {
minDist = distLeft;
nearestEdge = Sprite.Edge.LEFT;
}
if (distTop < minDist) {
minDist = distTop;
nearestEdge = Sprite.Edge.TOP;
}
if (distRight < minDist) {
minDist = distRight;
nearestEdge = Sprite.Edge.RIGHT;
}
if (distBottom < minDist) {
minDist = distBottom;
nearestEdge = Sprite.Edge.BOTTOM;
}
if (minDist > 0) {
nearestEdge = null;
}
return nearestEdge;
}
public say(text: string): void {
if (this._speechBubble?.timeout) clearTimeout(this._speechBubble.timeout);
this._speechBubble = { text: String(text), style: "say", timeout: null };
}
public think(text: string): void {
if (this._speechBubble?.timeout) clearTimeout(this._speechBubble.timeout);
this._speechBubble = { text: String(text), style: "think", timeout: null };
}
public *sayAndWait(text: string, seconds: number): Yielding<void> {
if (this._speechBubble?.timeout) clearTimeout(this._speechBubble.timeout);
const speechBubble: SpeechBubble = { text, style: "say", timeout: null };
let done = false;
const timeout = window.setTimeout(() => {
speechBubble.text = "";
speechBubble.timeout = null;
done = true;
}, seconds * 1000);
speechBubble.timeout = timeout;
this._speechBubble = speechBubble;
while (!done) yield;
}
public *thinkAndWait(text: string, seconds: number): Yielding<void> {
if (this._speechBubble?.timeout) clearTimeout(this._speechBubble.timeout);
const speechBubble: SpeechBubble = { text, style: "think", timeout: null };
let done = false;
const timeout = window.setTimeout(() => {
speechBubble.text = "";
speechBubble.timeout = null;
done = true;
}, seconds * 1000);
speechBubble.timeout = timeout;
this._speechBubble = speechBubble;
while (!done) yield;
}
public static RotationStyle = Object.freeze({
ALL_AROUND: Symbol("ALL_AROUND"),
LEFT_RIGHT: Symbol("LEFT_RIGHT"),
DONT_ROTATE: Symbol("DONT_ROTATE"),
});
public static Edge = Object.freeze({
BOTTOM: Symbol("BOTTOM"),
LEFT: Symbol("LEFT"),
RIGHT: Symbol("RIGHT"),
TOP: Symbol("TOP")
});
}
type StageInitialConditions = {
width?: number;
height?: number;
} & InitialConditions;
export class Stage extends SpriteBase {
public readonly width!: number;
public readonly height!: number;
public __counter: number;
public fence: {
left: number;
right: number;
top: number;
bottom: number;
}
public constructor(initialConditions: StageInitialConditions, vars = {}) {
super(initialConditions, vars);
// Use defineProperties to make these non-writable.
// Changing the width and height of the stage after initialization isn't supported.
Object.defineProperties(this, {
width: {
value: initialConditions.width || 480,
enumerable: true,
},
height: {
value: initialConditions.height || 360,
enumerable: true,
},
});
this.fence = {
left: -this.width / 2,
right: this.width / 2,
top: this.height / 2,
bottom: -this.height / 2
};
// For obsolete counter blocks.
this.__counter = 0;