-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtide-pool.html
More file actions
4315 lines (3741 loc) · 194 KB
/
tide-pool.html
File metadata and controls
4315 lines (3741 loc) · 194 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, user-scalable=no">
<link rel="manifest" href="manifest.webmanifest">
<meta name="theme-color" content="#1a3a4a">
<title>Tide Pool</title>
<meta name="description" content="A peaceful tide pool ecosystem simulation. Watch crabs, fish, anemones, and other creatures live their lives as the tides ebb and flow.">
<link rel="icon" href="assets/appicons/favicon.ico">
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body {
width: 100%;
height: 100%;
overflow: hidden;
background: #1a3a4a;
font-family: system-ui, -apple-system, sans-serif;
}
#pool-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
#pool-canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#pool-canvas:active {
cursor: grabbing;
}
/* Overlay UI */
#overlay-ui {
position: fixed;
top: 0;
left: 0;
right: 0;
padding: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) 12px max(12px, env(safe-area-inset-left));
display: flex;
justify-content: space-between;
align-items: flex-start;
pointer-events: none;
z-index: 10;
}
#title {
color: rgba(255,255,255,0.9);
text-shadow: 0 2px 8px rgba(0,0,0,0.5);
font-size: 1.4rem;
font-weight: 600;
}
#info-bar {
display: flex;
flex-wrap: wrap;
gap: 0.8rem;
color: rgba(255,255,255,0.85);
font-size: 0.85rem;
text-shadow: 0 1px 4px rgba(0,0,0,0.5);
}
.info-item {
display: flex;
align-items: center;
gap: 0.3rem;
background: rgba(0,0,0,0.2);
padding: 0.3rem 0.6rem;
border-radius: 1rem;
backdrop-filter: blur(4px);
}
@media (max-width: 600px) {
#overlay-ui {
flex-direction: column;
gap: 0.5rem;
}
#info-bar {
font-size: 0.75rem;
}
}
/* Toggle switch */
.toggle-item {
display: flex;
align-items: center;
gap: 0.4rem;
background: rgba(0,0,0,0.2);
padding: 0.3rem 0.6rem;
border-radius: 1rem;
backdrop-filter: blur(4px);
pointer-events: auto;
cursor: pointer;
user-select: none;
}
.toggle-switch {
position: relative;
width: 32px;
height: 18px;
background: rgba(255,255,255,0.3);
border-radius: 9px;
transition: background 0.2s;
}
.toggle-switch::after {
content: '';
position: absolute;
top: 2px;
left: 2px;
width: 14px;
height: 14px;
background: white;
border-radius: 50%;
transition: transform 0.2s;
box-shadow: 0 1px 3px rgba(0,0,0,0.3);
}
.toggle-item.active .toggle-switch {
background: rgba(100,200,255,0.7);
}
.toggle-item.active .toggle-switch::after {
transform: translateX(14px);
}
</style>
</head>
<body>
<div id="pool-container">
<canvas id="pool-canvas"></canvas>
</div>
<div id="overlay-ui">
<div id="title">🌊 Tide Pool</div>
<div id="info-bar">
<span class="info-item">🌙 <span id="moon-phase">Full Moon</span></span>
<span class="info-item">🌊 <span id="tide-state">High Tide</span></span>
<span class="info-item">☀️ <span id="time-of-day">Day</span></span>
<span class="toggle-item active" id="thought-toggle" title="Toggle thought bubbles">
💭 <span class="toggle-switch"></span>
</span>
</div>
</div>
<script>
// ═══════════════════════════════════════════════════════════════════════════
// TIDE POOL - An ecosystem simulation
// ═══════════════════════════════════════════════════════════════════════════
//
// Architecture: Entity-Component-System (lite)
// - Systems update in order, each receives deltaTime
// - Entities are data bags with components
// - Clean separation of concerns for easy expansion
//
// ═══════════════════════════════════════════════════════════════════════════
const canvas = document.getElementById('pool-canvas');
const ctx = canvas.getContext('2d');
// Offscreen canvas for soft caustic effects
const causticCanvas = document.createElement('canvas');
const causticCtx = causticCanvas.getContext('2d');
// ═══════════════════════════════════════════════════════════════════════════
// CONFIGURATION
// ═══════════════════════════════════════════════════════════════════════════
const CONFIG = {
targetFPS: 20,
msPerFrame: 1000 / 20,
// World dimensions (logical coordinates, scaled to fit screen)
width: 800,
height: 600,
// Physics
physics: {
gravity: 600, // pixels per second^2 (faster fall)
waterDrag: 0.92, // velocity multiplier in water
airDrag: 0.995, // velocity multiplier in air (very little drag)
buoyancy: 300, // upward force in water
floorY: 560, // Bottom of pool (sand floor)
leftWall: 35, // Left rock boundary
rightWall: 765, // Right rock boundary
},
// Oriented bounding-box overlap approximation for creature bodies.
// Uses each entity's rendering dimensions to build rotated OBBs and
// applies a simple SAT test over the two boxes' axes. This is an
// inexpensive, robust approximation of ellipse/oval overlap for game use.
obbOverlap(entityA, entityB) {
if (!entityA || !entityB) return false;
// Helper to build an OBB from an entity
function buildOBB(e) {
const cx = e.position.x;
const cy = e.position.y;
// Default extents and rotation
let rx = 20, ry = 10, rot = 0;
if (e.type === 'crab' && e.rig) {
rx = (e.rig.bodyWidth || 40) * 0.5;
ry = (e.rig.bodyHeight || 24) * 0.5;
rot = 0; // crab body doesn't tilt much
} else if (e.type === 'fish') {
const sz = e.size || 1;
rx = 18 * sz;
ry = 8 * sz;
const facing = e.behavior?.facingLeft ? -1 : 1;
const moveAngle = Math.atan2((e.velocity?.y) || 0, Math.abs((e.velocity?.x) || 0)) * facing;
rot = moveAngle * 0.3; // match visual tilt used in rendering
// Compute body center offset (entity.position is at the fish head).
// Transform local center (-bodyLength/2, 0) by scale(facing,1) then rotate(rot)
if (e.rig && e.rig.segments) {
const bodyLen = e.rig.segments.reduce((s, seg) => s + (seg.length || 0), 0);
const localCx = -bodyLen * 0.5;
const sx = facing * localCx;
const sy = 0;
const cc = Math.cos(rot), ss = Math.sin(rot);
const worldCx = cx + (cc * sx - ss * sy);
const worldCy = cy + (ss * sx + cc * sy);
return { cx: worldCx, cy: worldCy, ux: { x: Math.cos(rot) * facing, y: Math.sin(rot) * facing }, vx: { x: -Math.sin(rot), y: Math.cos(rot) }, rx, ry };
}
} else if (e.type === 'snail') {
const sz = e.size || 1;
rx = 18 * sz;
ry = 6 * sz;
rot = 0;
} else {
const sz = e.size || 1;
rx = 16 * sz;
ry = 8 * sz;
rot = 0;
}
const ux = { x: Math.cos(rot), y: Math.sin(rot) };
const vx = { x: -Math.sin(rot), y: Math.cos(rot) };
return { cx, cy, ux, vx, rx, ry };
}
const A = buildOBB(entityA);
const B = buildOBB(entityB);
// Axes to test: A.ux, A.vx, B.ux, B.vx
const axes = [A.ux, A.vx, B.ux, B.vx];
// Center distance
const dx = B.cx - A.cx;
const dy = B.cy - A.cy;
// Quick rejection using bounding circles (fast guard against distant false positives)
const approxA = Math.hypot(A.rx, A.ry);
const approxB = Math.hypot(B.rx, B.ry);
const centerDist = Math.hypot(dx, dy);
if (centerDist > (approxA + approxB) * 1.25) return false;
for (const axis of axes) {
// Normalize axis (they should already be unit, but be safe)
const len = Math.hypot(axis.x, axis.y) || 1;
const ax = axis.x / len;
const ay = axis.y / len;
// Project center distance onto axis
const proj = Math.abs(dx * ax + dy * ay);
// Radius of projection for A
const rA = Math.abs(A.rx * (A.ux.x * ax + A.ux.y * ay)) + Math.abs(A.ry * (A.vx.x * ax + A.vx.y * ay));
const rB = Math.abs(B.rx * (B.ux.x * ax + B.ux.y * ay)) + Math.abs(B.ry * (B.vx.x * ax + B.vx.y * ay));
if (proj > rA + rB) return false; // Separating axis found
}
return true; // No separation found
},
// OBB overlap with optional inflation factors for each entity's radii.
obbOverlapInflated(entityA, entityB, inflateA = 1, inflateB = 1) {
if (!entityA || !entityB) return false;
// Inline buildOBB to allow easy inflation
function buildOBB(e, inflate) {
const cx = e.position.x;
const cy = e.position.y;
let rx = 20, ry = 10, rot = 0;
if (e.type === 'crab' && e.rig) {
rx = (e.rig.bodyWidth || 40) * 0.5 * 0.9 * inflate; // slight reduction baseline
ry = (e.rig.bodyHeight || 24) * 0.5 * 0.9 * inflate;
rot = 0;
} else if (e.type === 'fish') {
const sz = e.size || 1;
rx = 18 * sz * inflate;
ry = 8 * sz * inflate;
const facing = e.behavior?.facingLeft ? -1 : 1;
const moveAngle = Math.atan2((e.velocity?.y) || 0, Math.abs((e.velocity?.x) || 0)) * facing;
rot = moveAngle * 0.3;
if (e.rig && e.rig.segments) {
const bodyLen = e.rig.segments.reduce((s, seg) => s + (seg.length || 0), 0);
const localCx = -bodyLen * 0.5;
const sx = facing * localCx;
const sy = 0;
const cc = Math.cos(rot), ss = Math.sin(rot);
const worldCx = cx + (cc * sx - ss * sy);
const worldCy = cy + (ss * sx + cc * sy);
const ux = { x: Math.cos(rot) * facing, y: Math.sin(rot) * facing };
const vx = { x: -Math.sin(rot), y: Math.cos(rot) };
return { cx: worldCx, cy: worldCy, ux, vx, rx, ry };
}
} else if (e.type === 'snail') {
const sz = e.size || 1;
rx = 18 * sz * inflate;
ry = 6 * sz * inflate;
rot = 0;
} else {
const sz = e.size || 1;
rx = 16 * sz * inflate;
ry = 8 * sz * inflate;
rot = 0;
}
const ux = { x: Math.cos(rot), y: Math.sin(rot) };
const vx = { x: -Math.sin(rot), y: Math.cos(rot) };
return { cx, cy, ux, vx, rx, ry };
}
const A = buildOBB(entityA, inflateA);
const B = buildOBB(entityB, inflateB);
// Quick rejection using bounding circles
const dx = B.cx - A.cx;
const dy = B.cy - A.cy;
const approxA = Math.hypot(A.rx, A.ry);
const approxB = Math.hypot(B.rx, B.ry);
const centerDist = Math.hypot(dx, dy);
if (centerDist > (approxA + approxB) * 1.25) return false;
const axes = [A.ux, A.vx, B.ux, B.vx];
for (const axis of axes) {
const len = Math.hypot(axis.x, axis.y) || 1;
const ax = axis.x / len;
const ay = axis.y / len;
const proj = Math.abs(dx * ax + dy * ay);
const rA = Math.abs(A.rx * (A.ux.x * ax + A.ux.y * ay)) + Math.abs(A.ry * (A.vx.x * ax + A.vx.y * ay));
const rB = Math.abs(B.rx * (B.ux.x * ax + B.ux.y * ay)) + Math.abs(B.ry * (B.vx.x * ax + B.vx.y * ay));
if (proj > rA + rB) return false;
}
return true;
},
// Return OBB parameters for an entity: center, rx, ry, and rotation (radians)
getOBB(entity) {
if (!entity) return null;
let rx = 20, ry = 10, rot = 0;
if (entity.type === 'crab' && entity.rig) {
rx = (entity.rig.bodyWidth || 40) * 0.5;
ry = (entity.rig.bodyHeight || 24) * 0.5;
rot = 0;
// Slightly reduce crab OBB to avoid leg/claw reach causing body overlap
rx *= 0.9;
ry *= 0.9;
// Inflate when snapping for visual tuning happens in draw logic
} else if (entity.type === 'fish') {
const sz = entity.size || 1;
rx = 18 * sz;
ry = 8 * sz;
const facing = entity.behavior?.facingLeft ? -1 : 1;
const moveAngle = Math.atan2((entity.velocity?.y) || 0, Math.abs((entity.velocity?.x) || 0)) * facing;
rot = moveAngle * 0.3;
// Move OBB center from head to body center (approx)
if (entity.rig && entity.rig.segments) {
const bodyLen = entity.rig.segments.reduce((s, seg) => s + (seg.length || 0), 0);
const localCx = -bodyLen * 0.5;
const sx = facing * localCx;
const sy = 0;
const cc = Math.cos(rot), ss = Math.sin(rot);
const worldCx = entity.position.x + (cc * sx - ss * sy);
const worldCy = entity.position.y + (ss * sx + cc * sy);
return { cx: worldCx, cy: worldCy, rx, ry, rot };
}
} else if (entity.type === 'snail') {
const sz = entity.size || 1;
rx = 18 * sz;
ry = 6 * sz;
rot = 0;
} else {
const sz = entity.size || 1;
rx = 16 * sz;
ry = 8 * sz;
rot = 0;
}
return { cx: entity.position.x, cy: entity.position.y, rx, ry, rot };
},
// Time cycles (in real seconds)
cycles: {
dayLength: 120, // 2 minutes = 1 full day
tideLength: 60, // 1 minute = tide in/out cycle
moonCycleDays: 8, // 8 game-days = full moon cycle
},
// Water levels (as fraction of pool height)
water: {
minLevel: 0.35, // low tide
maxLevel: 0.80, // high tide
springTideBonus: 0.08, // extra height during full/new moon
},
};
// ═══════════════════════════════════════════════════════════════════════════
// RESPONSIVE CANVAS SIZING
// ═══════════════════════════════════════════════════════════════════════════
let scale = 1;
let offsetX = 0;
let offsetY = 0;
function resizeCanvas() {
const container = document.getElementById('pool-container');
const screenW = container.clientWidth;
const screenH = container.clientHeight;
// Set canvas to screen size
canvas.width = screenW;
canvas.height = screenH;
// Expand game world to fill screen (no letterboxing!)
// Use a base scale, then expand the logical dimensions to fill
const baseHeight = 600; // Minimum logical height
const aspectRatio = screenW / screenH;
// Scale based on height to keep consistent vertical gameplay
scale = screenH / baseHeight;
// Expand logical width to fill horizontal space
CONFIG.width = screenW / scale;
CONFIG.height = screenH / scale;
// Update physics boundaries to match new dimensions
CONFIG.physics.floorY = CONFIG.height - 40;
CONFIG.physics.leftWall = 35;
CONFIG.physics.rightWall = CONFIG.width - 35;
// No offset needed - game fills screen
offsetX = 0;
offsetY = 0;
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
// ═══════════════════════════════════════════════════════════════════════════
// GAME STATE
// ═══════════════════════════════════════════════════════════════════════════
const state = {
entities: [],
rocks: [], // Static rock geometry
gameTime: 0, // Total elapsed game time (seconds)
paused: false,
};
// Debug helper: toggleable via typing the sequence 'debug'
const debug = {
enabled: false,
keyBuffer: '',
};
// Keyboard handling: type 'debug' to toggle, and when in debug mode press 'h' to make creatures hungry
window.addEventListener('keydown', (e) => {
// Ignore if modifier keys pressed
if (e.ctrlKey || e.metaKey || e.altKey) return;
const k = e.key;
// In debug mode 'h' forces creatures to just-become-hungry
if ((k === 'h' || k === 'H') && debug.enabled) {
for (const entity of state.entities) {
if (!entity.ecosystem) continue;
const eco = entity.ecosystem;
// Crabs require a higher threshold (~67%)
if (entity.type === 'crab') {
eco.hunger = eco.maxHunger * 0.68;
} else {
// Fish/snail/etc use ~50%
eco.hunger = eco.maxHunger * 0.51;
}
// Reset per-entity eat cooldowns so debug forces re-eat availability
eco.fishEatenToday = 0;
eco.recentEatTimer = 0;
if (entity.behavior) {
entity.behavior.eatTimer = 0;
entity.behavior.snapCooldown = 0;
entity.behavior.snapActive = 0;
}
// Trigger a hungry thought bubble where available
if (thoughtBubbleSystem && thoughtBubbleSystem.showThought) {
thoughtBubbleSystem.showThought(entity, 'hungry');
}
}
console.log('🛠️ Debug: set creatures to hungry levels and cleared eat cooldowns');
return; // handled
}
// Capture alphabetic characters into buffer (for toggling debug)
if (k.length === 1 && /[a-zA-Z]/.test(k)) {
debug.keyBuffer += k.toLowerCase();
if (debug.keyBuffer.length > 10) debug.keyBuffer = debug.keyBuffer.slice(-10);
if (debug.keyBuffer.endsWith('debug')) {
debug.enabled = !debug.enabled;
debug.keyBuffer = '';
console.log('🛠️ Debug mode', debug.enabled ? 'ON' : 'OFF');
}
return;
}
});
// ═══════════════════════════════════════════════════════════════════════════
// EVENT BUS - Decoupled communication between systems
// ═══════════════════════════════════════════════════════════════════════════
const eventBus = {
listeners: {},
on(event, callback) {
if (!this.listeners[event]) this.listeners[event] = [];
this.listeners[event].push(callback);
},
off(event, callback) {
if (!this.listeners[event]) return;
this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
},
emit(event, data) {
if (!this.listeners[event]) return;
this.listeners[event].forEach(cb => cb(data));
}
};
// ═══════════════════════════════════════════════════════════════════════════
// TIME SYSTEM - Tracks game time, day/night, moon phases
// ═══════════════════════════════════════════════════════════════════════════
const timeSystem = {
dayProgress: 0, // 0-1 through current day
moonPhase: 0, // 0-1 through moon cycle (0=new, 0.5=full)
isDay: true,
update(dt) {
state.gameTime += dt;
// TODO: Calculate day progress (0 = midnight, 0.5 = noon, 1 = midnight)
const prevDay = this.isDay;
this.dayProgress = (state.gameTime % CONFIG.cycles.dayLength) / CONFIG.cycles.dayLength;
this.isDay = this.dayProgress > 0.25 && this.dayProgress < 0.75;
// TODO: Calculate moon phase based on elapsed game-days
const gameDays = state.gameTime / CONFIG.cycles.dayLength;
this.moonPhase = (gameDays % CONFIG.cycles.moonCycleDays) / CONFIG.cycles.moonCycleDays;
// Emit events on state changes
if (prevDay !== this.isDay) {
eventBus.emit(this.isDay ? 'dawn' : 'dusk', {});
}
},
getMoonPhaseName() {
// TODO: Return human-readable moon phase
const phase = this.moonPhase;
if (phase < 0.125) return 'New Moon';
if (phase < 0.25) return 'Waxing Crescent';
if (phase < 0.375) return 'First Quarter';
if (phase < 0.5) return 'Waxing Gibbous';
if (phase < 0.625) return 'Full Moon';
if (phase < 0.75) return 'Waning Gibbous';
if (phase < 0.875) return 'Last Quarter';
return 'Waning Crescent';
},
getTimeOfDayName() {
// TODO: Return human-readable time of day
const p = this.dayProgress;
if (p < 0.2) return 'Night';
if (p < 0.3) return 'Dawn';
if (p < 0.7) return 'Day';
if (p < 0.8) return 'Dusk';
return 'Night';
},
getSunAngle() {
// TODO: Return sun/moon angle for lighting calculations
return this.dayProgress * Math.PI * 2;
},
};
// ═══════════════════════════════════════════════════════════════════════════
// TIDE SYSTEM - Water level based on time and moon phase
// ═══════════════════════════════════════════════════════════════════════════
const tideSystem = {
level: 0.5, // Current water level (0-1)
direction: 1, // 1 = rising, -1 = falling
isHighTide: false,
isLowTide: false,
update(dt) {
// TODO: Calculate tide level from sine wave + moon influence
const tideProgress = (state.gameTime % CONFIG.cycles.tideLength) / CONFIG.cycles.tideLength;
const baseTide = (Math.sin(tideProgress * Math.PI * 2 - Math.PI / 2) + 1) / 2;
// Spring tides (higher highs, lower lows) during full/new moon
const moonInfluence = Math.cos(timeSystem.moonPhase * Math.PI * 2);
const springTide = moonInfluence * CONFIG.water.springTideBonus;
const prevLevel = this.level;
this.level = CONFIG.water.minLevel +
baseTide * (CONFIG.water.maxLevel - CONFIG.water.minLevel) +
springTide * baseTide;
this.level = Math.max(0, Math.min(1, this.level));
this.direction = this.level > prevLevel ? 1 : -1;
// Detect tide state changes
const wasHigh = this.isHighTide;
const wasLow = this.isLowTide;
this.isHighTide = this.level > 0.8;
this.isLowTide = this.level < 0.35;
if (this.isHighTide && !wasHigh) eventBus.emit('highTide', {});
if (this.isLowTide && !wasLow) eventBus.emit('lowTide', {});
},
getWaterY() {
// TODO: Return Y coordinate of water surface
return CONFIG.height * (1 - this.level);
},
getTideStateName() {
if (this.isHighTide) return 'High Tide';
if (this.isLowTide) return 'Low Tide';
return this.direction > 0 ? 'Rising' : 'Falling';
},
isUnderwater(y) {
return y > this.getWaterY();
},
getWaterDepthAt(y) {
// TODO: Return depth below surface (0 if above water)
const waterY = this.getWaterY();
return Math.max(0, y - waterY);
},
};
// ═══════════════════════════════════════════════════════════════════════════
// PHYSICS SYSTEM - Position, velocity, buoyancy, drag
// ═══════════════════════════════════════════════════════════════════════════
const physicsSystem = {
update(dt, entities) {
for (const entity of entities) {
if (!entity.physics) continue;
// Skip physics for grabbed entities
if (interactionSystem.grabbed === entity) continue;
const p = entity.physics;
const waterY = tideSystem.getWaterY();
const inWater = entity.position.y > waterY;
// Gravity (always applies)
p.velocity.y += CONFIG.physics.gravity * dt;
// Water physics only when submerged
if (inWater) {
// Buoyancy force (opposes gravity)
p.velocity.y -= CONFIG.physics.buoyancy * p.buoyancy * dt;
// Water drag (significant)
const waterDrag = Math.pow(CONFIG.physics.waterDrag, dt * 60);
p.velocity.x *= waterDrag;
p.velocity.y *= waterDrag;
} else {
// Air drag (minimal)
const airDrag = Math.pow(CONFIG.physics.airDrag, dt * 60);
p.velocity.x *= airDrag;
p.velocity.y *= airDrag;
}
// Update position
entity.position.x += p.velocity.x * dt;
entity.position.y += p.velocity.y * dt;
// Track if on ground for behavior system
p.onGround = false;
// Floor collision (sand bottom)
const floorY = CONFIG.physics.floorY;
if (entity.position.y > floorY) {
entity.position.y = floorY;
p.onGround = true;
if (p.velocity.y > 0) {
p.velocity.y = -p.velocity.y * 0.2; // Small bounce
}
p.velocity.x *= 0.9; // Ground friction
}
// Wall collisions (rock sides)
const leftWall = CONFIG.physics.leftWall;
const rightWall = CONFIG.physics.rightWall;
if (entity.position.x < leftWall) {
entity.position.x = leftWall;
p.velocity.x = Math.abs(p.velocity.x) * 0.5;
}
if (entity.position.x > rightWall) {
entity.position.x = rightWall;
p.velocity.x = -Math.abs(p.velocity.x) * 0.5;
}
// Ceiling (can't go above screen)
if (entity.position.y < 10) {
entity.position.y = 10;
p.velocity.y = Math.abs(p.velocity.y) * 0.3;
}
}
},
};
// ═══════════════════════════════════════════════════════════════════════════
// RIG SYSTEM - Skeletal animation and IK for creatures
// ═══════════════════════════════════════════════════════════════════════════
const rigSystem = {
update(dt, entities) {
for (const entity of entities) {
if (!entity.rig) continue;
if (entity.type === 'crab') {
this.updateCrabRig(entity, dt);
} else if (entity.type === 'seaweed') {
this.updateSeaweedRig(entity, dt);
} else if (entity.type === 'kelp') {
this.updateKelpRig(entity, dt);
} else if (entity.type === 'fish') {
this.updateFishRig(entity, dt);
}
// TODO: Tentacle writhing for octopus
}
},
updateCrabRig(entity, dt) {
const rig = entity.rig;
const physics = entity.physics;
const speed = Math.abs(physics.velocity.x) + Math.abs(physics.velocity.y) * 0.3;
// Advance walk cycle based on movement speed
if (speed > 5) {
rig.walkCycle += dt * speed * 0.15;
} else {
// Subtle idle animation
rig.walkCycle += dt * 0.5;
}
// Eye stalks have gentle idle movement
rig.eyeOffset = Math.sin(state.gameTime * 2) * 0.1;
// Update each leg's pose
for (const leg of rig.legs) {
const cycleOffset = rig.walkCycle + leg.phase;
const lift = Math.max(0, Math.sin(cycleOffset)); // Only lift, don't push down
const stride = Math.cos(cycleOffset);
// Leg segments respond to walk cycle
// Coxa rotates for reach
leg.segments[0].angle = stride * 0.3;
// Femur lifts
leg.segments[1].angle = -0.4 + lift * 0.6;
// Tibia curls to touch ground
leg.segments[2].angle = 0.8 - lift * 0.5;
}
// Claws have subtle open/close idle animation
for (const claw of rig.claws) {
claw.openAngle = 0.2 + Math.sin(state.gameTime * 1.5 + claw.side) * 0.1;
}
},
updateSeaweedRig(entity, dt) {
const rig = entity.rig;
const waterY = tideSystem.getWaterY();
const inWater = entity.position.y > waterY;
// Current direction based on tide
const currentStrength = inWater ? 1 : 0.1; // Much less movement out of water
const tideInfluence = tideSystem.direction * 0.3; // Sway with tide direction
for (let i = 0; i < rig.segments.length; i++) {
const seg = rig.segments[i];
const depthFactor = (i + 1) / rig.segments.length; // Tips move more
// Calculate target angle from water current and natural sway
const sway = Math.sin(state.gameTime * rig.swaySpeed + seg.phase + i * 0.5);
const current = tideInfluence * depthFactor;
seg.targetAngle = (sway * rig.swayAmount + current) * currentStrength * depthFactor;
// Smoothly interpolate toward target (springy motion)
const diff = seg.targetAngle - seg.angle;
seg.angle += diff * rig.stiffness * dt * 60;
// Add slight damping
seg.angle *= 0.995;
}
},
updateKelpRig(entity, dt) {
const rig = entity.rig;
const waterY = tideSystem.getWaterY();
const anchorX = entity.position.x;
const anchorY = entity.position.y;
// Initialize segment positions and velocities if needed
if (!rig.positions) {
rig.positions = [];
rig.velocities = [];
let px = anchorX;
let py = anchorY;
for (let i = 0; i < rig.segments.length; i++) {
py -= rig.segments[i].length; // Start pointing straight up
rig.positions.push({ x: px, y: py });
rig.velocities.push({ x: 0, y: 0 });
}
}
// Sync positions/velocities with segments (segments can be eaten!)
while (rig.positions.length > rig.segments.length) {
rig.positions.pop();
rig.velocities.pop();
}
// Add new positions if segments were added (regrowth)
while (rig.positions.length < rig.segments.length) {
const lastPos = rig.positions[rig.positions.length - 1] || { x: anchorX, y: anchorY };
const seg = rig.segments[rig.positions.length];
rig.positions.push({ x: lastPos.x, y: lastPos.y - seg.length });
rig.velocities.push({ x: 0, y: 0 });
}
const positions = rig.positions;
const velocities = rig.velocities;
const gravity = 120; // Gentle gravity
const waterDrag = 0.88;
const airDrag = 0.96;
const currentStrength = 20;
// Apply forces to each segment
for (let i = 0; i < positions.length; i++) {
const seg = rig.segments[i];
const pos = positions[i];
const vel = velocities[i];
const inWater = pos.y > waterY;
const depthInWater = pos.y - waterY;
const nearSurface = inWater && depthInWater < 40;
if (inWater) {
// Buoyancy - stronger base, but reduces as kelp extends upward
const heightAboveAnchor = anchorY - pos.y;
const maxHeight = rig.segments.length * 18; // Rough total length
const stretchFactor = Math.max(0.15, 1 - heightAboveAnchor / maxHeight * 0.7);
const buoyancy = 150 * stretchFactor; // Strong enough to lift, tapers off at top
vel.y -= buoyancy * dt;
// Water current - gentle sway
const currentSway = Math.sin(state.gameTime * rig.swaySpeed + seg.phase + i * 0.3);
vel.x += (tideSystem.direction * currentStrength + currentSway * 12) * dt;
// Water drag
vel.x *= waterDrag;
vel.y *= waterDrag;
// Near surface: spread outward
if (nearSurface) {
const offsetFromAnchor = pos.x - anchorX;
const spreadDir = offsetFromAnchor > 5 ? 1 : (offsetFromAnchor < -5 ? -1 : 0);
vel.x += spreadDir * 15 * dt;
// Also resist going above surface
if (pos.y < waterY + 5) {
vel.y += 50 * dt;
}
}
} else {
// Above water: gravity pulls down
vel.y += gravity * dt;
// Air drag
vel.x *= airDrag;
vel.y *= airDrag;
}
// Apply velocity
pos.x += vel.x * dt;
pos.y += vel.y * dt;
}
// Distance constraints - keep segments at fixed length from parent
// Run multiple iterations for stability
for (let iter = 0; iter < 3; iter++) {
let prevX = anchorX;
let prevY = anchorY;
for (let i = 0; i < positions.length; i++) {
const pos = positions[i];
const targetLength = rig.segments[i].length;
// Vector from parent to this segment
const dx = pos.x - prevX;
const dy = pos.y - prevY;
const dist = Math.sqrt(dx * dx + dy * dy) || 0.001;
// Normalize and set to target length
const nx = dx / dist;
const ny = dy / dist;
pos.x = prevX + nx * targetLength;
pos.y = prevY + ny * targetLength;
prevX = pos.x;
prevY = pos.y;
}
}
// Update angles for rendering (derived from positions)
let prevX = anchorX;
let prevY = anchorY;
for (let i = 0; i < rig.segments.length; i++) {
const pos = positions[i];
const dx = pos.x - prevX;
const dy = pos.y - prevY;
// Angle relative to straight up (-PI/2)
rig.segments[i].angle = Math.atan2(dy, dx) + Math.PI / 2;
// Adjust to be relative to previous segment's direction
if (i > 0) {
const prevAngle = rig.segments[i - 1].angle;
rig.segments[i].angle -= prevAngle;
}
prevX = pos.x;
prevY = pos.y;
}
},
updateFishRig(entity, dt) {
const rig = entity.rig;
const vel = entity.velocity;
const behavior = entity.behavior;
// Swimming animation - sinusoidal wave travels down the body
rig.swimPhase += rig.swimSpeed * dt * 10;
// Speed affects swim intensity
const speed = Math.sqrt(vel.x ** 2 + vel.y ** 2);
const swimIntensity = Math.min(1, speed / 100) * 0.8 + 0.2;
for (let i = 0; i < rig.segments.length; i++) {
const t = i / (rig.segments.length - 1);
// Wave travels from head to tail, amplitude increases toward tail
const waveOffset = t * 2.5;
const amplitude = t * rig.tailAmplitude * swimIntensity;
rig.segments[i].angle = Math.sin(rig.swimPhase - waveOffset) * amplitude;
}
},
};
// ═══════════════════════════════════════════════════════════════════════════
// BEHAVIOR SYSTEM - AI and state machines for creatures
// ═══════════════════════════════════════════════════════════════════════════
const behaviorSystem = {
update(dt, entities) {
for (const entity of entities) {
// Handle treasure chests separately (no behavior property)
if (entity.type === 'treasureChest') {
this.updateTreasureChest(entity, dt);
continue;
}
if (!entity.behavior) continue;
switch (entity.type) {
case 'crab':
this.updateCrabBehavior(entity, dt);
break;
case 'fish':
this.updateFishBehavior(entity, dt);
break;
case 'snail':
this.updateSnailBehavior(entity, dt);
break;
// TODO: case 'anemone': Sway, retract when touched
// TODO: case 'octopus': Hunt, hide, squeeze through gaps
}
}
},