-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabsorption-3.js
More file actions
1345 lines (1164 loc) Β· 42.1 KB
/
absorption-3.js
File metadata and controls
1345 lines (1164 loc) Β· 42.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
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
// === SECTION 1: INITIALIZATION AND CONSTANTS ===
document.addEventListener("DOMContentLoaded", async () => {
// Fixed canvas size as per brief: 256x144 cells
const GRID_WIDTH = 256;
const GRID_HEIGHT = 144;
const SCALE_SIZE = 3;
const app = new PIXI.Application({
width: GRID_WIDTH * SCALE_SIZE,
height: GRID_HEIGHT * SCALE_SIZE,
backgroundColor: 0x000000,
});
document.getElementById("canvas-div").appendChild(app.view);
// === CONSTANTS ===
const CONSTANTS = {
// World parameters
WORLD: {
SCALE_SIZE: SCALE_SIZE,
TICK_INTERVAL: 40,
COLS: GRID_WIDTH,
ROWS: GRID_HEIGHT,
},
// Particle modes and transformations
FLUX: {
P_ENERGY: 0.05, // Increased from 0.01 to 0.05 (5% chance) for more energy spawning
WATER_DIAGONAL_CHANCE: 0.1,
},
// Plant genetics parameters
GENETICS: {
GROWTH_ENERGY_THRESHOLD: 8,
MUTATION_RATE: 0.1,
MUTATION_STRENGTH: 0.2,
},
// Growth parameters
GROWTH: {
ENERGY_TO_GROW: 5,
GROWTH_COST: 3,
MAX_ENERGY: 20,
},
// Simulation parameters
SIMULATION: {
INITIAL_WATER_COUNT: 1000,
INITIAL_SEED_COUNT: 1,
},
};
// Colors and mode definitions
const colors = {
ENERGY: 0xffff00,
WATER: 0x0066ff,
VAPOR: 0xc8ffff,
SEED: 0x8b4513,
STEM: 0x228b22,
LEAF: 0x00ff00,
BUD: 0x90ee90, // Light green - visible but natural
NODE: 0x14a014,
FLOWER: 0xff69b4,
};
const modeTextures = Object.entries(colors).reduce((acc, [mode, color]) => {
const graphics = new PIXI.Graphics();
graphics.beginFill(color);
graphics.drawRect(0, 0, 1, 1);
graphics.endFill();
acc[mode] = app.renderer.generateTexture(graphics);
return acc;
}, {});
// Performance monitoring setup
const fpsTextStyle = new PIXI.TextStyle({
fontFamily: "Arial",
fontSize: 24,
fill: "white",
});
const fpsText = new PIXI.Text("FPS: 0", fpsTextStyle);
fpsText.x = 10;
fpsText.y = 10;
app.stage.addChild(fpsText);
const particleCountText = new PIXI.Text("Particles: 0", fpsTextStyle);
particleCountText.x = 10;
particleCountText.y = 40;
app.stage.addChild(particleCountText);
const fastForwardText = new PIXI.Text("", fpsTextStyle);
fastForwardText.x = 10;
fastForwardText.y = 70;
app.stage.addChild(fastForwardText);
// Core simulation parameters
let particles = [];
let frame = 0;
let fastForward = false;
let fastForwardFactor = 10;
let lastRenderTime = performance.now();
let idCounter = 1;
// Grid setup with fixed dimensions
let scaleSize = CONSTANTS.WORLD.SCALE_SIZE;
let cols = CONSTANTS.WORLD.COLS;
let rows = CONSTANTS.WORLD.ROWS;
// Particle modes
const Mode = {
ENERGY: "ENERGY",
WATER: "WATER",
VAPOR: "VAPOR",
SEED: "SEED",
STEM: "STEM",
LEAF: "LEAF",
BUD: "BUD",
NODE: "NODE",
FLOWER: "FLOWER",
};
// === SECTION 2: LAYERED OCCUPANCY GRIDS ===
class LayeredOccupancyGrid {
constructor(cols, rows) {
this.cols = cols;
this.rows = rows;
// Separate layers for different particle types
this.plantLayer = new Array(cols * rows).fill(null);
this.waterLayer = new Array(cols * rows).fill(null);
this.energyLayer = new Array(cols * rows).fill(null);
// Visual overlays for water and energy
this.waterOverlays = new Array(cols * rows).fill(null);
this.energyOverlays = new Array(cols * rows).fill(null);
}
getIndex(x, y) {
return y * this.cols + x;
}
// Plant layer methods
setPlant(x, y, particle) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
this.plantLayer[this.getIndex(x, y)] = particle;
}
}
getPlant(x, y) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
return this.plantLayer[this.getIndex(x, y)];
}
return null;
}
removePlant(x, y) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
this.plantLayer[this.getIndex(x, y)] = null;
}
}
// Water layer methods
setWater(x, y, particle = null) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
const index = this.getIndex(x, y);
this.waterLayer[index] = particle;
// Create/remove visual overlay
if (particle && !this.waterOverlays[index]) {
const overlay = new PIXI.Graphics();
overlay.beginFill(0x0066ff, 0.2); // 20% alpha blue
overlay.drawRect(0, 0, scaleSize, scaleSize);
overlay.endFill();
overlay.x = x * scaleSize;
overlay.y = y * scaleSize;
app.stage.addChild(overlay);
this.waterOverlays[index] = overlay;
} else if (!particle && this.waterOverlays[index]) {
app.stage.removeChild(this.waterOverlays[index]);
this.waterOverlays[index] = null;
}
}
}
getWater(x, y) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
return this.waterLayer[this.getIndex(x, y)];
}
return null;
}
hasWater(x, y) {
return this.getWater(x, y) !== null;
}
// Energy layer methods
setEnergy(x, y, particle = null) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
const index = this.getIndex(x, y);
this.energyLayer[index] = particle;
// Create/remove visual overlay
if (particle && !this.energyOverlays[index]) {
const overlay = new PIXI.Graphics();
overlay.beginFill(0xffff00, 0.3); // 30% alpha yellow
overlay.drawRect(0, 0, scaleSize, scaleSize);
overlay.endFill();
overlay.x = x * scaleSize;
overlay.y = y * scaleSize;
app.stage.addChild(overlay);
this.energyOverlays[index] = overlay;
} else if (!particle && this.energyOverlays[index]) {
app.stage.removeChild(this.energyOverlays[index]);
this.energyOverlays[index] = null;
}
}
}
getEnergy(x, y) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
return this.energyLayer[this.getIndex(x, y)];
}
return null;
}
hasEnergy(x, y) {
return this.getEnergy(x, y) !== null;
}
// Check if plant layer is occupied (for movement/growth)
isPlantOccupied(x, y) {
if (x < 0 || x >= this.cols || y < 0 || y >= this.rows) return true;
return this.getPlant(x, y) !== null;
}
// Moore neighborhood check for crown shyness
isEmptyMooreNeighborhood(x, y) {
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
if (dx === 0 && dy === 0) continue;
const nx = x + dx,
ny = y + dy;
if (nx < 0 || nx >= this.cols || ny < 0 || ny >= this.rows) continue;
if (this.getPlant(nx, ny)) return false;
}
}
return true;
}
// Get plant neighbors for resource flow
getPlantNeighbors(x, y) {
let neighbors = [];
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
if (dx === 0 && dy === 0) continue;
let nx = x + dx,
ny = y + dy;
if (nx >= 0 && nx < this.cols && ny >= 0 && ny < this.rows) {
const plant = this.getPlant(nx, ny);
if (plant !== null) {
neighbors.push({ plant, x: nx, y: ny });
}
}
}
}
return neighbors;
}
}
let occupancyGrid = new LayeredOccupancyGrid(cols, rows);
// Helper function to count plant cells for a given plant ID
function countPlantCells(plantId) {
return particles.filter((p) => p.isPlantPart() && p.plantId === plantId)
.length;
}
// === SECTION 3: PLANT GENETICS SYSTEM ===
class PlantGenetics {
constructor(parentA = null, parentB = null) {
if (parentA && parentB) {
this.combineParents(parentA, parentB);
} else if (parentA) {
this.inheritFromParent(parentA);
} else {
this.generateRandom();
}
}
generateRandom() {
this.genes = {
// Growth pattern
internodeSpacing: 3 + Math.floor(Math.random() * 4), // 3-6
budGrowthLimit: 8 + Math.floor(Math.random() * 8), // 8-15
leafNodePattern: [1, 1, 0, 1], // Default phyllotaxis
// Branching pattern
branchingNodes: [5, 8], // Which nodes branch
branchAngle: 45, // Angle of branches
// Timing & thresholds
leafDelay: 2, // Ticks before leaf buds activate
floweringHeight: 8, // Height to start flowering
energyThreshold: 8, // Energy needed for growth
// Survival traits
droughtTolerance: 0.5 + Math.random() * 0.5,
coldTolerance: 0.5 + Math.random() * 0.5,
};
}
inheritFromParent(parent) {
this.genes = JSON.parse(JSON.stringify(parent.genes));
this.mutate();
}
combineParents(parentA, parentB) {
this.genes = {};
Object.keys(parentA.genes).forEach((key) => {
this.genes[key] =
Math.random() < 0.5 ? parentA.genes[key] : parentB.genes[key];
});
this.mutate();
}
mutate() {
if (Math.random() < CONSTANTS.GENETICS.MUTATION_RATE) {
const keys = Object.keys(this.genes);
const mutKey = keys[Math.floor(Math.random() * keys.length)];
if (typeof this.genes[mutKey] === "number") {
const change =
(Math.random() - 0.5) * 2 * CONSTANTS.GENETICS.MUTATION_STRENGTH;
this.genes[mutKey] = Math.max(1, this.genes[mutKey] * (1 + change));
}
}
}
calculateFitness() {
// Fitness based on balanced traits
const spacing = this.genes.internodeSpacing;
const height = this.genes.budGrowthLimit;
const energy = this.genes.energyThreshold;
// Prefer intermediate values for most traits
return (
10 -
Math.abs(spacing - 4) +
(15 - Math.abs(height - 12)) +
(10 - Math.abs(energy - 8))
);
}
getColor() {
const fitness = this.calculateFitness();
if (fitness > 30) return 0xffd700; // Gold
if (fitness > 25) return 0xffa500; // Orange
if (fitness > 20) return 0x32cd32; // Lime green
return 0x228b22; // Forest green
}
}
// === SECTION 4: PARTICLE CLASS ===
class Particle {
constructor(x, y, mode = Mode.WATER) {
this.pos = { x, y };
this.id = idCounter++;
this.mode = mode;
this.age = 0;
// Plant-specific properties
this.plantId = null;
this.genetics = null;
this.parent = null;
this.children = [];
this.hasAttemptedSprout = false; // Flag to prevent spam logging
this.hasAttemptedGrow = false; // Flag to prevent spam logging
this.hasLoggedBlocked = false; // Flag to prevent spam logging
this.hasLoggedGrowth = false; // Flag to prevent spam logging
this.hasLoggedStemCreation = false; // Flag to prevent spam logging
this.hasLoggedFirstRender = false; // Flag for first-time energy particle render
this.hasLoggedNoGenetics = false; // Flag to prevent spam logging
this.hasLoggedResourceCheck = false; // Flag to prevent spam logging
this.hasLoggedAbsorption = false; // Flag to prevent repeated logs for water absorption
// Movement properties (for flux particles)
this.isFalling = true;
this.fallingDirection = null;
// Always create sprite
this.sprite = new PIXI.Sprite(modeTextures[this.mode]);
this.sprite.x = Math.floor(x * scaleSize);
this.sprite.y = Math.floor(y * scaleSize);
this.sprite.scale.set(scaleSize, scaleSize);
app.stage.addChild(this.sprite);
// Log first-time energy particle creation
if (this.mode === Mode.ENERGY && !this.hasLoggedFirstRender) {
console.log(`β‘ Energy particle created at (${x}, ${y})`);
this.hasLoggedFirstRender = true;
}
// Initialize seed with stored energy (cotyledons) for bootstrap growth
if (this.mode === Mode.SEED) {
this.storedEnergy = 10; // Seeds start with 10 energy for initial growth
console.log(
`π° Seed created with ${this.storedEnergy} stored energy at (${x}, ${y})`
);
}
// Set in appropriate occupancy grid layer
if (this.isPlantPart()) {
occupancyGrid.setPlant(x, y, this);
}
}
isPlantPart() {
return [
Mode.SEED,
Mode.STEM,
Mode.LEAF,
Mode.BUD,
Mode.NODE,
Mode.FLOWER,
].includes(this.mode);
}
setMode(mode) {
if (this.mode !== mode) {
const oldMode = this.mode;
console.log(
`π MODE CHANGE: ${oldMode} β ${mode} at (${this.pos.x}, ${this.pos.y})`
);
this.mode = mode;
// Update sprite texture
if (this.sprite) {
this.sprite.texture = modeTextures[mode];
// Update sprite color based on genetics for plant parts
if (this.isPlantPart() && this.genetics) {
const color = this.genetics.getColor();
this.sprite.tint = color;
}
}
// Handle occupancy grid changes
if (this.isPlantPart() && !this.wasPlantPart(oldMode)) {
occupancyGrid.setPlant(this.pos.x, this.pos.y, this);
} else if (!this.isPlantPart() && this.wasPlantPart(oldMode)) {
occupancyGrid.removePlant(this.pos.x, this.pos.y);
}
}
}
wasPlantPart(mode) {
return [
Mode.SEED,
Mode.STEM,
Mode.LEAF,
Mode.BUD,
Mode.NODE,
Mode.FLOWER,
].includes(mode);
}
update() {
this.age++;
switch (this.mode) {
case Mode.WATER:
this.updateWater();
break;
case Mode.VAPOR:
this.updateVapor();
break;
case Mode.ENERGY:
this.updateEnergy();
break;
case Mode.SEED:
this.updateSeed();
break;
case Mode.BUD:
this.updateBud();
break;
case Mode.STEM:
case Mode.LEAF:
case Mode.NODE:
this.updatePlantPart();
break;
case Mode.FLOWER:
this.updateFlower();
break;
}
}
// === PARTICLE MOVEMENT METHODS ===
moveRel(x, y) {
// Handle vertical torus wrapping
let newY = this.pos.y + y;
if (newY < 0) {
newY = rows - 1;
} else if (newY >= rows) {
newY = 0;
}
// Handle horizontal bounds (closed edges)
let newX = this.pos.x + x;
if (newX < 0 || newX >= cols) {
return false; // Can't move outside horizontal bounds
}
// Update position
this.pos.x = newX;
this.pos.y = newY;
// Update sprite position
if (this.sprite) {
this.sprite.x = Math.floor(this.pos.x * scaleSize);
this.sprite.y = Math.floor(this.pos.y * scaleSize);
}
// Update occupancy grid for plant parts
if (this.isPlantPart()) {
occupancyGrid.removePlant(this.pos.x - x, this.pos.y - y);
occupancyGrid.setPlant(this.pos.x, this.pos.y, this);
}
return true;
}
// === FLUX PARTICLE UPDATES ===
updateWater() {
// Water physics with vertical torus topology
if (this.isFalling) {
// 1% chance to try diagonal movement first to help water find seeds
if (Math.random() < 0.01) {
const diagonalChoice = Math.random() < 0.5 ? "left" : "right";
if (diagonalChoice === "left" && this.moveRel(-1, 1)) {
this.fallingDirection = "left";
return; // Successfully moved diagonally
} else if (diagonalChoice === "right" && this.moveRel(1, 1)) {
this.fallingDirection = "right";
return; // Successfully moved diagonally
}
// If diagonal failed, continue with normal logic below
}
// Try to move down first
if (this.moveRel(0, 1)) {
this.fallingDirection = null;
} else {
// If can't move down, try diagonal
if (this.fallingDirection === null) {
this.fallingDirection = Math.random() < 0.5 ? "left" : "right";
}
if (this.fallingDirection === "left") {
if (!this.moveRel(-1, 1)) {
if (!this.moveRel(-1, 0)) {
this.fallingDirection = "right";
}
}
} else {
if (!this.moveRel(1, 1)) {
if (!this.moveRel(1, 0)) {
this.fallingDirection = "left";
}
}
}
}
}
// Check if water is in same space as plant - seeds and all plant parts can absorb water
const plant = occupancyGrid.getPlant(this.pos.x, this.pos.y);
if (plant && plant.plantId) {
// Only log if this is the first water particle absorbed by this plant cell
const alreadyHasWater = occupancyGrid.hasWater(this.pos.x, this.pos.y);
if (!alreadyHasWater) {
console.log(
`π§ Water absorbed by ${plant.mode} at (${this.pos.x}, ${this.pos.y})`
);
}
// Remove water particle and add to water layer (all plant parts can only hold 1 water)
occupancyGrid.setWater(this.pos.x, this.pos.y, this);
this.sprite.visible = false; // Hide the particle sprite
this.isFalling = false;
// Start local water flow from this cell
plant.tryFlowWater();
}
}
updateEnergy() {
// Energy can be absorbed by LEAF particles (photosynthesis) and SEED particles (cotyledons)
const plant = occupancyGrid.getPlant(this.pos.x, this.pos.y);
if (
plant &&
plant.plantId &&
(plant.mode === Mode.LEAF || plant.mode === Mode.SEED)
) {
const hasEnergyAlready = occupancyGrid.hasEnergy(
this.pos.x,
this.pos.y
);
const hasWater = occupancyGrid.hasWater(this.pos.x, this.pos.y);
// Seeds can store multiple energy (cotyledons), other plant parts can only store 1
const canAbsorbEnergy =
plant.mode === Mode.SEED
? !plant.storedEnergy || plant.storedEnergy < 10 // Seeds can store up to 10 energy
: !hasEnergyAlready && hasWater; // Leaves need water for photosynthesis
if (canAbsorbEnergy) {
if (plant.mode === Mode.SEED) {
// SEED: Store multiple energy particles (cotyledons)
console.log(
`β‘ Energy stored in seed at (${this.pos.x}, ${this.pos.y})`
);
// Initialize stored energy if needed
if (!plant.storedEnergy) plant.storedEnergy = 0;
plant.storedEnergy++;
// Destroy the energy particle (it's now stored in the seed)
this.destroy();
} else if (plant.mode === Mode.LEAF) {
// LEAF: Photosynthesis with respiration
console.log(
`β‘ Energy absorbed by ${plant.mode} at (${this.pos.x}, ${this.pos.y}) - creating vapor`
);
// RESPIRATION: Energy absorption consumes water
const waterParticle = occupancyGrid.getWater(
this.pos.x,
this.pos.y
);
if (waterParticle) {
// Remove water and create vapor
occupancyGrid.setWater(this.pos.x, this.pos.y, null);
// Create vapor particle
const vapor = new Particle(this.pos.x, this.pos.y, Mode.VAPOR);
particles.push(vapor);
// Remove water particle from the simulation
if (waterParticle && waterParticle.destroy) {
waterParticle.destroy();
}
}
// Move energy particle to plant cell
occupancyGrid.setEnergy(this.pos.x, this.pos.y, this);
this.sprite.visible = false; // Hide the particle sprite
// Try to flow energy through the plant
const flowSuccessful = plant.tryFlowEnergy();
// If energy couldn't flow (plant saturated), mark this energy for twinkling
if (!flowSuccessful) {
this.twinkleCountdown = 5; // Will fade out over 5 frames
console.log(
`β¨ Plant saturated - energy will twinkle out at (${this.pos.x}, ${this.pos.y})`
);
}
}
}
} else {
// Energy particle not on a leaf - check for fade-out due to saturation
if (this.twinkleCountdown !== undefined) {
this.twinkleCountdown--;
// Create twinkling effect by changing opacity
if (this.sprite) {
this.sprite.alpha = Math.max(0.1, this.twinkleCountdown / 5);
}
// Fade out completely
if (this.twinkleCountdown <= 0) {
console.log(
`β¨ Energy particle twinkled out at (${this.pos.x}, ${this.pos.y})`
);
this.destroy();
}
} else {
// Regular energy particle aging - fade out if too old and not absorbed
if (this.age > 100) {
console.log(
`ποΈ Old energy particle despawning at (${this.pos.x}, ${this.pos.y})`
);
this.destroy();
}
}
}
}
// === LOCAL SATURATION FLOW SYSTEM ===
tryFlowEnergy(visitedCells = new Set()) {
// Prevent infinite recursion
const cellKey = `${this.pos.x},${this.pos.y}`;
if (visitedCells.has(cellKey)) return false;
visitedCells.add(cellKey);
// Only flow if this cell has energy
if (!occupancyGrid.hasEnergy(this.pos.x, this.pos.y)) return false;
// Get the energy particle at this position
const energyParticle = occupancyGrid.getEnergy(this.pos.x, this.pos.y);
// Energy flows DOWNWARD: from leaves to seed (extremities to root)
const neighbors = this.getEnergyFlowNeighbors();
for (const neighbor of neighbors) {
if (!occupancyGrid.hasEnergy(neighbor.x, neighbor.y)) {
// Found empty space - flow energy there
occupancyGrid.setEnergy(this.pos.x, this.pos.y, null);
occupancyGrid.setEnergy(neighbor.x, neighbor.y, energyParticle);
console.log(
`β‘ Energy flowed DOWN from (${this.pos.x}, ${this.pos.y}) to (${neighbor.x}, ${neighbor.y})`
);
// Try to continue flowing from the new position
neighbor.plant.tryFlowEnergy(visitedCells);
return true;
} else {
// Neighbor has energy - ask it to try shifting first
if (neighbor.plant.tryFlowEnergy(visitedCells)) {
// Neighbor made space - now we can flow there
occupancyGrid.setEnergy(this.pos.x, this.pos.y, null);
occupancyGrid.setEnergy(neighbor.x, neighbor.y, energyParticle);
console.log(
`β‘ Energy flowed DOWN from (${this.pos.x}, ${this.pos.y}) to (${neighbor.x}, ${neighbor.y}) after neighbor shifted`
);
return true;
}
}
}
return false; // No flow possible - locally saturated
}
tryFlowWater(visitedCells = new Set()) {
// Prevent infinite recursion
const cellKey = `${this.pos.x},${this.pos.y}`;
if (visitedCells.has(cellKey)) return false;
visitedCells.add(cellKey);
// Only flow if this cell has water
if (!occupancyGrid.hasWater(this.pos.x, this.pos.y)) return false;
// Get the water particle at this position
const waterParticle = occupancyGrid.getWater(this.pos.x, this.pos.y);
// Water flows UPWARD: from parent to children only (seed pushes water up to extremities)
const neighbors = this.getWaterFlowNeighbors();
for (const neighbor of neighbors) {
if (!occupancyGrid.hasWater(neighbor.x, neighbor.y)) {
// Found empty space - flow water there
occupancyGrid.setWater(this.pos.x, this.pos.y, null);
occupancyGrid.setWater(neighbor.x, neighbor.y, waterParticle);
console.log(
`π§ Water flowed UP from (${this.pos.x}, ${this.pos.y}) to (${neighbor.x}, ${neighbor.y})`
);
// Try to continue flowing from the new position
neighbor.plant.tryFlowWater(visitedCells);
return true;
} else {
// Neighbor has water - ask it to try shifting first
if (neighbor.plant.tryFlowWater(visitedCells)) {
// Neighbor made space - now we can flow there
occupancyGrid.setWater(this.pos.x, this.pos.y, null);
occupancyGrid.setWater(neighbor.x, neighbor.y, waterParticle);
console.log(
`π§ Water flowed UP from (${this.pos.x}, ${this.pos.y}) to (${neighbor.x}, ${neighbor.y}) after neighbor shifted`
);
return true;
}
}
}
return false; // No flow possible - locally saturated
}
getWaterFlowNeighbors() {
// Water flows UPWARD: only to children (from root to extremities)
let neighbors = [];
// Add children (if any) - water flows UP
if (this.children) {
for (const child of this.children) {
if (child.isPlantPart && child.isPlantPart()) {
neighbors.push({
x: child.pos.x,
y: child.pos.y,
plant: child,
});
}
}
}
// Add adjacent plant cells from same plant that are higher (lower y value)
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
if (dx === 0 && dy === 0) continue;
const nx = this.pos.x + dx;
const ny = this.pos.y + dy;
if (nx >= 0 && nx < cols && ny >= 0 && ny < rows && ny < this.pos.y) {
// Only flow to higher positions
const plant = occupancyGrid.getPlant(nx, ny);
if (plant && plant.plantId === this.plantId) {
// Only add if not already in neighbors (avoid duplicates)
const exists = neighbors.some((n) => n.x === nx && n.y === ny);
if (!exists) {
neighbors.push({ x: nx, y: ny, plant });
}
}
}
}
}
return neighbors;
}
getEnergyFlowNeighbors() {
// Energy flows DOWNWARD: only to parent (from extremities to root)
let neighbors = [];
// Add parent (if exists) - energy flows DOWN
if (this.parent && this.parent.isPlantPart && this.parent.isPlantPart()) {
neighbors.push({
x: this.parent.pos.x,
y: this.parent.pos.y,
plant: this.parent,
});
}
// Add adjacent plant cells from same plant that are lower (higher y value)
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
if (dx === 0 && dy === 0) continue;
const nx = this.pos.x + dx;
const ny = this.pos.y + dy;
if (nx >= 0 && nx < cols && ny >= 0 && ny < rows && ny > this.pos.y) {
// Only flow to lower positions
const plant = occupancyGrid.getPlant(nx, ny);
if (plant && plant.plantId === this.plantId) {
// Only add if not already in neighbors (avoid duplicates)
const exists = neighbors.some((n) => n.x === nx && n.y === ny);
if (!exists) {
neighbors.push({ x: nx, y: ny, plant });
}
}
}
}
}
return neighbors;
}
updateVapor() {
// Vapor movement with upward bias
const directions = [
{ dx: -1, dy: -1 },
{ dx: 0, dy: -1 },
{ dx: 1, dy: -1 },
{ dx: 0, dy: -1 }, // Extra upward bias
{ dx: -1, dy: 0 },
{ dx: 0, dy: 0 },
{ dx: 1, dy: 0 },
{ dx: -1, dy: 1 },
{ dx: 0, dy: 1 },
{ dx: 1, dy: 1 },
];
const dir = directions[Math.floor(Math.random() * directions.length)];
this.moveRel(dir.dx, dir.dy);
// Condensation at top row
if (this.pos.y === 0) {
// Convert back to water
const water = new Particle(this.pos.x, this.pos.y, Mode.WATER);
particles.push(water);
this.destroy();
}
}
// === PLANT UPDATES ===
updateSeed() {
// Seed logic - try to sprout when it has enough energy
// Simple sprouting condition - just try to sprout after some time
if (this.age > 100 && !this.hasAttemptedSprout) {
console.log(
`π± Seed at (${this.pos.x}, ${this.pos.y}) attempting to sprout`
);
this.hasAttemptedSprout = true;
this.sprout();
}
}
updateBud() {
// Bud growth logic
if (!this.genetics) {
if (!this.hasLoggedNoGenetics) {
console.log(
`β Bud at (${this.pos.x}, ${this.pos.y}) has no genetics in update`
);
this.hasLoggedNoGenetics = true;
}
return;
}
// If this bud has been converted to a flower, stop trying to grow
if (this.mode !== Mode.BUD) {
return;
}
const hasEnergy = occupancyGrid.hasEnergy(this.pos.x, this.pos.y);
const hasWater = occupancyGrid.hasWater(this.pos.x, this.pos.y);
if (!this.hasLoggedResourceCheck) {
console.log(
`π§β‘ Bud at (${this.pos.x}, ${this.pos.y}) resource check: water=${hasWater}, energy=${hasEnergy}`
);
this.hasLoggedResourceCheck = true;
}
// Periodic resource status updates (every 200 frames)
if (frame % 200 === 0) {
console.log(
`π Bud at (${this.pos.x}, ${this.pos.y}) status: water=${hasWater}, energy=${hasEnergy}`
);
}
// If bud has water but no energy, try to request energy from parent
if (hasWater && !hasEnergy && this.parent) {
if (this.requestEnergyFromParent()) {
console.log(
`π Bud at (${this.pos.x}, ${this.pos.y}) successfully requested energy from parent`
);
}
}
// Check if bud has energy and water to grow
const hasEnergyNow = occupancyGrid.hasEnergy(this.pos.x, this.pos.y);
if (hasEnergyNow && hasWater) {
if (!this.hasAttemptedGrow) {
console.log(
`π± Bud at (${this.pos.x}, ${this.pos.y}) has energy + water, attempting growth`
);
this.hasAttemptedGrow = true;
}
this.grow();
}
}
requestEnergyFromParent() {
// Bud requests energy from its parent (seed or stem)
if (!this.parent) return false;
// Check if parent is a seed with stored energy
if (this.parent.mode === Mode.SEED && this.parent.storedEnergy > 0) {
// Transfer 1 energy from seed to bud
this.parent.storedEnergy--;
// Create energy particle at bud position
const energyParticle = new Particle(
this.pos.x,
this.pos.y,
Mode.ENERGY
);
occupancyGrid.setEnergy(this.pos.x, this.pos.y, energyParticle);
energyParticle.sprite.visible = false; // Hide since it's in plant cell
particles.push(energyParticle);
console.log(
`π Energy transferred from seed (${this.parent.pos.x}, ${this.parent.pos.y}) to bud (${this.pos.x}, ${this.pos.y}). Seed energy remaining: ${this.parent.storedEnergy}`
);
return true;
}
// Check if parent has energy in its cell and can pass it along
if (occupancyGrid.hasEnergy(this.parent.pos.x, this.parent.pos.y)) {
const parentEnergy = occupancyGrid.getEnergy(
this.parent.pos.x,
this.parent.pos.y
);
if (parentEnergy) {
// Move energy from parent to bud
occupancyGrid.setEnergy(this.parent.pos.x, this.parent.pos.y, null);
occupancyGrid.setEnergy(this.pos.x, this.pos.y, parentEnergy);
console.log(
`π Energy transferred from parent (${this.parent.pos.x}, ${this.parent.pos.y}) to bud (${this.pos.x}, ${this.pos.y})`
);
return true;