-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.js
1600 lines (1470 loc) · 41.9 KB
/
model.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* The model represents the simulation of the Emoji Quest world.
* The world is not sharded and every turn visits the entire world.
* The simulation works by gathering intents from the player and any simulated
* non-player entities, then running an auction to determine which intents
* succeed or fail to effect results for the simulated turn.
*
* The model emits transitions to a macro view model, which renders animated
* transitions for a section of the simulation for the player.
* The simulation is not responsible for choosing which entities to render, but
* broadcasts all world transitions and expects the view layer to cull
* irrelevant information.
*/
// @ts-check
import { assert, assertDefined, assumeDefined } from './lib/assert.js';
import { halfOcturn, fullOcturn, quarturnToOcturn } from './lib/geometry2d.js';
/**
* @callback TypeFn
* @param {number} entity
* @returns {number} type
*/
/**
* @typedef {Object} Bid
* @prop {number} position - origin
* @prop {number} direction
* @prop {number | undefined} turn - absence indicates a jump/teleport
* @prop {boolean} transit
* @prop {number} destination
* @prop {number} health
* @prop {number} stamina
* @prop {import('./types.js').ActionHandler} [handler]
* @prop {import('./types.js').ActionParameters} [parameters]
* @prop {string} [dialog]
* @prop {number} [morphType]
* @prop {number} [shiftType]
* @prop {number} [patient]
* @prop {boolean} [mirror]
*/
/**
* @callback WatchTerrainFn
* @param {Iterable<number>} locations
* @param {(location: number) => void} watcher
*/
/**
* @callback CaptureFn
* @param {number | undefined} player
* @returns {import('./types.js').Snapshot}
*/
// TOOD consider DeepReadonly on returned snapshot or enforce immutability by
// other means.
const makeFlags = function* () {
for (let i = 0; true; i += 1) {
yield 1 << i;
}
};
export const [terrainWater, terrainLava, terrainCold, terrainHot, terrainNext] =
makeFlags();
export const terrainMask = terrainNext - 1;
export const [heldSlot, packSlot] = makeFlags();
/**
* @template T
* @param {Array<T>} candidates
* @param {number} index
*/
const pluck = (candidates, index) => {
const winner = candidates[index];
candidates[index] = candidates[candidates.length - 1];
candidates.length--;
return winner;
};
/**
* @param {Object} args
* @param {number} args.size
* @param {import('./types.js').AdvanceFn} args.advance
* @param {import('./types.js').MacroViewModelFacetForModel} args.macroViewModel
* @param {import('./mechanics.js').Mechanics} args.mechanics
* @param {import('./types.js').Snapshot} [args.snapshot]
*/
export function makeModel({
size,
advance,
macroViewModel,
mechanics,
snapshot,
}) {
const {
itemTypes,
agentTypes,
// tileTypes,
// effectTypes,
// tileTypesByName,
// agentTypesByName,
itemTypesByName,
effectTypesByName,
tileTypeForAgent,
// tileTypeForItemType,
// tileTypeForEffectType,
craft,
bump,
// viewText,
} = mechanics;
const emptyItem = itemTypesByName.empty;
let entities = new Uint16Array(size);
let entitiesWriteBuffer = new Uint16Array(size);
/**
* The terrain model is a 1 byte bit mask per world cell.
*
* 0: water
* 1: magma
*/
const terrain = new Uint8Array(size);
/** @type {Map<number, Set<(location: number) => void>>} */
const terrainWatchers = new Map();
/** @type {WatchTerrainFn} */
const watchTerrain = (locations, watcher) => {
for (const location of locations) {
let watchers = terrainWatchers.get(location);
if (watchers === undefined) {
watchers = new Set();
terrainWatchers.set(location, watchers);
}
watchers.add(watcher);
}
};
/** @type {WatchTerrainFn} */
const unwatchTerrain = (locations, watcher) => {
for (const location of locations) {
const watchers = assumeDefined(terrainWatchers.get(location));
assert(watchers.has(watcher));
watchers.delete(watcher);
if (watchers.size === 0) {
terrainWatchers.delete(location);
}
}
};
/**
* @param {number} location
*/
const getTerrainFlags = location => {
return terrain[location];
};
/**
* @param {number} location
* @param {number} terrainFlags
*/
const setTerrainFlags = (location, terrainFlags) => {
terrain[location] = terrainFlags;
const watchers = terrainWatchers.get(location);
if (watchers !== undefined) {
for (const watch of watchers) {
watch(location);
}
}
};
/**
* @param {number} location
* @param {number} terrainFlags
*/
const toggleTerrainFlags = (location, terrainFlags) => {
terrain[location] ^= terrainFlags;
const watchers = terrainWatchers.get(location);
if (watchers !== undefined) {
for (const watch of watchers) {
watch(location);
}
}
};
// TODO consider assigning every position a priority, then shuffling
// priorities locally each turn.
// const priorities = new Array(size);
/** @type {Set<number>} entity number */
const moveIntents = new Set();
/** @type {Map<number, number>} entity number -> location number */
const locations = new Map();
/** @type {Map<number, number>} */
const entityTypes = new Map();
/** @type {Map<number, Map<number, Bid>>} target tile number -> intended
* entity number -> transition/bid */
const targets = new Map();
/** @type {Set<number>} entity numbers of mobile entities */
const mobiles = new Set();
/** @type {Map<number, Bid>} */
const moves = new Map();
/** @type {Set<number>} */
const removes = new Set();
/** @type {Map<number, number>} */
const bounces = new Map();
/** @type {Map<number, number>} entity to mode number (0 implied if absent) */
const tileTypes = new Map();
/** @type {Set<number>} entities that may have changed mode*/
const staleTileTypes = new Set();
/** @type {Array<{agent: number, patient: number, origin: number, destination: number, direction: number}>} */
const bumps = [];
/** @type {Map<number, {type: number, next: number}>} */
const dialogs = new Map();
/** @type {Set<number>} */
const craftIntents = new Set();
/** @type {Map<number, number>} agent to patient */
const bumpIntents = new Map();
/**
* Functions to inform of the motion of an entity.
* The entity does not need to still exist, and this invariant should be
* revisited if entity numbers get collected and reused in the future.
* This would complicate the unfollow function, which currently is able to
* distinguish an accidental call from a deliberate call by balancing follow
* and unfollow calls.
*
* @type {Map<number, Set<import('./types.js').ModelFollower>>}
*/
const followers = new Map();
let nextEntity = 1; // 0 implies non-existant.
/**
* Some entities may have an inventory.
* Each inventory is an array of item types, and type zero indicates an empty
* slot.
* This is sufficiently general to model inventories for arbitrary entities.
*
* Crafting mechanics apply only to the first two slots of the inventory
* array regardless of length.
*
* The player entity specifically has two hand slots followed by eight pack
* slots.
*
* The mechanics do not yet necessitate item entities to track item instance
* state.
* Concepts like "wear" would require this, but can also be cheaply but
* imperfectly modeled with a probability of wearing out on any use.
*
* @type {Map<number, Array<number>>}
*/
const inventories = new Map();
/** @type {Map<number, number>} */
const healths = new Map();
/** @type {Map<number, number>} */
const staminas = new Map();
/** @type {Set<number>} */
const staleHealths = new Set();
/** @type {Map<number, number>} */
const healthTrajectories = new Map();
/** @type {Set<number>} */
const staleHealthTrajectories = new Set();
/** @type {Map<number, number>} for teleport/warp/jump */
const entityTargetLocations = new Map();
/** @type {Map<number, number>} for teleport/warp/jump */
const entityTargetEntities = new Map();
/** @type {Map<number, Set<number>>} cograph of entityTargetEntities */
const entitySourceEntities = new Map();
/**
* Note that entity numbers are not reused and this could lead to problems if
* the next ID counter fills the double precision mantissa.
* The follow / unfollow functions would need to be revisited if we were to
* collect and reuse entity identifiers.
* Specifically, we would probably need to have follow return an opaque token
* (possibly a closure) to balance unfollow calls.
*
* @param {number} type
* @returns {number} entity
*/
function createEntity(type) {
const entity = nextEntity;
nextEntity++;
entityTypes.set(entity, type);
return entity;
}
/**
* @param {number} entity
* @param {number} location
*/
function destroyEntity(entity, location) {
removes.add(entity);
entityTypes.delete(entity);
tileTypes.delete(entity);
mobiles.delete(entity);
locations.delete(entity);
entityTypes.delete(entity);
mobiles.delete(entity);
staleTileTypes.delete(entity);
staleHealths.delete(entity);
staleHealthTrajectories.delete(entity);
entitiesWriteBuffer[location] = 0;
// Update entityTargetEntities graph, including
// backward facing edges.
const targetEntity = entityTargetEntities.get(entity);
if (targetEntity !== undefined) {
entityTargetEntities.delete(entity);
const sourceEntities = assumeDefined(
entitySourceEntities.get(targetEntity),
);
sourceEntities.delete(entity);
if (sourceEntities.size === 0) {
entitySourceEntities.delete(targetEntity);
}
}
const sourceEntities = entitySourceEntities.get(entity);
if (sourceEntities !== undefined) {
for (const sourceEntity of sourceEntities) {
entityTargetEntities.delete(sourceEntity);
}
}
entitySourceEntities.delete(entity);
}
/** @type {TypeFn} */
function entityType(entity) {
const type = entityTypes.get(entity);
assertDefined(
type,
`Cannot get type for non-existent model entity ${entity}`,
);
return type;
}
/**
* @param {number} entity - entity
* @returns {number} tile type
*/
const entityTileType = entity => tileTypeForAgent(entity, kit);
/**
* @param {number} e - entity
* @returns {number} t - tile
*/
function locate(e) {
const t = locations.get(e);
assertDefined(t, `Simulation assertion error: cannot locate entity ${e}`);
return t;
}
/**
* @param {number} e
* @param {import('./types.js').ModelFollower} follower
*/
function follow(e, follower) {
let entityFollowers = followers.get(e);
if (entityFollowers === undefined) {
/** @type {Set<import('./types.js').ModelFollower>} */
entityFollowers = new Set();
followers.set(e, entityFollowers);
}
assert(!entityFollowers.has(follower));
entityFollowers.add(follower);
const inventory = inventories.get(e);
if (inventory !== undefined) {
for (let slot = 0; slot < inventory.length; slot++) {
onInventory(e, slot, inventory[slot]);
}
}
const health = healths.get(e) ?? 5;
onHealth(e, health);
const stamina = staminas.get(e) ?? 5;
onStamina(e, stamina);
}
/**
* @param {number} e
* @param {import('./types.js').ModelFollower} follower
*/
function unfollow(e, follower) {
const entityFollowers = followers.get(e);
assertDefined(entityFollowers);
assert(entityFollowers.has(follower));
entityFollowers.delete(follower);
}
/**
* @param {number} e
* @param {import('./types.js').CursorChange} change
* @param {number} destination
*/
function onMove(e, change, destination) {
const entityFollowers = followers.get(e);
if (entityFollowers !== undefined) {
for (const follower of entityFollowers) {
follower.move(e, change, destination);
}
}
}
/**
* @param {number} e
* @param {number} destination
*/
function onJump(e, destination) {
const entityFollowers = followers.get(e);
if (entityFollowers !== undefined) {
for (const follower of entityFollowers) {
follower.jump(e, destination);
}
}
}
/**
* @param {number} e
* @param {number} slot
* @param {number} itemType
*/
function onInventory(e, slot, itemType) {
const entityFollowers = followers.get(e);
if (entityFollowers !== undefined) {
for (const follower of entityFollowers) {
follower.inventory(e, slot, itemType);
}
}
}
/**
* @param {number} e
* @param {string} dialog
*/
function onDialog(e, dialog) {
const entityFollowers = followers.get(e);
if (entityFollowers !== undefined) {
for (const follower of entityFollowers) {
follower.dialog(e, dialog);
}
}
}
/**
* @param {number} e
* @param {import('./types.js').Recipe} recipe
*/
function onCraft(e, recipe) {
const entityFollowers = followers.get(e);
if (entityFollowers !== undefined) {
for (const follower of entityFollowers) {
follower.craft(e, recipe);
}
}
}
/**
* @param {number} e
* @param {number} health
*/
function onHealth(e, health) {
const entityFollowers = followers.get(e);
if (entityFollowers !== undefined) {
for (const follower of entityFollowers) {
follower.health(e, health);
}
}
}
/**
* @param {number} e
* @param {number} stamina
*/
function onStamina(e, stamina) {
const entityFollowers = followers.get(e);
if (entityFollowers !== undefined) {
for (const follower of entityFollowers) {
follower.stamina(e, stamina);
}
}
}
/**
* @param {number} t - target tile number
* @returns {Map<number, Bid>} from entity
*/
function bids(t) {
let b = targets.get(t);
if (!b) {
/** @type {Map<number, Bid>} */
b = new Map();
targets.set(t, b);
}
return b;
}
/**
* @param {number} agent
* @param {number} patient
*/
function talk(agent, patient) {
const patientType = entityTypes.get(patient);
if (patientType === undefined) {
return false;
}
const patientDesc = agentTypes[patientType];
const { dialog } = patientDesc;
if (dialog !== undefined) {
// The dialog might cycle on repeated bumps and reset when the
// agent fails to repeat a bump.
const rotation = dialogs.get(agent);
let index = 0;
if (rotation !== undefined && rotation.type === patientType) {
index = rotation.next;
}
index = index % dialog.length;
onDialog(agent, dialog[index]);
dialogs.set(agent, { type: patientType, next: index + 1 });
return true;
}
return false;
}
/**
* @param {number} agent
* @param {number} direction - in quarters clockwise from north
* @param {boolean} repeat - whether the agent intends to act upon the
* patient before them.
*/
function intendToMove(agent, direction, repeat = false) {
if (
moveIntents.has(agent) ||
craftIntents.has(agent) ||
bumpIntents.has(agent)
) {
return;
}
moveIntents.add(agent);
const origin = locate(agent);
const cursorChange = advance({ position: origin, direction });
if (cursorChange === undefined) {
return;
}
const { position: destination, turn, transit } = cursorChange;
const patient = entities[destination];
if (patient !== 0) {
if (!repeat) {
bumps.push({
agent,
patient,
origin,
destination,
direction,
});
}
} else {
const { passable, dialog, health, stamina } = pass(agent, destination);
if (!passable) {
assertDefined(dialog);
bounces.set(agent, direction);
onDialog(agent, dialog);
} else {
assertDefined(health);
assertDefined(stamina);
bids(destination).set(agent, {
position: origin,
destination,
direction,
turn,
transit,
health,
stamina,
});
}
}
}
/**
* @param {number} entity
*/
function intendToCraft(entity) {
if (
moveIntents.has(entity) ||
craftIntents.has(entity) ||
bumpIntents.has(entity)
) {
return;
}
craftIntents.add(entity);
}
function entityEffect() {
return effectTypesByName.empty;
}
/**
* @param {number} entity
* @param {number} direction
* @param {number} location
*/
function take(entity, direction, location) {
macroViewModel.take(
entity,
(direction * quarturnToOcturn + halfOcturn) % fullOcturn,
);
destroyEntity(entity, location);
bounces.delete(entity);
}
/**
* @param {number} entity
* @param {number} location
*/
function fell(entity, location) {
macroViewModel.fell(entity);
destroyEntity(entity, location);
bounces.delete(entity);
}
/**
* @param {number} entity
* @param {number} entityType
*/
function replace(entity, entityType) {
entityTypes.set(entity, entityType);
staleTileTypes.add(entity);
bounces.delete(entity);
}
/**
* @param {number} entity
*/
function entityTargetLocation(entity) {
return entityTargetLocations.get(entity);
}
/**
* @param {number} entity
* @param {number} target
*/
function setEntityTargetLocation(entity, target) {
if (!entityTypes.has(entity)) {
return false;
}
entityTargetLocations.set(entity, target);
return true;
}
/**
* @param {number} entity
*/
function entityTargetEntity(entity) {
return entityTargetEntities.get(entity);
}
/**
* @param {number} entity
* @param {number} target
*/
function setEntityTargetEntity(entity, target) {
if (!entityTypes.has(entity)) {
return false;
}
if (!entityTypes.has(target)) {
return false;
}
entityTargetEntities.set(entity, target);
return true;
}
/** @type {import('./types.js').ModelKit} */
const kit = {
entityType,
entityEffect,
take,
fell,
inventory,
put,
has,
holds,
cold,
hot,
sick,
afloat,
immersed,
entityHealth,
entityStamina,
advance,
};
/**
* effects transitions
*/
function tick() {
// Measure
// let treeCount = 0;
// for (let i = 0; i < size; i++) {
// }
// // Create
// for (let i = 0; i < size; i++) {
// }
// Think
for (const entity of mobiles) {
// TODO select from eligible directions.
intendToMove(entity, Math.floor(Math.random() * 4));
}
// Update entity health trajectories
for (const entity of staleHealthTrajectories) {
const unhealthy = hot(entity) || cold(entity);
if (unhealthy) {
healthTrajectories.set(entity, -1);
} else {
healthTrajectories.delete(entity);
}
}
// Update entity health
for (const [entity, trajectory] of healthTrajectories.entries()) {
let health = healths.get(entity) ?? 5;
health += trajectory;
health = Math.max(0, health);
if (health === 5) {
healths.delete(entity);
} else {
healths.set(entity, health);
}
staleHealths.add(entity);
}
// Emit health change
for (const entity of staleHealths) {
const health = healths.get(entity) ?? 5;
onHealth(entity, health);
staleTileTypes.add(entity);
}
// Prepare the next generation
entitiesWriteBuffer.set(entities);
// Bump.
// Bumps must precede the auction for moves because some bumps
// may result in a bid to move or teleport, the destruction of the
// patient (invalidating its bid to move), or the transformation
// of the patient (invalidating or altering some intended actions).
for (const { agent, patient, destination, direction } of bumps) {
bounces.set(agent, direction);
// A side-effect of bumping may include cancellation of the above
// bounce, in the case that the agent is destroyed by another bump.
const parameters = {
agent,
patient,
destination,
direction,
};
const bumped = bump(kit, parameters);
if (bumped !== undefined) {
const { handler, dialog, jump, morphType, shiftType, mirror } = bumped;
if (jump !== undefined) {
let jumpTargetLocation;
if (jump === 'location') {
jumpTargetLocation = entityTargetLocation(patient);
} else if (jump === 'entity') {
const jumpTargetEntity = entityTargetEntity(patient);
if (jumpTargetEntity !== undefined) {
const jumpTargetEntityLocation = locate(jumpTargetEntity);
if (jumpTargetEntityLocation > 0) {
const adjacentCursor = advance({
position: jumpTargetEntityLocation,
direction,
});
if (adjacentCursor !== undefined) {
jumpTargetLocation = adjacentCursor.position;
}
}
}
} else {
throw new Error(
`Program invariant failed: jump property of actions should be validated to one of "location" or "entity"`,
);
}
if (jumpTargetLocation !== undefined) {
const {
passable,
dialog: passDialog,
health,
stamina,
} = pass(agent, jumpTargetLocation);
if (!passable) {
if (passDialog !== undefined) {
onDialog(agent, passDialog);
}
} else {
assertDefined(health);
assertDefined(stamina);
bids(jumpTargetLocation).set(agent, {
position: locate(agent),
destination: jumpTargetLocation,
direction,
turn: undefined,
transit: false,
health,
stamina,
handler,
parameters,
dialog: dialog,
shiftType,
morphType,
patient,
mirror,
});
}
} else {
// The jump target does not exist because of the direction and
// topology.
}
} else {
bids(destination).set(agent, {
position: locate(agent),
destination,
direction,
turn: undefined,
transit: false,
health: 0,
stamina: 0,
handler,
parameters,
dialog,
morphType,
shiftType,
patient,
mirror,
});
}
} else {
talk(agent, patient);
}
}
// Auction for Moves.
// Considering every tile that an entity wishes to move into or act upon.
for (const [destination, candidates] of targets.entries()) {
// TODO filter entities that have been scheduled for demolition from the
// losers.
const losers = [...candidates.keys()];
const winner = pluck(losers, Math.floor(Math.random() * losers.length));
const bid = assumeDefined(candidates.get(winner));
const {
position: origin,
health,
stamina,
handler,
parameters,
dialog,
shiftType,
morphType,
patient = 0,
mirror,
} = bid;
if (dialog !== undefined) {
onDialog(winner, dialog);
}
if (handler !== undefined && parameters !== undefined) {
if (mirror) {
handler(kit, parameters, 1, 0);
} else {
handler(kit, parameters, 0, 1);
}
}
if (shiftType !== undefined) {
replace(winner, shiftType);
}
if (patient !== 0 && morphType !== undefined) {
replace(patient, morphType);
}
// Bump
if (entities[destination] !== 0) {
continue;
}
// Move
locations.set(winner, destination);
staleTileTypes.add(winner);
staleHealthTrajectories.add(winner);
moves.set(winner, bid);
entitiesWriteBuffer[destination] = winner;
entitiesWriteBuffer[origin] = 0;
adjustHealth(winner, health);
adjustStamina(winner, stamina);
// Bounce all of the candidates that did not get to proceed in the
// direction they intended.
for (const loser of losers) {
const change = assumeDefined(candidates.get(loser));
const { direction } = change;
if (direction === undefined) {
// TODO
// macroViewModel.shake(loser);
} else {
macroViewModel.bounce(loser, direction * quarturnToOcturn);
}
}
}
// Craft.
for (const entity of craftIntents) {
const inventory = inventories.get(entity);
if (inventory !== undefined && inventory.length >= 2) {
const agent = inventory[0];
const reagent = inventory[1];
const formula = craft(agent, reagent);
if (formula !== undefined) {
const [product, byproduct, dialog] = formula;
inventory[0] = product;
inventory[1] = byproduct;
onCraft(entity, { agent, reagent, product, byproduct });
if (dialog !== undefined) {
onDialog(entity, dialog);
}
} else {
onDialog(entity, `💩 Can’t combine these!`);
}
}
}
// Orchestrate moves and moves combined with type type changes.
for (const [entity, change] of moves.entries()) {
let newType;
if (staleTileTypes.has(entity)) {
staleTileTypes.delete(entity);
const oldType = assumeDefined(tileTypes.get(entity));
newType = tileTypeForAgent(entity, kit);
if (oldType == newType) {
newType = undefined;
} else {
tileTypes.set(entity, newType);
}
// Hold my beer.
staleTileTypes.delete(entity);
}
const { position, destination, direction, turn, transit } = change;
if (turn === undefined) {
macroViewModel.jump(
entity,
destination,
direction * quarturnToOcturn,
newType || tileTypeForAgent(entity, kit),
);
onJump(entity, destination);
} else {
if (newType !== undefined) {
macroViewModel.movingReplace(
entity,
newType,
destination,
direction * quarturnToOcturn,
turn,
);
} else {
macroViewModel.move(
entity,
destination,
direction * quarturnToOcturn,
turn,
);
}
onMove(
entity,
{
position,
direction,
turn,
transit,
},
destination,