Repository navigation
Expand file tree
/
Copy pathGame.fs
More file actions
1368 lines (1148 loc) · 52.8 KB
/
Copy pathGame.fs
File metadata and controls
1368 lines (1148 loc) · 52.8 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
/// THE FS HOCKEY LEAGUE — Game Logic
/// Entity update, AI, human input, collision, puck physics, scoring.
/// Taking influence from Solar Hockey by Galifir Developments (Harm Hanemaayer & John Remyn, 1990-1992)
module HockeyDemo.Game
open System
open HockeyDemo.Physics
// ─── Types ─────────────────────────────────────────────────────────────
type Entity =
{ mutable X: float<px>
mutable Y: float<px>
mutable VelX: float<subpx / tick>
mutable VelY: float<subpx / tick>
mutable DirX: float
mutable DirY: float
mutable MaxSpeed: float<subpx / tick>
mutable Accel: float<subpx / tick>
mutable ShotPower: float<subpx / tick> }
[<Struct>]
type PuckState =
| Free
| HeldBy of entityIdx: int
/// Which team scored (for goal-flash display)
[<Struct>]
type GoalScoredBy =
| NoGoal
| Team1Scored
| Team2Scored
/// A skate mark left on the ice during a tight turn
type TrailMark =
{ mutable X: float<px>
mutable Y: float<px>
mutable Life: int<tick> }
/// Player role for 5-player mode AI dispatch
[<Struct>]
type PlayerRole =
| Goalie
| Forward
| Wing
/// One player's directional + fire input for the current tick.
[<Struct>]
type Input =
{ Left: bool; Right: bool; Up: bool; Down: bool; Fire: bool }
module Input =
let none = { Left = false; Right = false; Up = false; Down = false; Fire = false }
// ─── League / Tournament Types ─────────────────────────────────────────
type TeamStats =
{ mutable Wins: int
mutable Losses: int
mutable Draws: int
mutable Points: int
mutable GoalsFor: int
mutable GoalsAgainst: int }
type LeagueState =
{ Stats: TeamStats array
/// Full round-robin: Schedule.[round] = array of (team1, team2) matchups
Schedule: (int * int) array array
Rng: Random
mutable CurrentRound: int
mutable Finished: bool
HumanTeam: int }
type GameState =
{ Entities: Entity array
Rng: Random
mutable Team1Score: int
mutable Team2Score: int
mutable ClockSeconds: int<sec>
mutable ClockTick: int<tick>
mutable PuckState: PuckState
mutable PossessionTimer: int<tick>
// Shot re-capture cooldown: after a player releases the puck, that
// player (and only that player) cannot re-capture it for a short
// window, so you cannot pass to yourself.
mutable LastReleaser: int
mutable RecaptureBlockTicks: int<tick>
mutable StalemateCounter: int<tick>
mutable PrevPuckState: PuckState
mutable ActivePlayer1: int
mutable ActivePlayer2: int
mutable PuckAnimFrame: int
mutable PuckFrictionCounter: int
mutable GameTick: int<tick>
mutable Playing: bool
mutable GoalFlashTimer: int<tick>
// "PERIOD X" banner countdown; play holds while it shows
mutable PeriodFlashTimer: int<tick>
mutable GoalScoredBy: GoalScoredBy
mutable Team1Idx: int
mutable Team2Idx: int
mutable Team1Human: bool
mutable Team2Human: bool
// Puck release speed for the current match (hard mode shoots harder);
// set by the UI at match start alongside the team stats.
mutable ShotSpeed: float<subpx / tick>
mutable PeriodLength: int<sec>
mutable CurrentPeriod: int
mutable NumPeriods: int
// Dynamic player layout
mutable PlayersPerTeam: int
mutable FivePlayerMode: bool
// Keyboard state (one input snapshot per player)
mutable Input1: Input
mutable Input2: Input
// Shoot charge
mutable FireHoldTicks1: int<tick>
mutable FireHoldTicks2: int<tick>
// Stick animation timer per entity
mutable StickAnimTimers: int array
// AI wander: per-player random target offset, re-rolled periodically
WanderX: float<px> array
WanderY: float<px> array
mutable WanderTimer: int<tick>
// Ice trail: skate marks from tight turns
TrailMarks: TrailMark array
mutable TrailMarkCount: int
mutable TrailMarkHead: int // circular buffer write index
PrevDirX: float array // previous direction per entity
PrevDirY: float array }
// Layout derived from the team size. Computed members rather than stored
// fields so they cannot drift out of sync with PlayersPerTeam.
member s.NumPlayers = s.PlayersPerTeam * 2
member s.Team2Start = s.PlayersPerTeam
member s.PuckIdx = s.PlayersPerTeam * 2
member s.NumEntities = s.PlayersPerTeam * 2 + 1
// ─── Helpers ───────────────────────────────────────────────────────────
let private zeroVel = 0.0<subpx / tick>
/// Determine the role of a local player index in the current mode
let playerRole (fivePlayer: bool) (localIdx: int) =
match fivePlayer, localIdx with
| false, _ -> Forward
| true, 0 -> Goalie
| true, (3 | 4) -> Wing
| true, _ -> Forward // indices 1, 2, 5 = forwards
/// Is the entity on team 1?
let inline isOnTeam1 (gs: GameState) idx = idx < gs.Team2Start
/// Does the given team own the puck?
let teamOwnsPuck (gs: GameState) isTeam1 =
match gs.PuckState with
| HeldBy owner ->
if isTeam1 then
isOnTeam1 gs owner
else
not (isOnTeam1 gs owner)
| Free -> false
/// Does the opponent team own the puck?
let opponentOwnsPuck (gs: GameState) isTeam1 = teamOwnsPuck gs (not isTeam1)
/// Sign-based velocity from a direction component
let private dirToVel (dir: float) (power: float<subpx / tick>) =
if dir > 0.0 then power
elif dir < 0.0 then -power
else zeroVel
// ─── Factory ───────────────────────────────────────────────────────────
let createEntity maxSpd accel shotPwr : Entity =
{ X = 0.0<px>
Y = 0.0<px>
VelX = zeroVel
VelY = zeroVel
DirX = 0.0
DirY = 0.0
MaxSpeed = maxSpd
Accel = accel
ShotPower = shotPwr }
let createGameState () : GameState =
let ppt = PlayersPerTeam3
let ents =
Array.init MaxEntities (fun i ->
if i < MaxPlayersPerTeam * 2 then
createEntity zeroVel ForwardAccel zeroVel
else
createEntity PuckMaxSpeed zeroVel zeroVel)
{ Entities = ents
Rng = Random()
Team1Score = 0
Team2Score = 0
ClockSeconds = 0<sec>
ClockTick = 0<tick>
PuckState = Free
PossessionTimer = 0<tick>
LastReleaser = -1
RecaptureBlockTicks = 0<tick>
StalemateCounter = 0<tick>
PrevPuckState = Free
ActivePlayer1 = 0
ActivePlayer2 = ppt
PuckAnimFrame = PuckAnimFrames
PuckFrictionCounter = PuckAnimFrames
GameTick = 0<tick>
Playing = false
GoalFlashTimer = 0<tick>
PeriodFlashTimer = 0<tick>
GoalScoredBy = NoGoal
Team1Idx = 0
Team2Idx = 1
Team1Human = true
Team2Human = false
ShotSpeed = ShotReleaseSpeed
PeriodLength = PeriodMinutes * 60 * 1<sec>
CurrentPeriod = 0
NumPeriods = ExhibitionPeriods
PlayersPerTeam = ppt
FivePlayerMode = false
Input1 = Input.none
Input2 = Input.none
FireHoldTicks1 = 0<tick>
FireHoldTicks2 = 0<tick>
StickAnimTimers = Array.zeroCreate MaxEntities
WanderX = Array.zeroCreate MaxEntities
WanderY = Array.zeroCreate MaxEntities
WanderTimer = 0<tick>
TrailMarks = Array.init MaxTrailMarks (fun _ -> { X = 0.0<px>; Y = 0.0<px>; Life = 0<tick> })
TrailMarkCount = 0
TrailMarkHead = 0
PrevDirX = Array.zeroCreate MaxEntities
PrevDirY = Array.zeroCreate MaxEntities }
// ─── Set Player Mode ──────────────────────────────────────────────────
let setPlayerMode (gs: GameState) fivePlayer =
let ppt = if fivePlayer then PlayersPerTeam5 else PlayersPerTeam3
gs.PlayersPerTeam <- ppt
gs.FivePlayerMode <- fivePlayer
// Entity indices change between modes — drop any stale re-capture block
gs.LastReleaser <- -1
gs.RecaptureBlockTicks <- 0<tick>
// Ensure puck entity has correct stats
let puck = gs.Entities.[gs.PuckIdx]
puck.MaxSpeed <- PuckMaxSpeed
puck.Accel <- zeroVel
puck.ShotPower <- zeroVel
// ─── Position Reset ────────────────────────────────────────────────────
let private resetTeamPositions (gs: GameState) startIdx (homeX: float<px> array) (homeY: float<px> array) dirX =
for i in 0 .. gs.PlayersPerTeam - 1 do
let e = gs.Entities.[startIdx + i]
e.X <- homeX.[i]
e.Y <- homeY.[i]
e.VelX <- zeroVel
e.VelY <- zeroVel
e.DirX <- dirX
e.DirY <- 0.0
let resetPositions (gs: GameState) =
if gs.FivePlayerMode then
resetTeamPositions gs 0 team1HomeX5 team1HomeY5 1.0
resetTeamPositions gs gs.Team2Start team2HomeX5 team2HomeY5 -1.0
else
resetTeamPositions gs 0 team1HomeX team1HomeY 1.0
resetTeamPositions gs gs.Team2Start team2HomeX team2HomeY -1.0
let puck = gs.Entities.[gs.PuckIdx]
// Small random jitter so faceoff races aren't decided the same way
// every time (with exact spawn + symmetric positions it's always a tie,
// and ties break by entity index — i.e. always toward team 1)
puck.X <- CenterX + (gs.Rng.NextDouble() * 2.0 - 1.0) * 6.0<px>
puck.Y <- CenterY + (gs.Rng.NextDouble() * 2.0 - 1.0) * 6.0<px>
puck.VelX <- zeroVel
puck.VelY <- zeroVel
gs.PuckState <- Free
gs.PossessionTimer <- 0<tick>
gs.LastReleaser <- -1
gs.RecaptureBlockTicks <- 0<tick>
gs.StalemateCounter <- 0<tick>
gs.PrevPuckState <- Free
gs.PuckAnimFrame <- PuckAnimFrames
gs.PuckFrictionCounter <- PuckAnimFrames
// ─── Init Match ────────────────────────────────────────────────────────
let initMatch (gs: GameState) =
gs.Team1Score <- 0
gs.Team2Score <- 0
gs.ClockSeconds <- 0<sec>
gs.ClockTick <- 0<tick>
gs.GameTick <- 0<tick>
gs.GoalFlashTimer <- 0<tick>
gs.PeriodFlashTimer <- PeriodFlashTicks
gs.CurrentPeriod <- 0
gs.Playing <- true
gs.Input1 <- Input.none
gs.Input2 <- Input.none
gs.FireHoldTicks1 <- 0<tick>
gs.FireHoldTicks2 <- 0<tick>
let skipGoalie = if gs.FivePlayerMode then 1 else 0
gs.ActivePlayer1 <- skipGoalie
gs.ActivePlayer2 <- gs.Team2Start + skipGoalie
resetPositions gs
// ─── Find Nearest Player to Puck ───────────────────────────────────────
let findNearestToPuck (gs: GameState) startIdx endIdx =
let puck = gs.Entities.[gs.PuckIdx]
let mutable bestDist = Double.MaxValue
let mutable bestIdx = startIdx
for i in startIdx..endIdx do
let e = gs.Entities.[i]
let dx = float (e.X - puck.X)
let dy = float (e.Y - puck.Y)
let d = dx * dx + dy * dy
if d < bestDist then
bestDist <- d
bestIdx <- i
bestIdx
// ─── Release Puck (kick/shoot) ─────────────────────────────────────────
/// Ticks a player is blocked from re-capturing the puck after releasing it.
/// 18 ticks = 0.3 s at the ~60 Hz physics rate (30 FPS x 2 physics ticks
/// per frame). Prevents shooting and immediately picking the puck back up.
let RecaptureCooldownTicks = 18<tick>
/// powerFrac: 0.0..1.0 — fraction of the match's ShotSpeed (pass vs full shot)
let releasePuck (gs: GameState) entityIdx (powerFrac: float) =
let ent = gs.Entities.[entityIdx]
let puck = gs.Entities.[gs.PuckIdx]
let power = gs.ShotSpeed * powerFrac
ent.VelX <- zeroVel
ent.VelY <- zeroVel
puck.VelX <- dirToVel ent.DirX power
puck.VelY <- dirToVel ent.DirY power
gs.PuckState <- Free
gs.PuckAnimFrame <- PuckAnimFrames
gs.PuckFrictionCounter <- PuckAnimFrames
// Block the releaser (and only them) from re-capturing for a short
// window, starting the very tick the puck leaves the stick.
gs.LastReleaser <- entityIdx
gs.RecaptureBlockTicks <- RecaptureCooldownTicks
gs.StickAnimTimers.[entityIdx] <- 10
// ─── Apply Friction ────────────────────────────────────────────────────
// Constant +/-1 per tick toward zero (NOT multiplicative)
let applyFriction (ent: Entity) =
let decel v =
if v > zeroVel then max zeroVel (v - FrictionRate)
elif v < zeroVel then min zeroVel (v + FrictionRate)
else v
ent.VelX <- decel ent.VelX
ent.VelY <- decel ent.VelY
// ─── Clamp Velocity ────────────────────────────────────────────────────
let clampVel (ent: Entity) =
ent.VelX <- clamp -ent.MaxSpeed ent.MaxSpeed ent.VelX
ent.VelY <- clamp -ent.MaxSpeed ent.MaxSpeed ent.VelY
// ─── Wall Bounce + Goal Check ──────────────────────────────────────────
// Returns true if a goal was scored
let checkWallsAndGoals (gs: GameState) idx =
let ent = gs.Entities.[idx]
let isPuck = (idx = gs.PuckIdx)
let mutable scored = false
let inGoalY () = ent.Y >= GoalTop && ent.Y <= GoalBottom
// Left wall / left goal
if ent.VelX < zeroVel && ent.X <= FieldLeft then
if isPuck && inGoalY () then
gs.Team2Score <- gs.Team2Score + 1
gs.GoalFlashTimer <- 90<tick>
gs.GoalScoredBy <- Team2Scored
scored <- true
else
ent.X <- FieldLeft
ent.VelX <- abs ent.VelX
elif ent.X <= FieldLeft && not isPuck then
ent.X <- FieldLeft
if ent.VelX < zeroVel then
ent.VelX <- abs ent.VelX
// Right wall / right goal
if ent.VelX > zeroVel && ent.X >= FieldRight then
if isPuck && inGoalY () then
gs.Team1Score <- gs.Team1Score + 1
gs.GoalFlashTimer <- 90<tick>
gs.GoalScoredBy <- Team1Scored
scored <- true
else
ent.X <- FieldRight
ent.VelX <- -(abs ent.VelX)
elif ent.X >= FieldRight && not isPuck then
ent.X <- FieldRight
if ent.VelX > zeroVel then
ent.VelX <- -(abs ent.VelX)
// Top/bottom walls
if ent.VelY < zeroVel && ent.Y <= FieldTop then
ent.Y <- FieldTop
ent.VelY <- abs ent.VelY
if ent.VelY > zeroVel && ent.Y >= FieldBottom then
ent.Y <- FieldBottom
ent.VelY <- -(abs ent.VelY)
// Clamp safety
if not (isPuck && scored) then
ent.X <- clamp FieldLeft FieldRight ent.X
ent.Y <- clamp FieldTop FieldBottom ent.Y
scored
// ─── Human Input ───────────────────────────────────────────────────────
let applyHumanInput (gs: GameState) idx (input: Input) (fireHoldTicks: int<tick> byref) =
let ent = gs.Entities.[idx]
let mutable dx = 0.0
let mutable dy = 0.0
if input.Left then
ent.VelX <- ent.VelX - ent.Accel
dx <- -1.0
if input.Right then
ent.VelX <- ent.VelX + ent.Accel
dx <- 1.0
if input.Up then
ent.VelY <- ent.VelY - ent.Accel
dy <- -1.0
if input.Down then
ent.VelY <- ent.VelY + ent.Accel
dy <- 1.0
clampVel ent
if dx <> 0.0 || dy <> 0.0 then
ent.DirX <- dx
ent.DirY <- dy
// Charge mechanic: hold fire key for harder shot, release to fire
match gs.PuckState with
| HeldBy owner when owner = idx ->
if input.Fire then
fireHoldTicks <- fireHoldTicks + 1<tick>
elif fireHoldTicks > 0<tick> then
let t = float (int fireHoldTicks) / float (int ChargeTicksForFull)
let chargeFrac = PassPowerFraction + (1.0 - PassPowerFraction) * (min 1.0 t)
fireHoldTicks <- 0<tick>
releasePuck gs idx chargeFrac
| _ -> fireHoldTicks <- 0<tick>
// ─── AI: Move toward target ────────────────────────────────────────────
/// Move toward a target with top speed capped to `speedFrac` of MaxSpeed
/// (1.0 = full speed; lower for unhurried repositioning)
let aiMoveTowardCapped (ent: Entity) (targetX: float<px>) (targetY: float<px>) (speedFrac: float) =
if ent.X > targetX then
ent.VelX <- ent.VelX - ent.Accel
elif ent.X < targetX then
ent.VelX <- ent.VelX + ent.Accel
if ent.Y > targetY then
ent.VelY <- ent.VelY - ent.Accel
elif ent.Y < targetY then
ent.VelY <- ent.VelY + ent.Accel
let cap = ent.MaxSpeed * speedFrac
ent.VelX <- clamp -cap cap ent.VelX
ent.VelY <- clamp -cap cap ent.VelY
let dx = float (targetX - ent.X)
let dy = float (targetY - ent.Y)
if abs dx > 2.0 || abs dy > 2.0 then
ent.DirX <- float (sign dx)
ent.DirY <- float (sign dy)
let aiMoveToward (ent: Entity) (targetX: float<px>) (targetY: float<px>) =
aiMoveTowardCapped ent targetX targetY 1.0
// ─── AI: Active Player Logic ───────────────────────────────────────────
/// Nearest opposing skater to entity `idx` (goalie excluded in 5-player
/// mode: it never leaves the crease, so it doesn't apply pressure).
/// Returns (opponent index, distance in px as float).
let private nearestOpponent (gs: GameState) idx isTeam1 =
let ent = gs.Entities.[idx]
let skipGoalie = if gs.FivePlayerMode then 1 else 0
let oppStart = if isTeam1 then gs.Team2Start else 0
let mutable bestDistSq = Double.MaxValue
let mutable bestIdx = oppStart + skipGoalie
for i in oppStart + skipGoalie .. oppStart + gs.PlayersPerTeam - 1 do
let o = gs.Entities.[i]
let dx = float (o.X - ent.X)
let dy = float (o.Y - ent.Y)
let d = dx * dx + dy * dy
if d < bestDistSq then
bestDistSq <- d
bestIdx <- i
bestIdx, sqrt bestDistSq
/// Pick a teammate worth passing to: within pass range, unmarked, and not
/// far behind the carrier; prefer the most forward-positioned candidate.
let private tryFindPassMate (gs: GameState) idx isTeam1 =
let ent = gs.Entities.[idx]
let goalDir = if isTeam1 then 1.0 else -1.0
let skipGoalie = if gs.FivePlayerMode then 1 else 0
let startEnt = if isTeam1 then 0 else gs.Team2Start
let mutable best = -1
let mutable bestForward = -20.0 // allow a slight drop pass, nothing deeper
for i in skipGoalie .. gs.PlayersPerTeam - 1 do
let ei = startEnt + i
if ei <> idx then
let mate = gs.Entities.[ei]
let dx = float (mate.X - ent.X)
let dy = float (mate.Y - ent.Y)
let dist = sqrt (dx * dx + dy * dy)
if dist >= float AiPassMinDist && dist <= float AiPassMaxDist then
let _, oppDist = nearestOpponent gs ei isTeam1
if oppDist > float AiMateOpenDist then
let forward = dx * goalDir
if forward > bestForward then
bestForward <- forward
best <- ei
if best >= 0 then ValueSome best else ValueNone
/// Aim at a teammate (8-way, since the puck leaves along DirX/DirY) and pass.
let private aiPassTo (gs: GameState) idx mateIdx =
let ent = gs.Entities.[idx]
let mate = gs.Entities.[mateIdx]
let dx = float (mate.X - ent.X)
let dy = float (mate.Y - ent.Y)
let adx = abs dx
let ady = abs dy
// Closest of the 8 directions: pure axis when within ~22.5° of it
if adx > 2.414 * ady then
ent.DirX <- float (sign dx)
ent.DirY <- 0.0
elif ady > 2.414 * adx then
ent.DirX <- 0.0
ent.DirY <- float (sign dy)
else
ent.DirX <- float (sign dx)
ent.DirY <- float (sign dy)
releasePuck gs idx AiPassPowerFraction
let aiActivePlayer (gs: GameState) idx isTeam1 =
let ent = gs.Entities.[idx]
let puck = gs.Entities.[gs.PuckIdx]
let goalDir = if isTeam1 then 1.0 else -1.0
match gs.PuckState with
| Free -> aiMoveToward ent puck.X puck.Y
| HeldBy owner when owner = idx ->
let oppIdx, oppDist = nearestOpponent gs idx isTeam1
let opp = gs.Entities.[oppIdx]
// Blocking = close AND on the goal side of the carrier (roughly
// between the carrier and the target goal)
let goalSide = float (opp.X - ent.X) * goalDir > -6.0
let blocked = oppDist < float AiBlockDist && goalSide
let pressured = oppDist < float AiPressureDist
let inShootZone =
if isTeam1 then
ent.X > FieldRight - AiShootZoneX
else
ent.X < FieldLeft + AiShootZoneX
let alignedWithGoal = ent.Y >= GoalTop && ent.Y <= GoalBottom
// Fresh possession: for the first couple of seconds the carrier
// rushes toward the opponent goal instead of passing or backing off
let rushing = gs.PossessionTimer > PossessionTimer - AiInitialRushTicks
// The defending goalie (5-player mode): don't shoot straight into
// its pads — skate around it instead
let goalieBlocking, goalieY =
if gs.FivePlayerMode then
let g = gs.Entities.[if isTeam1 then gs.Team2Start else 0]
let linedUp = abs (float (g.Y - ent.Y)) < float AiGoalieAvoidY
let goalSideOfCarrier = float (g.X - ent.X) * goalDir > 0.0
linedUp && goalSideOfCarrier, g.Y
else
false, 0.0<px>
if inShootZone && alignedWithGoal && not blocked && not goalieBlocking then
// Clear look at the goal: shoot — but not with perfect aim; a
// fair share of shots go off diagonally and miss from range
ent.DirX <- goalDir
ent.DirY <-
let r = gs.Rng.Next 100
if r < 20 then 1.0
elif r < 40 then -1.0
else 0.0
releasePuck gs idx 1.0
elif inShootZone && goalieBlocking then
// Deke: cut sideways around the goalie to open a shooting angle
// (fast skaters naturally pull this off better)
let side = if ent.Y >= goalieY then 1.0 else -1.0
let targetY =
clamp (GoalTop + 4.0<px>) (GoalBottom - 4.0<px>)
(goalieY + side * AiGoalieDekeOffset)
aiMoveToward
ent
(clamp FieldLeft FieldRight (ent.X + goalDir * 10.0<px>))
targetY
elif rushing then
let targetX =
if isTeam1 then FieldRight - AiCarryTargetMargin
else FieldLeft + AiCarryTargetMargin
let lane =
if blocked || pressured then
// swerve around the defender while still advancing
if opp.Y > ent.Y then ent.Y - 28.0<px> else ent.Y + 28.0<px>
else
ent.Y + gs.WanderY.[idx] * 1.5
let targetY =
if inShootZone then
clamp (GoalTop + 8.0<px>) (GoalBottom - 8.0<px>) lane
else
clamp (FieldTop + 12.0<px>) (FieldBottom - 12.0<px>) lane
aiMoveToward ent targetX targetY
elif pressured then
// Opponent right on us: pass if someone is open, otherwise
// skate a bit backwards and sideways to find a better spot
match tryFindPassMate gs idx isTeam1 with
| ValueSome mateIdx -> aiPassTo gs idx mateIdx
| ValueNone ->
let backX = ent.X - goalDir * 20.0<px>
let sideY =
if opp.Y > ent.Y then ent.Y - 24.0<px> else ent.Y + 24.0<px>
aiMoveToward
ent
(clamp FieldLeft FieldRight backX)
(clamp FieldTop FieldBottom sideY)
elif gs.PossessionTimer <= AiForcedShotTimer then
// Held long enough — get a shot away before the possession
// timer force-releases the puck in a random direction
let rndY = float (gs.Rng.Next(int AiRandomShot * 2 + 1)) - AiRandomShot
ent.DirX <- goalDir
ent.DirY <-
if rndY > 3.0 then 1.0
elif rndY < -3.0 then -1.0
else 0.0
releasePuck gs idx 1.0
elif blocked then
// Blocker ahead but not on us yet: pass if a mate is open,
// otherwise dodge laterally around the blocker, keeping the puck
match tryFindPassMate gs idx isTeam1 with
| ValueSome mateIdx -> aiPassTo gs idx mateIdx
| ValueNone ->
let sideY =
if opp.Y > ent.Y then ent.Y - 28.0<px> else ent.Y + 28.0<px>
aiMoveToward
ent
(clamp FieldLeft FieldRight (ent.X + goalDir * 8.0<px>))
(clamp FieldTop FieldBottom sideY)
else
// Open ice: carry toward the opponent end, weaving a random
// route via the wander offset; funnel toward the goal mouth
// once inside the shooting zone
let targetX =
if isTeam1 then FieldRight - AiCarryTargetMargin
else FieldLeft + AiCarryTargetMargin
let lane = ent.Y + gs.WanderY.[idx] * 1.5
let targetY =
if inShootZone then
clamp (GoalTop + 8.0<px>) (GoalBottom - 8.0<px>) lane
else
clamp (FieldTop + 12.0<px>) (FieldBottom - 12.0<px>) lane
aiMoveToward ent targetX targetY
| HeldBy _ ->
if opponentOwnsPuck gs isTeam1 then
aiMoveToward ent puck.X puck.Y
else
let supportX =
(if isTeam1 then puck.X - 30.0<px> else puck.X + 30.0<px>)
+ gs.WanderX.[idx]
let supportY =
clamp FieldTop FieldBottom (puck.Y + gs.WanderY.[idx])
aiMoveToward ent (clamp FieldLeft FieldRight supportX) supportY
// ─── AI: Defender Logic ────────────────────────────────────────────────
let aiDefender (gs: GameState) idx isTeam1 =
let ent = gs.Entities.[idx]
let localIdx = if isTeam1 then idx else idx - gs.Team2Start
let hasPuck = teamOwnsPuck gs isTeam1
if not gs.FivePlayerMode && opponentOwnsPuck gs isTeam1 then
// 3v3 has no goalie: non-active players collapse in front of their
// own goal (staggered depths) to block the shooting lane
let puck = gs.Entities.[gs.PuckIdx]
// Stand off the crease like defensemen — challenge the shooter,
// don't stand in the net
let guardX =
if isTeam1 then
FieldLeft + 24.0<px> + float localIdx * 12.0<px>
else
FieldRight - 24.0<px> - float localIdx * 12.0<px>
// Track the puck's Y exactly — this is net-minding duty, wander
// here means goals against
let guardY = clamp (GoalTop + 4.0<px>) (GoalBottom - 4.0<px>) puck.Y
aiMoveToward ent guardX guardY
else
let homeX, homeY =
if gs.FivePlayerMode then
let hx =
if hasPuck then
(if isTeam1 then team1HomeX5Attack else team2HomeX5Attack).[localIdx]
else
(if isTeam1 then team1HomeX5 else team2HomeX5).[localIdx]
let hy = (if isTeam1 then team1HomeY5 else team2HomeY5).[localIdx]
hx, hy
else
let hx =
if hasPuck then
(if isTeam1 then team1HomeXAttack else team2HomeXAttack).[localIdx]
else
(if isTeam1 then team1HomeX else team2HomeX).[localIdx]
let hy = (if isTeam1 then team1HomeY else team2HomeY).[localIdx]
hx, hy
// Wander offset so players don't park on exactly the same spot every time
let targetX = clamp FieldLeft FieldRight (homeX + gs.WanderX.[idx])
let targetY = clamp FieldTop FieldBottom (homeY + gs.WanderY.[idx])
// While the puck is loose nobody needs to sprint back to position —
// drift home at reduced speed so the play doesn't reset so abruptly
match gs.PuckState with
| Free -> aiMoveTowardCapped ent targetX targetY AiReturnSpeedFrac
| HeldBy _ -> aiMoveToward ent targetX targetY
// ─── AI: Goalie Logic (5-player mode, index 0 per team) ──────────────
// Goalie patrols a square zone in front of the goal (not just a line).
// When holding the puck, immediately passes forward to nearest teammate.
let private goalieAutoPass (gs: GameState) goalieIdx isTeam1 =
let goalie = gs.Entities.[goalieIdx]
let ppt = gs.PlayersPerTeam
let startEnt = if isTeam1 then 0 else gs.Team2Start
// Find nearest non-goalie teammate to pass to
let mutable bestDist = Double.MaxValue
let mutable bestIdx = -1
for i in 1 .. ppt - 1 do // skip index 0 (goalie itself)
let ei = startEnt + i
let mate = gs.Entities.[ei]
let dx = float (mate.X - goalie.X)
let dy = float (mate.Y - goalie.Y)
let d = dx * dx + dy * dy
if d < bestDist then
bestDist <- d
bestIdx <- ei
if bestIdx >= 0 then
let mate = gs.Entities.[bestIdx]
let dx = float (mate.X - goalie.X)
let dy = float (mate.Y - goalie.Y)
let len = sqrt (dx * dx + dy * dy)
if len > 1.0 then
goalie.DirX <- float (sign dx)
goalie.DirY <- float (sign dy)
else
goalie.DirX <- if isTeam1 then 1.0 else -1.0
goalie.DirY <- 0.0
releasePuck gs goalieIdx PassPowerFraction
let aiGoalie (gs: GameState) idx isTeam1 =
let ent = gs.Entities.[idx]
let puck = gs.Entities.[gs.PuckIdx]
// Auto-pass when holding puck (pass immediately, no delay)
match gs.PuckState with
| HeldBy owner when owner = idx ->
goalieAutoPass gs idx isTeam1
| _ -> ()
// Movement: square zone in front of goal (like real crease)
// Goalie tracks puck Y, but allowed forward shift depends on game situation:
// - Opponent has puck: stay very close to goal line (minimal forward shift)
// - Puck free: moderate forward shift
// - Team has puck: can come out a bit more
let baseX = if isTeam1 then GoaliePatrolXLeft else GoaliePatrolXRight
let forwardShift =
if opponentOwnsPuck gs isTeam1 then 6.0<px> // stay deep
elif teamOwnsPuck gs isTeam1 then 14.0<px> // come out a bit
else 10.0<px> // moderate
let goalieMinX, goalieMaxX =
if isTeam1 then baseX, baseX + forwardShift
else baseX - forwardShift, baseX
// Move toward puck but clamped within the crease square
let targetX = clamp goalieMinX goalieMaxX puck.X
let targetY = clamp (GoalTop + 4.0<px>) (GoalBottom - 4.0<px>) puck.Y
aiMoveToward ent targetX targetY
// ─── AI: Wing Logic (5-player mode, indices 3-4 per team) ────────────
let aiWing (gs: GameState) idx isTeam1 =
let ent = gs.Entities.[idx]
let puck = gs.Entities.[gs.PuckIdx]
let localIdx = if isTeam1 then idx else idx - gs.Team2Start
let wx = gs.WanderX.[idx]
let wy = gs.WanderY.[idx]
if teamOwnsPuck gs isTeam1 then
let targetX =
if isTeam1 then
clamp (FieldLeft + 40.0<px>) (FieldRight - 20.0<px>) (puck.X + 40.0<px> + wx)
else
clamp (FieldLeft + 20.0<px>) (FieldRight - 40.0<px>) (puck.X - 40.0<px> + wx)
let baseY = (if isTeam1 then team1HomeY5 else team2HomeY5).[localIdx]
let targetY = clamp FieldTop FieldBottom (baseY + wy)
aiMoveToward ent targetX targetY
elif opponentOwnsPuck gs isTeam1 then
let retreatX =
if isTeam1 then
clamp FieldLeft (CenterX - 20.0<px>) (puck.X - 50.0<px> + wx)
else
clamp (CenterX + 20.0<px>) FieldRight (puck.X + 50.0<px> + wx)
let targetY = clamp (GoalTop - 10.0<px>) (GoalBottom + 10.0<px>) (puck.Y + wy)
aiMoveToward ent retreatX targetY
else
// puck is loose: drift toward position at reduced speed
let homeX = (if isTeam1 then team1HomeX5 else team2HomeX5).[localIdx]
let homeY = (if isTeam1 then team1HomeY5 else team2HomeY5).[localIdx]
let targetX = clamp FieldLeft FieldRight ((homeX + puck.X) / 2.0 + wx)
let targetY = clamp FieldTop FieldBottom ((homeY + puck.Y) / 2.0 + wy)
aiMoveTowardCapped ent targetX targetY AiReturnSpeedFrac
// ─── Move Puck When Possessed ──────────────────────────────────────────
let movePuckPossessed (gs: GameState) =
match gs.PuckState with
| HeldBy owner ->
let ent = gs.Entities.[owner]
let puck = gs.Entities.[gs.PuckIdx]
puck.X <- ent.X + ent.DirX * 8.0<px>
puck.Y <- ent.Y + ent.DirY * 8.0<px>
puck.VelX <- zeroVel
puck.VelY <- zeroVel
| Free -> ()
// ─── Puck Pickup Collision ─────────────────────────────────────────────
let checkPuckPickup (gs: GameState) =
match gs.PuckState with
| HeldBy _ -> ()
| Free ->
let puck = gs.Entities.[gs.PuckIdx]
// Alternate which team's players are checked first, so that when two
// opponents reach the puck on the same tick the tie doesn't always
// break toward team 1.
let offset = if int gs.GameTick % 2 = 0 then 0 else gs.Team2Start
let rec tryPickup n =
if n < gs.NumPlayers then
let i = (n + offset) % gs.NumPlayers
let ent = gs.Entities.[i]
// The player who just released the puck cannot re-capture it
// during the cooldown; teammates and opponents still can.
let blocked = i = gs.LastReleaser && gs.RecaptureBlockTicks > 0<tick>
if not blocked
&& abs (ent.X - puck.X) < CollisionDist
&& abs (ent.Y - puck.Y) < CollisionDist then
gs.PuckState <- HeldBy i
gs.PossessionTimer <- PossessionTimer
puck.VelX <- zeroVel
puck.VelY <- zeroVel
else
tryPickup (n + 1)
tryPickup 0
// ─── Stalemate Detection ──────────────────────────────────────────────
let checkStalemate (gs: GameState) =
match gs.PrevPuckState, gs.PuckState with
| Free, HeldBy _ -> gs.StalemateCounter <- 0<tick>
| _, Free -> gs.StalemateCounter <- gs.StalemateCounter + 1<tick>
| HeldBy a, HeldBy b when a <> b -> gs.StalemateCounter <- 0<tick>
| _ -> gs.StalemateCounter <- gs.StalemateCounter + 1<tick>
gs.PrevPuckState <- gs.PuckState
gs.StalemateCounter >= StalemateFaceoff
// ─── Game Clock ────────────────────────────────────────────────────────
let updateClock (gs: GameState) =
gs.ClockTick <- gs.ClockTick + 1<tick>
if gs.ClockTick >= ClockTicksPerSec * 1<sec> then
gs.ClockTick <- 0<tick>
gs.ClockSeconds <- gs.ClockSeconds + 1<sec>
// ─── Process One Team ──────────────────────────────────────────────────
let private processTeam
(gs: GameState)
isTeam1
isHuman
activeIdx
(input: Input)
(holdTicks: int<tick> byref)
=
let ppt = gs.PlayersPerTeam
let t2s = gs.Team2Start
let startEnt = if isTeam1 then 0 else t2s
for i in 0 .. ppt - 1 do
let ei = startEnt + i
let role = playerRole gs.FivePlayerMode i
match role with
| Goalie -> aiGoalie gs ei isTeam1
| _ when ei = activeIdx ->
if isHuman then
applyHumanInput gs ei input &holdTicks
else
aiActivePlayer gs ei isTeam1
| Wing -> aiWing gs ei isTeam1
| _ -> aiDefender gs ei isTeam1
// ─── Main Game Tick ────────────────────────────────────────────────────
let gameTick (gs: GameState) =
if not gs.Playing then
()
else
gs.GameTick <- gs.GameTick + 1<tick>
// Decrement stick animation timers
for i in 0 .. gs.NumEntities - 1 do
let t = gs.StickAnimTimers.[i]
if t > 0 then
gs.StickAnimTimers.[i] <- t - 1