-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinterpreter.ts
More file actions
836 lines (767 loc) · 30.1 KB
/
interpreter.ts
File metadata and controls
836 lines (767 loc) · 30.1 KB
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
namespace microcode {
// an interpreter for ProgramDefn
class Error {
constructor(public msg: string) {}
}
// delay on sending stuff in pipes and changing pages
const ANTI_FREEZE_DELAY = 50
type ValueType = number | string | boolean | any[] | object
type VariableMap = { [key: string]: ValueType }
type SensorMap = { [key: number]: number }
enum OutputResource {
LEDScreen = 1000,
Speaker,
RadioGroup, // well radio group affects subsequent radio.send
PageCounter,
}
function getOutputResource(action: Tid) {
switch (action) {
case Tid.TID_ACTUATOR_PAINT:
case Tid.TID_ACTUATOR_SHOW_NUMBER:
return OutputResource.LEDScreen
case Tid.TID_ACTUATOR_CUP_X_ASSIGN:
case Tid.TID_ACTUATOR_CUP_Y_ASSIGN:
case Tid.TID_ACTUATOR_CUP_Z_ASSIGN:
return action
case Tid.TID_ACTUATOR_RADIO_SET_GROUP:
return OutputResource.RadioGroup
case Tid.TID_ACTUATOR_MUSIC:
case Tid.TID_ACTUATOR_SPEAKER:
return OutputResource.Speaker
case Tid.TID_ACTUATOR_SWITCH_PAGE:
return OutputResource.PageCounter
}
return undefined
}
enum ActionKind {
Instant = 1,
TakesTime,
}
function getActionKind(action: Tid) {
switch (action) {
case Tid.TID_ACTUATOR_PAINT:
case Tid.TID_ACTUATOR_MUSIC:
case Tid.TID_ACTUATOR_SHOW_NUMBER:
case Tid.TID_ACTUATOR_SPEAKER:
case Tid.TID_ACTUATOR_RGB_LED:
case Tid.TID_ACTUATOR_CAR:
return ActionKind.TakesTime
}
return ActionKind.Instant
}
class RuleClosure {
private backgroundActive = false
private wakeTime: number = 0
private actionRunning: boolean = false
private modifierIndex: number = 0
private loopIndex: number = 0
private timerGoAhead: boolean = false
constructor(
public index: number,
public rule: RuleDefn,
private interp: Interpreter
) {}
public active() {
return this.actionRunning
}
public start(timer = false) {
if (!this.interp.running || this.active() || this.backgroundActive)
return
this.reset()
const time = this.getWakeTime()
if (!timer || time > 0) this.timerOrSequenceRule()
}
private reset() {
this.wakeTime = 0
this.actionRunning = false
this.modifierIndex = 0
this.loopIndex = 0
}
kill() {
const resource = this.getOutputResource()
if (resource == OutputResource.LEDScreen) {
led.stopAnimation()
} else if (resource == OutputResource.Speaker) music.stopAllSounds()
this.actionRunning = false
// give the background fiber chance to finish unless it is waiting
while (this.wakeTime == 0 && this.backgroundActive) {
basic.pause(0)
}
}
public matchWhen(tid: number, filter: number = undefined): boolean {
const sensor = this.rule.sensor
if (tid != sensor) return false
if (sensor == Tid.TID_SENSOR_START_PAGE) {
return true
} else if (getKind(sensor) == TileKind.Variable) {
return this.filterViaCompare()
} else {
if (
this.rule.filters.length == 0 ||
getKind(this.rule.filters[0]) == TileKind.EventCode
) {
const eventCode = this.lookupEventCode()
return eventCode == -1 || filter == eventCode
} else {
return this.filterViaCompare()
}
}
}
private lookupEventCode() {
const sensor = this.rule.sensor
// get default event for sensor, if exists
let evCode = defaultEventCode(sensor)
if (evCode) {
// override if user specifies event code
for (const m of this.rule.filters)
if (getKind(m) == TileKind.EventCode) {
return getParam(m)
}
return evCode
}
return undefined
}
private filterViaCompare(): boolean {
if (this.rule.filters.length) {
return this.interp.getValue(
[this.rule.sensor].concat(this.rule.filters),
0
) as boolean
} else {
return true // sensor changed value, but no constraint
}
}
private ok() {
return this.interp.running && this.active()
}
private timerOrSequenceRule() {
if (this.backgroundActive) {
this.interp.error(
`trying to spawn another background fiber for ${this.index}`
)
}
// make sure we have something to do
if (this.rule.actuators.length == 0) return
// prevent re-entrancy
if (this.active()) return
this.actionRunning = true
control.runInBackground(() => {
this.backgroundActive = true
while (this.ok()) {
if (this.wakeTime > 0) {
basic.pause(this.wakeTime)
this.wakeTime = 0
if (this.ok()) {
this.interp.addEvent({
kind: MicroCodeEventKind.TimerFire,
ruleIndex: this.index,
} as TimerEvent)
this.timerGoAhead = false
while (this.ok() && !this.timerGoAhead) {
basic.pause(1)
}
}
}
if (!this.ok()) break
this.runAction()
if (!this.ok()) break
this.checkForLoopFinish()
// yield, otherwise the app will hang
basic.pause(5)
}
this.backgroundActive = false
if (this.rule.sensor == Tid.TID_SENSOR_TIMER) {
this.interp.addEvent({
kind: MicroCodeEventKind.RestartTimer,
ruleIndex: this.index,
} as TimerEvent)
}
})
}
private atLoop() {
return (
this.modifierIndex < this.rule.modifiers.length &&
getTid(this.rule.modifiers[this.modifierIndex]) ==
Tid.TID_MODIFIER_LOOP
)
}
private checkForLoopFinish() {
control.waitMicros(ANTI_FREEZE_DELAY * 1000)
const actionKind = this.getActionKind()
if (
actionKind === ActionKind.Instant ||
getTid(this.rule.actuators[0]) == Tid.TID_ACTUATOR_SHOW_NUMBER
) {
this.actionRunning = false
return
}
if (!this.atLoop()) this.modifierIndex++
if (this.modifierIndex < this.rule.modifiers.length) {
const m = this.rule.modifiers[this.modifierIndex]
if (getTid(m) == Tid.TID_MODIFIER_LOOP) {
if (this.modifierIndex == this.rule.modifiers.length - 1) {
// forever loop
this.modifierIndex = 0
} else {
// get the loop bound
const loopBound = this.interp.getValue(
this.rule.modifiers.slice(this.modifierIndex + 1),
0
) as number
this.loopIndex++
if (this.loopIndex >= loopBound) {
this.actionRunning = false
} else {
this.modifierIndex = 0
}
}
} else {
// we move to the next tile in sequence
}
} else {
this.actionRunning = false
}
}
public releaseTimer() {
this.timerGoAhead = true
}
// use this to determine conflicts between rules
public getOutputResource() {
if (this.rule.actuators.length == 0) return undefined
return getOutputResource(this.rule.actuators[0])
}
public getActionKind() {
if (this.rule.actuators.length == 0) return undefined
return getActionKind(this.rule.actuators[0])
}
public getParamInstant() {
const actuator = this.rule.actuators[0]
if (this.rule.modifiers.length == 0)
return defaultModifier(actuator)
switch (actuator) {
case Tid.TID_ACTUATOR_CUP_X_ASSIGN:
case Tid.TID_ACTUATOR_CUP_Y_ASSIGN:
case Tid.TID_ACTUATOR_CUP_Z_ASSIGN:
case Tid.TID_ACTUATOR_SHOW_NUMBER:
case Tid.TID_ACTUATOR_RADIO_SEND:
case Tid.TID_ACTUATOR_RADIO_SET_GROUP: {
return this.interp.getValue(this.rule.modifiers, 0)
}
case Tid.TID_ACTUATOR_SWITCH_PAGE: {
let targetPage = 1
for (const m of this.rule.modifiers)
targetPage = getParam(m)
return targetPage
}
}
return undefined
}
public runInstant(): boolean {
const actuator = this.rule.actuators[0]
const param = this.getParamInstant()
const ok = this.interp.runAction(this.index, actuator, param)
this.kill()
return ok
}
private runAction() {
const actuator = this.rule.actuators[0]
let param: any = undefined
if (
this.rule.modifiers.length == 0 ||
getTid(this.rule.modifiers[0]) == Tid.TID_MODIFIER_LOOP
) {
param = defaultModifier(actuator)
} else {
switch (actuator) {
case Tid.TID_ACTUATOR_PAINT: {
const mod = this.rule.modifiers[this.modifierIndex]
const modEditor = mod as ModifierEditor
param = modEditor.getField()
break
}
case Tid.TID_ACTUATOR_MUSIC: {
// TODO: get the whole sequence and do as one shot, to avoid burps
const mod = this.rule.modifiers[
this.modifierIndex
] as MelodyEditor
param = melodyToNotes(mod.field)
break
}
case Tid.TID_ACTUATOR_SPEAKER: {
param = this.rule.modifiers[this.modifierIndex]
break
}
default:
param = this.getParamInstant()
}
}
this.interp.runAction(this.index, actuator, param)
if (this.getActionKind() === ActionKind.Instant)
this.interp.processNewState()
}
private getWakeTime() {
this.wakeTime = 0
const sensor = this.rule.sensor
if (
sensor == Tid.TID_SENSOR_TIMER ||
sensor == Tid.TID_SENSOR_START_PAGE
) {
let period = 0
let randomPeriod = 0
for (const m of this.rule.filters) {
// assert isTimeSpan(m)
const param = getParam(m)
if (param >= 0) period += param
else randomPeriod += -param // see hack in jdParam
}
if (
sensor == Tid.TID_SENSOR_TIMER &&
period == 0 &&
randomPeriod == 0
) {
period = 1000 // reasonable default
}
if (randomPeriod > 0)
period += Math.floor(Math.random() * randomPeriod)
this.wakeTime = period
return period
}
return 0
}
}
export enum SensorChange {
Up = 1,
Down,
}
export type SensorTid =
| Tid.TID_SENSOR_ACCELEROMETER
| Tid.TID_SENSOR_PRESS
| Tid.TID_SENSOR_RELEASE
| Tid.TID_SENSOR_RADIO_RECEIVE
export type ActionTid =
| Tid.TID_ACTUATOR_PAINT
| Tid.TID_ACTUATOR_SHOW_NUMBER
| Tid.TID_ACTUATOR_SPEAKER
| Tid.TID_ACTUATOR_MUSIC
| Tid.TID_ACTUATOR_RADIO_SEND
| Tid.TID_ACTUATOR_RADIO_SET_GROUP
export interface RuntimeHost {
emitClearScreen(): void
stopOngoingActions(): void
registerOnSensorEvent(
handler: (tid: number, filter: number) => void
): void
getSensorValue(tid: number, normalized: boolean): number
execute(tid: ActionTid, param: any): void
}
const vars2tids: VariableMap = {
cup_x: Tid.TID_SENSOR_CUP_X_WRITTEN,
cup_y: Tid.TID_SENSOR_CUP_Y_WRITTEN,
cup_z: Tid.TID_SENSOR_CUP_Z_WRITTEN,
}
enum MicroCodeEventKind {
StateUpdate,
SensorUpdate,
SwitchPage,
StartPage,
TimerFire,
RestartTimer,
}
interface MicroCodeEvent {
kind: MicroCodeEventKind
}
interface StateUpdateEvent extends MicroCodeEvent {
kind: MicroCodeEventKind.StateUpdate
updatedVars: string[]
}
interface SensorUpdateEvent extends MicroCodeEvent {
kind: MicroCodeEventKind.SensorUpdate
sensor: number
filter: number
}
interface SwitchPageEvent extends MicroCodeEvent {
kind: MicroCodeEventKind.SwitchPage
index: number
}
interface TimerEvent extends MicroCodeEvent {
kind: MicroCodeEventKind.TimerFire | MicroCodeEventKind.RestartTimer
ruleIndex: number
}
interface StartPageEvent extends MicroCodeEvent {
kind: MicroCodeEventKind.StartPage
}
type SensorInfo = {
delta: number
classicNormalized: boolean
}
const sensorTids = [
Tid.TID_SENSOR_LED_LIGHT,
Tid.TID_SENSOR_MICROPHONE, // more CPU intensive
Tid.TID_SENSOR_TEMP,
Tid.TID_SENSOR_MAGNET, // i2c
]
const sensorInfo: SensorInfo[] = [
{ delta: 10, classicNormalized: true },
{ delta: 10, classicNormalized: true },
{ delta: 1, classicNormalized: false },
{ delta: 1, classicNormalized: true }, // what about magnet?
]
export class Interpreter {
private hasErrors: boolean = false
public running: boolean = false
private currentPage: number = 0
private ruleClosures: RuleClosure[] = []
// state storage for variables and other temporary global state
// (local per-rule state is kept in RuleClosure)
public state: VariableMap = {}
public newState: VariableMap = {}
// state storage for sensor values
public sensors: SensorMap = {}
constructor(private program: ProgramDefn, private host: RuntimeHost) {
this.host.emitClearScreen()
this.host.registerOnSensorEvent((t, f) =>
this.onSensorEvent(t, f, f)
)
for (const v of Object.keys(vars2tids)) this.state[v] = 0
for (const tid of sensorTids) {
this.sensors[tid] = undefined
}
this.sensors[Tid.TID_SENSOR_RADIO_RECEIVE] = 0
this.startSensors()
this.running = true
// get ready to receive events
this.setupEventQueue()
this.switchPage(0)
}
private stopAllRules() {
this.ruleClosures.forEach(r => r.kill())
this.ruleClosures = []
}
private switchPage(page: number) {
// need to make sure outstanding events are dropped and no new events
this.eventQueue = []
this.allowEvents = false
// now stop existing rules
this.stopAllRules()
// set up new rule closures
this.currentPage = page
this.program.pages[this.currentPage].rules.forEach((r, index) => {
this.ruleClosures.push(new RuleClosure(index, r, this))
})
// start up timer-based rules (should these be events as well?)
this.ruleClosures.forEach(rc => rc.start(true))
// restart events
this.allowEvents = true
this.addEvent({
kind: MicroCodeEventKind.StartPage,
} as StartPageEvent)
// on start of each page, we allow checking of variables
this.addEvent({
kind: MicroCodeEventKind.StateUpdate,
updatedVars: Object.keys(vars2tids),
} as StateUpdateEvent)
}
public runAction(ruleIndex: number, action: Tile, param: any): boolean {
switch (action) {
case Tid.TID_ACTUATOR_SWITCH_PAGE: {
// no switch if no param
if (param) {
// when switching, drop any outstanding events
this.eventQueue = []
this.addEvent({
kind: MicroCodeEventKind.SwitchPage,
index: param,
} as SwitchPageEvent)
return true
}
return false
}
case Tid.TID_ACTUATOR_CUP_X_ASSIGN:
case Tid.TID_ACTUATOR_CUP_Y_ASSIGN:
case Tid.TID_ACTUATOR_CUP_Z_ASSIGN: {
const varName = getParam(action)
this.updateState(ruleIndex, varName, param)
return true
}
default:
this.host.execute(action as ActionTid, param)
}
return true
}
private updateState(ruleIndex: number, varName: string, v: number) {
if (!this.newState) this.newState = {}
this.newState[varName] = v
}
public processNewState() {
const updatedVars = Object.keys(this.newState)
if (updatedVars.length) {
updatedVars.forEach(k => {
this.state[k] = this.newState[k]
})
this.addEvent({
kind: MicroCodeEventKind.StateUpdate,
updatedVars: updatedVars,
} as StateUpdateEvent)
}
this.newState = {}
}
private processNewRules(newRules: RuleClosure[]) {
if (newRules.length == 0) return
// first new rule (in lexical order) on a resource wins
const resourceWinner: { [resource: number]: number } = {}
for (const rc of newRules) {
const resource = rc.getOutputResource()
const currentWinner = resourceWinner[resource]
if (currentWinner === undefined || rc.index < currentWinner)
resourceWinner[resource] = rc.index
}
const liveIndices = Object.keys(resourceWinner).map(
k => resourceWinner[parseInt(k)]
)
const live = newRules.filter(rc =>
liveIndices.some(i => i === rc.index)
)
const dead = this.ruleClosures.filter(rc => {
const resource = rc.getOutputResource()
const res =
live.indexOf(rc) === -1 &&
rc.active() &&
resourceWinner[resource] != undefined
return res
})
dead.forEach(rc => {
rc.kill()
})
// partition the live into instant and takes time
const instant = live.filter(
rc => rc.getActionKind() === ActionKind.Instant
)
// execute the instant ones right now (guaranteed no conflict)
instant.forEach(rc => {
const resource = rc.getOutputResource()
if (resource != OutputResource.PageCounter) {
rc.runInstant()
}
})
this.processNewState()
const switchPage = instant.find(
rc => rc.getOutputResource() == OutputResource.PageCounter
)
if (switchPage) {
if (switchPage.runInstant()) return // others don't get chance to run
}
const takesTime = live.filter(
rc => rc.getActionKind() === ActionKind.TakesTime
)
takesTime.forEach(rc => {
const whenSensor =
rc.rule.sensor &&
getKindTid(rc.rule.sensor) == TileKind.Sensor
if (!whenSensor) rc.kill()
rc.start()
})
}
private allowEvents = false
private eventQueueActive = false
private eventQueue: MicroCodeEvent[] = []
public addEvent(event: MicroCodeEvent) {
if (!this.running || !this.allowEvents) return
this.eventQueue.push(event)
}
private setupEventQueue() {
const matchingRules = (sensor: number, filter: number) => {
return this.ruleClosures.filter(rc =>
rc.matchWhen(sensor, filter)
)
}
control.inBackground(() => {
this.eventQueueActive = true
while (this.running) {
if (this.eventQueue.length) {
const ev = this.eventQueue[0]
this.eventQueue.removeAt(0)
switch (ev.kind) {
case MicroCodeEventKind.StateUpdate: {
control.waitMicros(ANTI_FREEZE_DELAY * 1000)
const event = ev as StateUpdateEvent
const rules = event.updatedVars.map(v => {
const tid = vars2tids[v] as number
return matchingRules(tid, undefined)
})
// flatten into one list
let newOnes: RuleClosure[] = []
rules.forEach(l => {
newOnes = newOnes.concat(l)
})
this.processNewRules(newOnes)
break
}
case MicroCodeEventKind.SensorUpdate: {
const event = ev as SensorUpdateEvent
// see if any rule matches
this.processNewRules(
matchingRules(event.sensor, event.filter)
)
break
}
case MicroCodeEventKind.SwitchPage: {
control.waitMicros(ANTI_FREEZE_DELAY * 1000)
const event = ev as SwitchPageEvent
this.switchPage(event.index - 1)
break
}
case MicroCodeEventKind.StartPage: {
this.processNewRules(
matchingRules(
Tid.TID_SENSOR_START_PAGE,
undefined
)
)
break
}
case MicroCodeEventKind.RestartTimer: {
const event = ev as TimerEvent
const rc = this.ruleClosures[event.ruleIndex]
rc.start(true)
break
}
case MicroCodeEventKind.TimerFire: {
const event = ev as TimerEvent
const rc = this.ruleClosures[event.ruleIndex]
// TODO: this isn't good enough, we need to
// TODO: kill rules that are conflicting before releasing
rc.releaseTimer()
break
}
}
}
basic.pause(10)
}
this.eventQueueActive = false
})
}
public onSensorEvent(tid: number, newVal: number, filter: number = -1) {
this.sensors[tid] = newVal
this.addEvent({
kind: MicroCodeEventKind.SensorUpdate,
sensor: tid,
filter: filter,
} as SensorUpdateEvent)
}
private getSensorValue(tid: number): number {
const gen1to5 = (v: number) => Math.round(4 * v) + 1
return microcodeClassic
? gen1to5(this.host.getSensorValue(tid, true))
: this.host.getSensorValue(tid, false)
}
// note that radio is not polled as a sensor
private startSensorsActive = false
private startSensors() {
control.inBackground(() => {
this.startSensorsActive = true
while (this.running) {
// poll the sensors and check for change
sensorTids.forEach((tid, index) => {
const oldReading = this.sensors[tid]
const newReading = this.getSensorValue(tid)
const delta = Math.abs(newReading - oldReading)
if (
oldReading === undefined ||
(microcodeClassic && newReading != oldReading) ||
!microcodeClassic
) {
basic.pause(1)
this.onSensorEvent(
tid,
newReading,
newReading > oldReading
? SensorChange.Up
: SensorChange.Down
)
}
})
basic.pause(500)
}
this.startSensorsActive = false
})
}
stop() {
// stop all activity
this.running = false
while (this.startSensorsActive || this.eventQueueActive) {
basic.pause(1)
}
this.stopAllRules()
this.host.stopOngoingActions()
}
public error(msg: string) {
console.log(msg)
control.panic(123)
}
private getExprValue(expr: Tile): string {
const tid = getTid(expr)
switch (tid) {
case Tid.TID_OPERATOR_DIVIDE:
return "/"
case Tid.TID_OPERATOR_MULTIPLY:
return "*"
case Tid.TID_OPERATOR_MINUS:
return "-"
case Tid.TID_OPERATOR_PLUS:
return "+"
case Tid.TID_COMPARE_EQ:
return "=="
case Tid.TID_COMPARE_NEQ:
return "!="
case Tid.TID_COMPARE_GT:
return ">"
case Tid.TID_COMPARE_GTE:
return ">="
case Tid.TID_COMPARE_LT:
return "<"
case Tid.TID_COMPARE_LTE:
return "<="
}
const kind = getKind(expr)
const param = getParam(expr)
const lookupVar = (v: string) => {
return (this.state[v] as number).toString()
}
const lookupSensor = (tid: number) => {
const sensorTid = getParam(tid)
const val = this.sensors[sensorTid] as number
return val !== undefined ? val.toString() : "0"
}
switch (kind) {
case TileKind.Sensor:
return lookupSensor(tid)
case TileKind.Literal:
return (param as number).toString()
case TileKind.Variable:
return lookupVar(param)
default:
this.error(`can't emit kind ${kind} for ${getTid(expr)}`)
return undefined
}
}
public getValue(tiles: Tile[], defl: number): number | boolean {
let tokens: string[] = []
const rnd = (max: number) => Math.floor(Math.random() * max) + 1
for (let i = 0; i < tiles.length; i++) {
const m = tiles[i]
if (getTid(m) == Tid.TID_MODIFIER_RANDOM_TOSS) {
const max =
i == tiles.length - 1
? 6 // default value
: (this.getValue(tiles.slice(i + 1), 0) as number)
tokens.push(rnd(max).toString())
break
} else {
tokens.push(this.getExprValue(m))
}
}
const result = new parser.Parser(tokens).parse()
return result
}
}
}