-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2862 lines (2802 loc) · 112 KB
/
script.js
File metadata and controls
2862 lines (2802 loc) · 112 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
'use strict';
// ============================================================
// CONSTANTS & MATH
// ============================================================
const PI = Math.PI;
const PI2 = Math.PI * 2;
const HP = Math.PI / 2;
const IS_TOUCH = ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
function clamp(v, lo, hi) { return v < lo ? lo : v > hi ? hi : v; }
function lerp(a, b, t) { return a + (b - a) * t; }
function damp(a, b, lambda, dt) { return lerp(a, b, 1 - Math.exp(-lambda * dt)); }
function dist(ax, ay, bx, by) { const dx = ax - bx, dy = ay - by; return Math.sqrt(dx*dx + dy*dy); }
function rng(lo, hi) { return lo + Math.random() * (hi - lo); }
function normalizeAngle(a) { while (a > PI) a -= PI2; while (a < -PI) a += PI2; return a; }
function angleDiff(a, b) { return normalizeAngle(b - a); }
function formatTime(ms) {
const m = Math.floor(ms / 60000);
const s = Math.floor((ms % 60000) / 1000);
const t = Math.floor((ms % 1000) / 100);
return m + ':' + String(s).padStart(2,'0') + '.' + t;
}
function catmullRom(p0, p1, p2, p3, t) {
const t2 = t * t, t3 = t2 * t;
return 0.5 * ((2*p1) + (-p0+p2)*t + (2*p0-5*p1+4*p2-p3)*t2 + (-p0+3*p1-3*p2+p3)*t3);
}
// ============================================================
// CONFIG
// ============================================================
const CARS = [
{ name:'Speedster', topSpeed:180, accel:0.28, brake:0.35, grip:0.88, nitroMax:100 },
{ name:'Thunder', topSpeed:170, accel:0.32, brake:0.32, grip:0.85, nitroMax:110 },
{ name:'Phantom', topSpeed:195, accel:0.24, brake:0.38, grip:0.92, nitroMax:90 },
{ name:'Titan', topSpeed:150, accel:0.36, brake:0.42, grip:0.80, nitroMax:120 }
];
const COLORS = ['#e83030','#3080ff','#20c060','#f0c030','#cc40cc','#ff8020','#20cccc','#ffffff'];
const TRACKS = [
{
name:'Grand Circuit',
center:[3200,2800],
points:[
{r:1200,a:0},{r:1240,a:0.22},{r:1160,a:0.45},{r:1050,a:0.68},
{r:940,a:0.92},{r:880,a:1.18},{r:960,a:1.45},{r:1080,a:1.68},
{r:1180,a:1.90},{r:1280,a:2.15},{r:1300,a:2.42},{r:1250,a:2.70},
{r:1120,a:2.98},{r:980,a:3.22},{r:860,a:3.48},{r:760,a:3.75},
{r:800,a:4.02},{r:920,a:4.28},{r:1040,a:4.55},{r:1140,a:4.82},
{r:1200,a:5.10},{r:1240,a:5.35},{r:1260,a:5.60},{r:1240,a:5.85},
{r:1220,a:6.10},{r:1200,a:6.28}
]
},
{
name:'Tight Twister',
center:[3000,2600],
points:[
{r:820,a:0},{r:780,a:0.35},{r:650,a:0.72},{r:520,a:1.08},
{r:460,a:1.42},{r:520,a:1.78},{r:680,a:2.12},{r:820,a:2.48},
{r:940,a:2.82},{r:980,a:3.14},{r:940,a:3.50},{r:820,a:3.86},
{r:660,a:4.22},{r:520,a:4.58},{r:480,a:4.92},{r:540,a:5.28},
{r:680,a:5.62},{r:780,a:5.96},{r:820,a:6.28}
]
},
{
name:'Oval Speedway',
center:[3200,2800],
points:[
{r:1100,a:0},{r:1060,a:0.30},{r:700,a:0.65},{r:640,a:1.00},
{r:620,a:1.57},{r:640,a:2.14},{r:700,a:2.49},{r:1060,a:2.84},
{r:1100,a:3.14},{r:1060,a:3.44},{r:700,a:3.79},{r:640,a:4.14},
{r:620,a:4.71},{r:640,a:5.28},{r:700,a:5.63},{r:1060,a:5.98},
{r:1100,a:6.28}
]
},
{
name:'Mountain Pass',
center:[3400,3000],
points:[
{r:1400,a:0},{r:1350,a:0.18},{r:1200,a:0.38},{r:1020,a:0.60},
{r:860,a:0.82},{r:720,a:1.05},{r:650,a:1.30},{r:680,a:1.58},
{r:780,a:1.82},{r:920,a:2.06},{r:1100,a:2.28},{r:1280,a:2.50},
{r:1380,a:2.72},{r:1420,a:2.96},{r:1350,a:3.20},{r:1180,a:3.45},
{r:980,a:3.70},{r:800,a:3.95},{r:680,a:4.22},{r:640,a:4.52},
{r:700,a:4.82},{r:860,a:5.10},{r:1040,a:5.36},{r:1220,a:5.60},
{r:1360,a:5.82},{r:1400,a:6.05},{r:1400,a:6.28}
]
},
{
name:'Desert Sprint',
center:[3000,2600],
points:[
{r:900,a:0},{r:1050,a:0.25},{r:1200,a:0.55},{r:1300,a:0.88},
{r:1280,a:1.20},{r:1150,a:1.50},{r:920,a:1.72},{r:760,a:1.95},
{r:700,a:2.20},{r:740,a:2.50},{r:860,a:2.78},{r:1020,a:3.05},
{r:1180,a:3.30},{r:1300,a:3.55},{r:1320,a:3.82},{r:1250,a:4.10},
{r:1080,a:4.38},{r:900,a:4.65},{r:740,a:4.92},{r:680,a:5.22},
{r:720,a:5.52},{r:820,a:5.78},{r:900,a:6.05},{r:900,a:6.28}
]
}
];
const DIFFICULTIES = [
{name:'Easy', skill:0.60},
{name:'Medium', skill:0.75},
{name:'Hard', skill:0.88},
{name:'Expert', skill:1.00}
];
const WEATHERS = ['Clear','Rain','Storm','Night','Dynamic'];
const ITEM_TYPES = ['shield','boost','missile','oil','magnet','repair','nitro_refill','mine','lightning','ghost_mode'];
const ITEM_EMOJI = {shield:'🛡',boost:'⚡',missile:'🚀',oil:'🛢',magnet:'🧲',repair:'🔧',nitro_refill:'💧',mine:'💣',lightning:'⚡',ghost_mode:'👻'};
const AI_NAMES = ['Blaze','Nova','Ghost','Viper','Storm','Titan','Raven','Spike','Cruz','Neon','Axel','Drift'];
const AI_COLORS = ['#ff4444','#44aaff','#44ff88','#ffcc00','#ff44ff','#ff8800','#00ffcc','#8888ff','#ff6666','#66ff66'];
// Unique personality traits per named AI (aggression, caution, itemStrategy, consistency)
const AI_PERSONALITIES = {
'Blaze': { aggression: 0.90, caution: 0.30, itemStrategy: 0.70, consistency: 0.80 },
'Nova': { aggression: 0.60, caution: 0.60, itemStrategy: 0.80, consistency: 0.90 },
'Ghost': { aggression: 0.40, caution: 0.90, itemStrategy: 0.90, consistency: 0.95 },
'Viper': { aggression: 0.75, caution: 0.65, itemStrategy: 1.00, consistency: 0.85 },
'Storm': { aggression: 0.85, caution: 0.40, itemStrategy: 0.60, consistency: 0.70 },
'Titan': { aggression: 0.50, caution: 0.80, itemStrategy: 0.70, consistency: 0.90 },
'Raven': { aggression: 0.75, caution: 0.55, itemStrategy: 0.85, consistency: 0.80 },
'Spike': { aggression: 0.95, caution: 0.20, itemStrategy: 0.50, consistency: 0.60 },
'Cruz': { aggression: 0.60, caution: 0.70, itemStrategy: 0.75, consistency: 0.85 },
'Neon': { aggression: 0.70, caution: 0.55, itemStrategy: 0.80, consistency: 0.75 },
'Axel': { aggression: 0.80, caution: 0.45, itemStrategy: 0.65, consistency: 0.70 },
'Drift': { aggression: 0.70, caution: 0.60, itemStrategy: 0.70, consistency: 0.65 }
};
const TOTAL_LAPS = 5;
const ROAD_WIDTH = 220;
const WALL_HIT_COOLDOWN_MS = 300;
const PLAYER_WALL_RESTITUTION = 0.35;
const PLAYER_WALL_SPEED_FACTOR = 0.5;
const AI_WALL_RESTITUTION = 0.2;
const AI_WALL_SPEED_FACTOR = 0.6;
const AI_ITEM_USE_RATE = 0.0015; // probability per ms that AI uses an item (legacy, replaced by strategic system)
const AI_BASE_GRIP_MULTIPLIER = 0.9; // AI grip is slightly softer than ideal to simulate realistic handling
const RUBBER_BAND_THRESHOLD = 300; // distance gap before rubber-banding kicks in
const RUBBER_BAND_CATCH_UP = 4000; // divisor for catch-up factor (larger = gentler)
const RUBBER_BAND_SLOW_DOWN = 5000; // divisor for slow-down factor
const RUBBER_BAND_MAX_BOOST = 0.12; // max rubber-band speed multiplier (catch-up)
const RUBBER_BAND_MAX_SLOW = 0.08; // max rubber-band speed reduction (slow-down)
const CAMERA_DAMPING = 5; // camera follow damping lambda
const CAMERA_LOOKAHEAD_FWD = 80; // camera lookahead distance (forward)
const CAMERA_LOOKAHEAD_REV = 110; // camera lookahead distance (rear view)
// ============================================================
// AUDIO ENGINE
// ============================================================
class AudioEngine {
constructor() {
this.enabled = true;
this.ctx = null;
this.osc1 = null; this.osc2 = null; this.drone = null;
this.gainNode = null; this.filterNode = null;
this._started = false;
}
_init() {
if (this._started) return;
this._started = true;
try {
this.ctx = new (window.AudioContext || window.webkitAudioContext)();
this.gainNode = this.ctx.createGain();
this.gainNode.gain.value = 0.18;
this.filterNode = this.ctx.createBiquadFilter();
this.filterNode.type = 'lowpass';
this.filterNode.frequency.value = 800;
const wave = this.ctx.createWaveShaper();
const n = 256, curve = new Float32Array(n);
for (let i = 0; i < n; i++) { const x = (i*2/n)-1; curve[i] = (3+20)*x*20*PI/180/(PI*(3+Math.abs(20*x))); }
wave.curve = curve;
this.osc1 = this.ctx.createOscillator();
this.osc1.type = 'sawtooth';
this.osc1.frequency.value = 80;
this.osc2 = this.ctx.createOscillator();
this.osc2.type = 'square';
this.osc2.frequency.value = 40;
this.drone = this.ctx.createOscillator();
this.drone.type = 'sine';
this.drone.frequency.value = 55;
const g1 = this.ctx.createGain(); g1.gain.value = 0.6;
const g2 = this.ctx.createGain(); g2.gain.value = 0.3;
const g3 = this.ctx.createGain(); g3.gain.value = 0.2;
this.osc1.connect(g1); g1.connect(wave);
this.osc2.connect(g2); g2.connect(wave);
this.drone.connect(g3); g3.connect(wave);
wave.connect(this.filterNode);
this.filterNode.connect(this.gainNode);
this.gainNode.connect(this.ctx.destination);
this.osc1.start(); this.osc2.start(); this.drone.start();
} catch(e) { this.enabled = false; }
}
start() { this._init(); }
setEngine(rpm, speed) {
if (!this.enabled || !this.ctx) return;
const t = this.ctx.currentTime;
const freq = 60 + rpm * 0.06;
const filt = 400 + speed * 4;
this.osc1.frequency.setTargetAtTime(freq, t, 0.05);
this.osc2.frequency.setTargetAtTime(freq * 0.5, t, 0.05);
this.filterNode.frequency.setTargetAtTime(clamp(filt, 200, 3000), t, 0.05);
this.gainNode.gain.setTargetAtTime(this.enabled ? 0.18 : 0, t, 0.05);
}
playEffect(type) {
if (!this.enabled || !this.ctx) return;
const ac = this.ctx;
const t = ac.currentTime;
const g = ac.createGain();
g.connect(ac.destination);
const o = ac.createOscillator();
o.connect(g);
switch(type) {
case 'screech': o.type='sawtooth'; o.frequency.value=300; g.gain.setValueAtTime(0.3,t); g.gain.exponentialRampToValueAtTime(0.001,t+0.4); o.start(t); o.stop(t+0.4); break;
case 'impact': o.type='square'; o.frequency.setValueAtTime(200,t); o.frequency.exponentialRampToValueAtTime(50,t+0.2); g.gain.setValueAtTime(0.4,t); g.gain.exponentialRampToValueAtTime(0.001,t+0.2); o.start(t); o.stop(t+0.2); break;
case 'chime': o.type='sine'; o.frequency.setValueAtTime(880,t); o.frequency.exponentialRampToValueAtTime(440,t+0.3); g.gain.setValueAtTime(0.2,t); g.gain.exponentialRampToValueAtTime(0.001,t+0.3); o.start(t); o.stop(t+0.3); break;
case 'pickup': o.type='sine'; o.frequency.setValueAtTime(440,t); o.frequency.setValueAtTime(660,t+0.05); g.gain.setValueAtTime(0.15,t); g.gain.exponentialRampToValueAtTime(0.001,t+0.2); o.start(t); o.stop(t+0.2); break;
case 'powerup': o.type='sine'; o.frequency.setValueAtTime(330,t); o.frequency.exponentialRampToValueAtTime(990,t+0.4); g.gain.setValueAtTime(0.2,t); g.gain.exponentialRampToValueAtTime(0.001,t+0.4); o.start(t); o.stop(t+0.4); break;
case 'thunder': o.type='sawtooth'; o.frequency.setValueAtTime(60,t); o.frequency.exponentialRampToValueAtTime(20,t+0.6); g.gain.setValueAtTime(0.5,t); g.gain.exponentialRampToValueAtTime(0.001,t+0.6); o.start(t); o.stop(t+0.6); break;
case 'missile': o.type='sawtooth'; o.frequency.setValueAtTime(400,t); o.frequency.exponentialRampToValueAtTime(150,t+0.3); g.gain.setValueAtTime(0.25,t); g.gain.exponentialRampToValueAtTime(0.001,t+0.3); o.start(t); o.stop(t+0.3); break;
case 'countdown': o.type='square'; o.frequency.value=440; g.gain.setValueAtTime(0.3,t); g.gain.exponentialRampToValueAtTime(0.001,t+0.15); o.start(t); o.stop(t+0.15); break;
case 'go': o.type='square'; o.frequency.value=880; g.gain.setValueAtTime(0.35,t); g.gain.exponentialRampToValueAtTime(0.001,t+0.3); o.start(t); o.stop(t+0.3); break;
case 'horn': o.type='sine'; o.frequency.setValueAtTime(440,t); o.frequency.setValueAtTime(550,t+0.12); o.frequency.setValueAtTime(440,t+0.24); g.gain.setValueAtTime(0.28,t); g.gain.exponentialRampToValueAtTime(0.001,t+0.45); o.start(t); o.stop(t+0.45); break;
}
}
toggle() {
this.enabled = !this.enabled;
if (this.gainNode) this.gainNode.gain.value = this.enabled ? 0.18 : 0;
return this.enabled;
}
}
// ============================================================
// PARTICLES
// ============================================================
class Particles {
constructor() {
this.pool = [];
this._freeStack = [];
this.active = [];
for (let i = 0; i < 1200; i++) {
this.pool.push({alive:false, _poolIdx:i});
this._freeStack.push(i);
}
}
_get() {
if (this._freeStack.length > 0) return this.pool[this._freeStack.pop()];
return {alive:false, _poolIdx:-1};
}
emit(x, y, opts={}) {
const p = this._get();
p.alive = true;
p.x = x; p.y = y;
p.vx = opts.vx || 0; p.vy = opts.vy || 0;
p.life = opts.life || 800;
p.maxLife = p.life;
p.size = opts.size || 4;
p.color = opts.color || '#fff';
p.drag = opts.drag !== undefined ? opts.drag : 0.97;
p.gravity = opts.gravity || 0;
this.active.push(p);
}
burst(x, y, count, opts={}) {
for (let i = 0; i < count; i++) {
const a = rng(0, PI2);
const spd = rng(opts.minSpd || 30, opts.maxSpd || 100);
this.emit(x, y, Object.assign({}, opts, { vx: Math.cos(a)*spd, vy: Math.sin(a)*spd }));
}
}
update(dt) {
for (let i = this.active.length - 1; i >= 0; i--) {
const p = this.active[i];
p.life -= dt;
if (p.life <= 0) { p.alive = false; if (p._poolIdx >= 0) this._freeStack.push(p._poolIdx); this.active.splice(i,1); continue; }
p.vx *= p.drag; p.vy *= p.drag;
p.vy += p.gravity * dt * 0.001;
p.x += p.vx * dt * 0.001;
p.y += p.vy * dt * 0.001;
}
}
draw(ctx, cx, cy, W, H) {
// Cull particles outside visible area (world-space culling using camera bounds)
const halfW = W / 2, halfH = H / 2;
const margin = 60;
for (const p of this.active) {
const offX = p.x - cx, offY = p.y - cy;
if (offX < -(halfW + margin) || offX > halfW + margin ||
offY < -(halfH + margin) || offY > halfH + margin) continue;
const alpha = clamp(p.life / p.maxLife, 0, 1);
ctx.globalAlpha = alpha;
ctx.fillStyle = p.color;
ctx.beginPath();
// Draw at world coordinates; canvas transform maps to screen
ctx.arc(p.x, p.y, p.size * alpha, 0, PI2);
ctx.fill();
}
ctx.globalAlpha = 1;
}
}
// ============================================================
// TIRE MARKS
// ============================================================
class TireMarks {
constructor() {
this.marks = [];
this.MAX = 2000;
}
add(x, y, heading, width) {
if (this.marks.length >= this.MAX) this.marks.shift();
const px = -Math.sin(heading) * 12, py = Math.cos(heading) * 12;
this.marks.push({ x1:x+px, y1:y+py, x2:x-px, y2:y-py, age:0, maxAge:15000 });
}
update(dt) {
for (const m of this.marks) m.age += dt;
}
prune() {
let write = 0;
for (let i = 0; i < this.marks.length; i++) {
if (this.marks[i].age < this.marks[i].maxAge) this.marks[write++] = this.marks[i];
}
this.marks.length = write;
}
draw(ctx) {
for (const m of this.marks) {
const a = clamp(1 - m.age/m.maxAge, 0, 1) * 0.5;
ctx.strokeStyle = `rgba(20,15,10,${a})`;
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(m.x1, m.y1);
ctx.lineTo(m.x2, m.y2);
ctx.stroke();
}
}
}
// ============================================================
// WEATHER
// ============================================================
class Weather {
constructor() {
this.state = 'CLEAR';
this.dynamic = false;
this.cycleTimer = 0;
this.cycleInterval = rng(20000, 38000);
this.drops = [];
this.lightningAlpha = 0;
this.lightningTimer = 0;
this.nightAlpha = 0;
this.GRIPS = { CLEAR:1.0, RAIN:0.82, STORM:0.68, NIGHT:0.95 };
this.STATES = ['CLEAR','RAIN','STORM','NIGHT'];
for (let i = 0; i < 400; i++) {
this.drops.push({ x: rng(0,800), y: rng(0,600), vx: rng(-1,1), vy: rng(8,16) });
}
}
setWeather(type) {
if (type === 'Dynamic') { this.dynamic = true; this.state = 'CLEAR'; }
else { this.dynamic = false; this.state = type.toUpperCase(); }
this.nightAlpha = this.state === 'NIGHT' ? 0.5 : 0;
}
getGrip() { return this.GRIPS[this.state] || 1.0; }
update(dt) {
if (this.dynamic) {
this.cycleTimer += dt;
if (this.cycleTimer >= this.cycleInterval) {
this.cycleTimer = 0;
this.cycleInterval = rng(20000,38000);
const idx = (this.STATES.indexOf(this.state) + 1) % this.STATES.length;
this.state = this.STATES[idx];
}
}
if (this.state === 'NIGHT') this.nightAlpha = damp(this.nightAlpha, 0.55, 3, dt*0.001);
else this.nightAlpha = damp(this.nightAlpha, 0, 3, dt*0.001);
if (this.state === 'STORM') {
this.lightningTimer -= dt;
if (this.lightningTimer <= 0) {
this.lightningAlpha = 0.7;
this.lightningTimer = rng(3000,8000);
}
this.lightningAlpha *= 0.92;
} else { this.lightningAlpha = 0; }
}
draw(ctx, W, H, px, py, heading) {
if (this.nightAlpha > 0.01) {
ctx.save();
ctx.setTransform(1,0,0,1,0,0);
ctx.fillStyle = `rgba(0,0,20,${this.nightAlpha})`;
ctx.fillRect(0,0,W,H);
// headlight cones — two beams fanned forward from the car
const cx2 = W/2, cy2 = H/2;
// Ambient glow around car
const ambGrad = ctx.createRadialGradient(cx2,cy2,0,cx2,cy2,120);
ambGrad.addColorStop(0,'rgba(255,250,200,0.10)');
ambGrad.addColorStop(1,'rgba(0,0,0,0)');
ctx.fillStyle = ambGrad;
ctx.beginPath(); ctx.arc(cx2,cy2,120,0,PI2); ctx.fill();
// Left headlight beam
const offL = 0.22; // angular offset to left
const ha = heading;
for (const beamOff of [-offL, offL]) {
const bCx = cx2 + Math.cos(ha + beamOff - PI/2) * 12;
const bCy = cy2 + Math.sin(ha + beamOff - PI/2) * 12;
const bGrad = ctx.createRadialGradient(bCx,bCy,4,bCx,bCy,300);
bGrad.addColorStop(0,'rgba(255,252,220,0.22)');
bGrad.addColorStop(0.5,'rgba(255,248,200,0.08)');
bGrad.addColorStop(1,'rgba(0,0,0,0)');
ctx.fillStyle = bGrad;
ctx.beginPath();
ctx.moveTo(bCx,bCy);
ctx.arc(bCx,bCy,300,ha-0.45,ha+0.45);
ctx.closePath();
ctx.fill();
}
ctx.restore();
}
if (this.lightningAlpha > 0.01) {
ctx.save();
ctx.setTransform(1,0,0,1,0,0);
ctx.fillStyle = `rgba(200,220,255,${this.lightningAlpha})`;
ctx.fillRect(0,0,W,H);
ctx.restore();
}
if (this.state === 'RAIN' || this.state === 'STORM') {
const count = this.state === 'STORM' ? 400 : 220;
ctx.save();
ctx.setTransform(1,0,0,1,0,0);
for (let i = 0; i < count; i++) {
const d = this.drops[i];
d.x += d.vx; d.y += d.vy;
if (d.x > W) d.x -= W; if (d.x < 0) d.x += W;
if (d.y > H) { d.y -= H; d.x = rng(0,W); }
// Vary each drop slightly for natural look
const alpha = 0.25 + (i % 5) * 0.08;
const len = 1.5 + (i % 3) * 0.8;
ctx.strokeStyle = `rgba(180,210,255,${alpha})`;
ctx.lineWidth = 0.6 + (i % 4) * 0.25;
ctx.beginPath();
ctx.moveTo(d.x, d.y);
ctx.lineTo(d.x + d.vx * len, d.y + d.vy * len);
ctx.stroke();
}
ctx.restore();
}
}
getIndicatorText() {
const icons = {CLEAR:'☀️',RAIN:'🌧️',STORM:'⛈️',NIGHT:'🌙'};
return (icons[this.state]||'🌤') + ' ' + this.state;
}
}
// ============================================================
// ITEM BOX
// ============================================================
class ItemBox {
constructor(x, y) {
this.x = x; this.y = y;
this.bobTimer = Math.random() * PI2;
this.active = true;
this.respawnTimer = 0;
}
update(dt) {
this.bobTimer += 0.003 * dt;
if (!this.active) {
this.respawnTimer -= dt;
if (this.respawnTimer <= 0) this.active = true;
}
}
collect(player) {
if (!this.active) return false;
const item = ITEM_TYPES[Math.floor(Math.random()*ITEM_TYPES.length)];
player.addItem(item);
this.active = false;
this.respawnTimer = rng(7000,14000);
return true;
}
draw(ctx) {
if (!this.active) return;
const bob = Math.sin(this.bobTimer) * 4;
ctx.save();
ctx.translate(this.x, this.y + bob);
const grad = ctx.createRadialGradient(0,0,4,0,0,18);
grad.addColorStop(0,'rgba(255,240,80,0.9)');
grad.addColorStop(1,'rgba(255,180,0,0.2)');
ctx.fillStyle = grad;
ctx.beginPath(); ctx.arc(0,0,18,0,PI2); ctx.fill();
ctx.strokeStyle='rgba(255,220,60,0.8)'; ctx.lineWidth=2;
ctx.beginPath(); ctx.arc(0,0,16,0,PI2); ctx.stroke();
ctx.fillStyle='#fff'; ctx.font='14px Arial'; ctx.textAlign='center'; ctx.textBaseline='middle';
ctx.fillText('?',0,0);
ctx.restore();
}
}
// ============================================================
// OIL SLICK
// ============================================================
class OilSlick {
constructor(x, y) {
this.x = x; this.y = y;
this.rotation = Math.random()*PI2;
this.radiusX = 55; this.radiusY = 35;
this.lifetime = 14000; this.maxLife = 14000;
this.active = true;
}
update(dt) {
if (!this.active) return;
this.lifetime -= dt;
if (this.lifetime <= 0) this.active = false;
}
draw(ctx) {
if (!this.active) return;
const a = clamp(this.lifetime/this.maxLife,0,1)*0.6;
ctx.save();
ctx.translate(this.x,this.y);
ctx.rotate(this.rotation);
ctx.globalAlpha = a;
ctx.fillStyle='rgba(20,15,5,0.85)';
ctx.beginPath();
ctx.ellipse(0,0,this.radiusX,this.radiusY,0,0,PI2);
ctx.fill();
ctx.globalAlpha=1;
ctx.restore();
}
}
// ============================================================
// MISSILE
// ============================================================
class Missile {
constructor(x, y, heading, particles) {
this.x = x; this.y = y;
this.heading = heading;
this.speed = 700;
this.lifetime = 3000;
this.active = true;
this.particles = particles;
this.owner = null; // set after creation to identify who fired it
}
update(dt, cars) {
if (!this.active) return;
this.lifetime -= dt;
if (this.lifetime <= 0) { this.active = false; return; }
const s = dt * 0.001;
this.x += Math.cos(this.heading) * this.speed * s;
this.y += Math.sin(this.heading) * this.speed * s;
// trail
if (this.particles) this.particles.emit(this.x, this.y, { color:'#ff8030', size:5, life:300, vx:rng(-20,20), vy:rng(-20,20), drag:0.9 });
// hit detection
for (const car of cars) {
if (car === this.owner) continue; // never hit the car that fired this missile
if (dist(this.x, this.y, car.x, car.y) < 30) {
// Ghost mode: missile passes through
if (car.activeEffects && car.activeEffects.ghost_mode > 0) continue;
// Shield: deflect missile without harming car
if (car.activeEffects && car.activeEffects.shield > 0) {
this.active = false;
if (this.particles) this.particles.burst(this.x,this.y,8,{color:'#44aaff',minSpd:60,maxSpd:140,life:400});
return;
}
car.angularVel = (Math.random()-0.5)*2;
car.speed *= 0.3;
// Stun AI cars briefly after missile impact
if (car.stunTimer !== undefined) car.stunTimer = 600;
this.active = false;
if (this.particles) {
this.particles.burst(this.x,this.y,14,{color:'#ff4400',minSpd:80,maxSpd:220,life:550,size:5});
this.particles.burst(this.x,this.y,8, {color:'#ffcc00',minSpd:60,maxSpd:180,life:450,size:4});
this.particles.burst(this.x,this.y,5, {color:'#ffffff',minSpd:120,maxSpd:260,life:350,size:3});
}
return;
}
}
}
draw(ctx) {
if (!this.active) return;
ctx.save();
ctx.translate(this.x,this.y);
ctx.rotate(this.heading);
ctx.fillStyle='#ffcc00';
ctx.beginPath(); ctx.ellipse(0,0,5,12,0,0,PI2); ctx.fill();
ctx.fillStyle='#ff4400';
ctx.beginPath(); ctx.ellipse(0,8,4,8,0,0,PI2); ctx.fill();
ctx.restore();
}
}
// ============================================================
// GHOST
// ============================================================
class Ghost {
constructor() {
this.frames = [];
this.bestLap = null;
this.playing = false;
this.playIdx = 0;
}
record(x, y, heading) { this.frames.push({x,y,heading}); }
saveLap(lapTime) {
if (!this.bestLapTime || lapTime < this.bestLapTime) {
this.bestLapTime = lapTime;
this.bestLap = this.frames.slice();
}
this.frames = [];
}
startPlayback() { if (this.bestLap) { this.playing = true; this.playIdx = 0; } }
getFrame() {
if (!this.playing || !this.bestLap) return null;
const f = this.bestLap[this.playIdx % this.bestLap.length];
this.playIdx++;
return f;
}
reset() { this.frames = []; this.playing = false; this.playIdx = 0; }
draw(ctx, frame) {
if (!frame) return;
ctx.save();
ctx.translate(frame.x, frame.y);
ctx.rotate(frame.heading + PI/2);
ctx.globalAlpha = 0.32;
// Match aerodynamic body shape
ctx.strokeStyle = 'rgba(160,220,255,0.9)';
ctx.fillStyle = 'rgba(80,160,255,0.12)';
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(-7, -29);
ctx.bezierCurveTo(16, -22, 17, -10, 17, 0);
ctx.lineTo(17, 15);
ctx.bezierCurveTo(17, 24, 12, 27, 8, 27);
ctx.lineTo(-8, 27);
ctx.bezierCurveTo(-12, 27, -17, 24, -17, 15);
ctx.lineTo(-17, 0);
ctx.bezierCurveTo(-17, -10, -16, -22, -7, -29);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.globalAlpha = 1;
ctx.restore();
}
}
// ============================================================
// TRACK
// ============================================================
class Track {
constructor(config) {
this.config = config;
this.center = config.center;
this.roadWidth = ROAD_WIDTH;
this.spline = [];
this.normals = [];
this.cumLen = [];
this.totalLen = 0;
this.itemBoxes = [];
this.trees = [];
this.grandstands = [];
this._buildSpline();
this._placeTrees();
this._placeGrandstands();
this._placeItems();
}
_buildSpline() {
const pts = this.config.points;
const raw = pts.map(p => ({
x: this.center[0] + p.r * Math.cos(p.a),
y: this.center[1] + p.r * Math.sin(p.a)
}));
const N = raw.length;
const segs = 16;
for (let i = 0; i < N; i++) {
const p0 = raw[(i-1+N)%N], p1 = raw[i], p2 = raw[(i+1)%N], p3 = raw[(i+2)%N];
for (let s = 0; s < segs; s++) {
const t = s / segs;
const x = catmullRom(p0.x,p1.x,p2.x,p3.x,t);
const y = catmullRom(p0.y,p1.y,p2.y,p3.y,t);
this.spline.push({x,y});
}
}
// normals and arc lengths
const SN = this.spline.length;
this.cumLen = [0];
for (let i = 0; i < SN; i++) {
const a = this.spline[i], b = this.spline[(i+1)%SN];
const dx = b.x-a.x, dy = b.y-a.y;
const len = Math.sqrt(dx*dx+dy*dy);
const nx = -dy/len, ny = dx/len;
this.normals.push({nx,ny});
this.cumLen.push(this.cumLen[i]+len);
}
this.totalLen = this.cumLen[SN];
// Build spatial grid for O(1) nearest lookup
this._buildGrid();
// Precompute grass texture dots (decorative) with wildflowers
this._grassDots = [];
const flowerColors = ['#ffdd22','#ffffff','#cc44cc','#ff8844','#44aaff'];
for (let i = 0; i < SN; i += 3) {
const sp = this.spline[i];
const nx = this.normals[i].nx, ny = this.normals[i].ny;
for (let side = -1; side <= 1; side += 2) {
const off = rng(ROAD_WIDTH/2 + 16, ROAD_WIDTH/2 + 160);
const isFlower = Math.random() < 0.12;
this._grassDots.push({
x: sp.x + nx * off * side + rng(-12, 12),
y: sp.y + ny * off * side + rng(-12, 12),
r: isFlower ? rng(2, 3.5) : rng(1, 3.5),
dark: Math.random() > 0.55,
flower: isFlower,
flowerColor: flowerColors[Math.floor(Math.random()*flowerColors.length)]
});
}
}
// Precompute gravel dots (between shoulder and road)
this._gravelDots = [];
for (let i = 0; i < SN; i += 2) {
const sp = this.spline[i];
const nx = this.normals[i].nx, ny = this.normals[i].ny;
for (let side = -1; side <= 1; side += 2) {
const off = rng(ROAD_WIDTH/2 + 2, ROAD_WIDTH/2 + 28);
this._gravelDots.push({
x: sp.x + nx * off * side + rng(-4, 4),
y: sp.y + ny * off * side + rng(-4, 4),
r: rng(1.5, 3.5)
});
}
}
// Precompute asphalt surface patches (subtle road variation)
this._asphaltPatches = [];
for (let i = 0; i < SN; i += 5) {
if (Math.random() > 0.45) continue;
const sp = this.spline[i];
const nx = this.normals[i].nx, ny = this.normals[i].ny;
const off = rng(-(ROAD_WIDTH/2 - 28), ROAD_WIDTH/2 - 28);
this._asphaltPatches.push({
x: sp.x + nx * off, y: sp.y + ny * off,
w: rng(14, 52), h: rng(7, 22), a: Math.random() * PI2
});
}
// Precompute advertising banners (placed at regular intervals beside track)
this._banners = [];
const bannerData = [
{bg:'#e83030',fg:'#ffffff',text:'TURBO'},
{bg:'#2255cc',fg:'#ffff00',text:'SPEED'},
{bg:'#228822',fg:'#ffffff',text:'RACE'},
{bg:'#ff8800',fg:'#111111',text:'NITRO'},
{bg:'#8822aa',fg:'#ffffff',text:'APEX'},
{bg:'#111111',fg:'#ff3333',text:'DRIFT'}
];
const bannerStep = Math.max(1, Math.floor(SN / 18));
for (let i = 0; i < SN; i += bannerStep) {
const sp = this.spline[i];
const nn = this.normals[i];
for (let side = -1; side <= 1; side += 2) {
if (Math.random() < 0.45) continue;
const off = ROAD_WIDTH/2 + 38;
const bd = bannerData[Math.floor(Math.random()*bannerData.length)];
this._banners.push({
x: sp.x + nn.nx*off*side,
y: sp.y + nn.ny*off*side,
angle: Math.atan2(nn.ny, nn.nx) + PI/2,
w: rng(52, 80), h: rng(14, 20),
bg: bd.bg, fg: bd.fg, text: bd.text
});
}
}
}
_buildGrid() {
const CELL = 200;
this._gridCell = CELL;
this._grid = {};
for (let i = 0; i < this.spline.length; i++) {
const sp = this.spline[i];
const cx = Math.floor(sp.x / CELL);
const cy = Math.floor(sp.y / CELL);
const key = cx + ',' + cy;
if (!this._grid[key]) this._grid[key] = [];
this._grid[key].push(i);
}
}
nearest(x, y) {
const SN = this.spline.length;
const CELL = this._gridCell;
const cx = Math.floor(x / CELL);
const cy = Math.floor(y / CELL);
let bestDist = Infinity, bestIdx = 0;
// Check 5x5 grid cells (radius 2) around the car position
for (let dcx = -2; dcx <= 2; dcx++) {
for (let dcy = -2; dcy <= 2; dcy++) {
const key = (cx + dcx) + ',' + (cy + dcy);
const cell = this._grid[key];
if (!cell) continue;
for (const i of cell) {
const sp = this.spline[i];
const dx = x - sp.x, dy = y - sp.y;
const d = Math.sqrt(dx*dx + dy*dy);
if (d < bestDist) { bestDist = d; bestIdx = i; }
}
}
}
// Fallback: if grid missed (car far off track), scan all points
if (bestDist === Infinity) {
for (let i = 0; i < SN; i++) {
const sp = this.spline[i];
const d = dist(x,y,sp.x,sp.y);
if (d < bestDist) { bestDist = d; bestIdx = i; }
}
}
return { idx: bestIdx, dist: bestDist, nx: this.normals[bestIdx].nx, ny: this.normals[bestIdx].ny };
}
onRoad(x, y) { return this.nearest(x,y).dist < this.roadWidth/2 + 20; }
curvatureAt(idx) {
const SN = this.spline.length;
const a = this.spline[(idx-1+SN)%SN];
const b = this.spline[idx];
const c = this.spline[(idx+1)%SN];
const d1x = b.x-a.x, d1y = b.y-a.y;
const d2x = c.x-b.x, d2y = c.y-b.y;
const l1 = Math.sqrt(d1x*d1x+d1y*d1y), l2 = Math.sqrt(d2x*d2x+d2y*d2y);
if (l1<0.001||l2<0.001) return 0;
return Math.abs((d1x/l1)*(d2x/l2)+(d1y/l1)*(d2y/l2));
}
_placeItems() {
const SN = this.spline.length;
const step = Math.floor(SN / 12);
for (let i = 0; i < 12; i++) {
const sp = this.spline[(i * step + Math.floor(step/2)) % SN];
this.itemBoxes.push(new ItemBox(sp.x, sp.y));
}
}
_placeTrees() {
const SN = this.spline.length;
for (let i = 0; i < 80; i++) {
const idx = Math.floor(Math.random()*SN);
const sp = this.spline[idx];
const side = Math.random() > 0.5 ? 1 : -1;
const offset = rng(ROAD_WIDTH/2+30, ROAD_WIDTH/2+160);
const nx = this.normals[idx].nx, ny = this.normals[idx].ny;
this.trees.push({ x: sp.x + nx*offset*side, y: sp.y + ny*offset*side, r: rng(12,26) });
}
}
_placeGrandstands() {
const SN = this.spline.length;
const step = Math.floor(SN/6);
for (let i = 0; i < 6; i++) {
const idx = (i*step + 10)%SN;
const sp = this.spline[idx];
const nx = this.normals[idx].nx, ny = this.normals[idx].ny;
const angle = Math.atan2(ny,nx);
this.grandstands.push({ x: sp.x+nx*180, y: sp.y+ny*180, w:120, h:40, angle });
}
}
draw(ctx) {
const SN = this.spline.length;
// Grass background is drawn by the game loop
// Wildflower dots (colored) mixed with grass texture
for (const d of this._grassDots) {
if (d.flower) {
ctx.fillStyle = d.flowerColor;
ctx.beginPath(); ctx.arc(d.x, d.y, d.r * 1.4, 0, PI2); ctx.fill();
} else {
ctx.fillStyle = d.dark ? '#2a5c18' : '#3d7a28';
ctx.beginPath(); ctx.arc(d.x, d.y, d.r, 0, PI2); ctx.fill();
}
}
// Gravel trap (tan strip between shoulder and road)
ctx.strokeStyle='#d4b88a'; ctx.lineWidth=ROAD_WIDTH+52;
ctx.lineCap='round'; ctx.lineJoin='round';
ctx.beginPath();
ctx.moveTo(this.spline[0].x,this.spline[0].y);
for (let i=1;i<SN;i++) ctx.lineTo(this.spline[i].x,this.spline[i].y);
ctx.closePath(); ctx.stroke();
// Gravel texture (subtle dots over gravel strip)
ctx.fillStyle='rgba(160,130,90,0.18)';
for (const p of this._gravelDots||[]) {
ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, PI2); ctx.fill();
}
// Rumble strips — kerb alternating red/white blocks
ctx.strokeStyle='#ffffff'; ctx.lineWidth=ROAD_WIDTH+14;
ctx.setLineDash([32,32]); ctx.lineDashOffset=0;
ctx.beginPath();
ctx.moveTo(this.spline[0].x,this.spline[0].y);
for (let i=1;i<SN;i++) ctx.lineTo(this.spline[i].x,this.spline[i].y);
ctx.closePath(); ctx.stroke();
ctx.strokeStyle='#cc1111'; ctx.lineDashOffset=32;
ctx.beginPath();
ctx.moveTo(this.spline[0].x,this.spline[0].y);
for (let i=1;i<SN;i++) ctx.lineTo(this.spline[i].x,this.spline[i].y);
ctx.closePath(); ctx.stroke();
ctx.setLineDash([]); ctx.lineDashOffset=0;
// Road shadow (subtle dark edge under road)
ctx.strokeStyle='rgba(0,0,0,0.18)'; ctx.lineWidth=ROAD_WIDTH+6;
ctx.beginPath();
ctx.moveTo(this.spline[0].x,this.spline[0].y);
for (let i=1;i<SN;i++) ctx.lineTo(this.spline[i].x,this.spline[i].y);
ctx.closePath(); ctx.stroke();
// Asphalt road surface
ctx.strokeStyle='#2e2e34'; ctx.lineWidth=ROAD_WIDTH;
ctx.beginPath();
ctx.moveTo(this.spline[0].x,this.spline[0].y);
for (let i=1;i<SN;i++) ctx.lineTo(this.spline[i].x,this.spline[i].y);
ctx.closePath(); ctx.stroke();
// Road crown — slightly lighter center strip for 3D road feel
ctx.strokeStyle='rgba(60,60,70,0.35)'; ctx.lineWidth=ROAD_WIDTH*0.45;
ctx.beginPath();
ctx.moveTo(this.spline[0].x,this.spline[0].y);
for (let i=1;i<SN;i++) ctx.lineTo(this.spline[i].x,this.spline[i].y);
ctx.closePath(); ctx.stroke();
// Asphalt surface patches (subtle dark variation)
ctx.fillStyle='rgba(0,0,0,0.07)';
for (const p of this._asphaltPatches) {
ctx.save();
ctx.translate(p.x, p.y); ctx.rotate(p.a);
ctx.fillRect(-p.w/2, -p.h/2, p.w, p.h);
ctx.restore();
}
// Lane markings — white dashes at 1/3 and 2/3 track width
ctx.strokeStyle='rgba(255,255,255,0.28)'; ctx.lineWidth=2; ctx.setLineDash([30,26]);
for (const side of [-1, 1]) {
ctx.beginPath();
const off = side * ROAD_WIDTH * 0.30;
const s0 = this.spline[0], n0 = this.normals[0];
ctx.moveTo(s0.x + n0.nx*off, s0.y + n0.ny*off);
for (let i=1;i<SN;i++) {
const sp = this.spline[i], nn = this.normals[i];
ctx.lineTo(sp.x + nn.nx*off, sp.y + nn.ny*off);
}
ctx.closePath(); ctx.stroke();
}
// Center dashed line
ctx.strokeStyle='rgba(255,224,96,0.60)'; ctx.lineWidth=3.5; ctx.setLineDash([28,22]);
ctx.beginPath();
ctx.moveTo(this.spline[0].x,this.spline[0].y);
for (let i=1;i<SN;i++) ctx.lineTo(this.spline[i].x,this.spline[i].y);
ctx.closePath(); ctx.stroke();
ctx.setLineDash([]);
// Advertising banners alongside the track
for (const b of this._banners||[]) {
ctx.save();
ctx.translate(b.x, b.y); ctx.rotate(b.angle);
ctx.fillStyle = b.bg;
ctx.fillRect(-b.w/2, -b.h/2, b.w, b.h);
ctx.fillStyle = b.fg;
ctx.font = `bold ${Math.round(b.h*0.55)}px Arial`;
ctx.textAlign='center'; ctx.textBaseline='middle';
ctx.fillText(b.text, 0, 0);
ctx.strokeStyle='rgba(0,0,0,0.4)'; ctx.lineWidth=1;
ctx.strokeRect(-b.w/2,-b.h/2,b.w,b.h);
ctx.restore();
}
// Checkered start/finish line
const sf = this.spline[0];
const sfn = this.normals[0];
const sq = 14;
const numSq = Math.ceil(ROAD_WIDTH / sq) + 1;
const lineAngle = Math.atan2(sfn.ny, sfn.nx);
ctx.save();
ctx.translate(sf.x, sf.y);
ctx.rotate(lineAngle);
for (let i = 0; i < numSq; i++) {
for (let row = 0; row < 2; row++) {
ctx.fillStyle = ((i + row) % 2 === 0) ? '#ffffff' : '#111111';
ctx.fillRect(-ROAD_WIDTH/2 + i * sq, -sq + row * sq, sq, sq);
}
}
ctx.restore();
// Trees — more detailed with trunk and highlight
for (const t of this.trees) {
// Trunk
ctx.fillStyle='#5c3d1a';
ctx.beginPath(); ctx.ellipse(t.x, t.y+t.r*0.4, t.r*0.18, t.r*0.35, 0, 0, PI2); ctx.fill();
// Outer canopy shadow
ctx.fillStyle='#1e5012';
ctx.beginPath(); ctx.arc(t.x+t.r*0.12, t.y+t.r*0.1, t.r, 0, PI2); ctx.fill();
// Main canopy
ctx.fillStyle='#2d6e20';
ctx.beginPath(); ctx.arc(t.x, t.y, t.r, 0, PI2); ctx.fill();
// Highlight
ctx.fillStyle='#4a9a32';
ctx.beginPath(); ctx.arc(t.x-t.r*0.22, t.y-t.r*0.22, t.r*0.62, 0, PI2); ctx.fill();
// Top glint
ctx.fillStyle='rgba(120,220,80,0.3)';
ctx.beginPath(); ctx.arc(t.x-t.r*0.3, t.y-t.r*0.3, t.r*0.3, 0, PI2); ctx.fill();
}
// Grandstands — multi-row with roof and flag
for (const g of this.grandstands) {
ctx.save(); ctx.translate(g.x, g.y); ctx.rotate(g.angle);
// Stand base
ctx.fillStyle='#6a6a7a';
ctx.fillRect(-g.w/2,-g.h/2,g.w,g.h);
// Row lines
const rows = 5;
ctx.strokeStyle='#9090a8'; ctx.lineWidth=1.2;
for (let r=1;r<rows;r++) {
const ry = -g.h/2 + r*(g.h/rows);
ctx.beginPath(); ctx.moveTo(-g.w/2, ry); ctx.lineTo(g.w/2, ry); ctx.stroke();
}
// Spectator dots
const specColors = ['#e04040','#4080ee','#40cc60','#f0c030','#cc44cc','#ff8844'];
const rowH = g.h / rows;
const cols = Math.floor(g.w / 8);
for (let r = 0; r < rows; r++) {
const ry = -g.h/2 + r * rowH + rowH * 0.5;
for (let c = 0; c < cols; c++) {
const cx2 = -g.w/2 + c * 8 + 4;
const si = (r * 13 + c * 7) % specColors.length;
ctx.fillStyle = specColors[si];
ctx.beginPath(); ctx.arc(cx2, ry, 2, 0, PI2); ctx.fill();