forked from KilledByAPixel/LittleJS-AI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolePosition.html
More file actions
783 lines (670 loc) · 25.8 KB
/
Copy pathpolePosition.html
File metadata and controls
783 lines (670 loc) · 25.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
<!DOCTYPE html><head>
<title>LittleJS Pole Position</title>
<meta charset=utf-8>
</head><body>
<script src="../dist/littlejs.js?1.18.15"></script>
<script src="../templates/soundGenerator.js"></script>
<script>
'use strict';
// engine settings
debugWatermark = false; // Hide debug watermark in corner
showEngineVersion = false; // Hide engine version console display
///////////////////////////////////////////////////////////////////////////////
// Pole Position (tiny playable prototype)
// track + camera constants (tuned for a ~960x540 canvas)
const CANVAS_SIZE = vec2(960, 540);
const DRAW_DIST = 260; // how many road segments to draw
const ROAD_W = 1.85; // road half-width in world units
const CAMERA_HEIGHT = 0.72; // bigger = road appears lower
const CAMERA_DEPTH = 1.00; // perspective strength
const RUMBLE_W = 1.22; // rumble extends beyond road
const MAX_SPEED = 0.90; // world segments per frame
const ACCEL = 0.012;
const BRAKE = 0.020;
const COAST_DECEL = 0.008;
const OFFROAD_DECEL = 0.030;
// steering (velocity-based for smooth handling)
const STEER_ACCEL = 0.010; // input accel (scaled by speed-factor)
const STEER_DAMP = 0.86; // velocity damping per frame
const STEER_MAX_VEL = 0.055; // cap so curves are still recoverable
const CENTRIFUGAL = 0.9; // curve pull applied to lateral velocity
// track data
let segments = [];
let trackLen = 0;
// game state
let state = 'title'; // 'title' | 'play' | 'timeup'
let trackPos = 0; // distance along track in segments
let speed = 0;
let playerX = 0; // lateral offset in world units
let playerVX = 0; // lateral velocity
let score = 0;
let lap = 0;
let timeLeftFrames = 60 * 60; // 60 seconds at 60 fps
let crashTimer = 0;
// AI cars
let aiCars = [];
// cached projection for the visible road
let proj = [];
// sounds
let sStart, sCrash, sRumble, sEngine;
///////////////////////////////////////////////////////////////////////////////
function buildTrack()
{
segments = [];
const add = (count, curve=0)=>
{
for (let i=0; i<count; ++i)
segments.push({ curve });
};
// A simple repeating circuit: straights + wide left/right + S bends
add(160, 0);
add(120, -0.0020);
add(60, -0.0010);
add(120, 0);
add(140, 0.0022);
add(80, 0.0012);
add(130, 0);
// S bend section
add(60, -0.0024);
add(60, 0.0024);
add(60, -0.0016);
add(60, 0.0016);
// long straight to feel fast
add(220, 0);
// big sweeping right back to start
add(180, 0.0020);
add(80, 0.0010);
add(120, 0);
// pad a bit for comfort
add(60, 0);
trackLen = segments.length;
}
function resetGame()
{
state = 'play';
trackPos = 0;
speed = 0;
playerX = 0;
playerVX = 0;
score = 0;
lap = 0;
timeLeftFrames = 60 * 60;
crashTimer = 0;
// spawn some simple AI cars ahead
aiCars = [];
const carCount = 12;
for (let i=0; i<carCount; ++i)
{
aiCars.push({
z: (i*trackLen/carCount + 60) % trackLen,
speed: rand(0.35, 0.55),
offset: rand(0.9, -0.9),
wobble: rand(1000),
colorH: rand(),
});
}
sStart && sStart.play();
}
///////////////////////////////////////////////////////////////////////////////
function gameInit()
{
setCanvasFixedSize(CANVAS_SIZE);
buildTrack();
// lightweight sfx
sStart = new SoundGenerator({ volume:.6, frequency:420, attack:0, release:.08, pitchJump:80, pitchJumpTime:.02, noise:.02 });
sCrash = new SoundGenerator({ volume:.8, frequency:90, attack:0, release:.25, shapeCurve:0, noise:.35, bitCrush:6, slide:-.6 });
sRumble = new SoundGenerator({ volume:.25, frequency:120, attack:0, release:.05, noise:.15, bitCrush:10 });
// engine "vroom" pulse - replayed at a rate set by speed (see gameUpdate)
sEngine = new SoundGenerator({ volume:.22, frequency:55, attack:0, release:.06, shapeCurve:.3, noise:.05, bitCrush:7 });
proj = new Array(DRAW_DIST+2);
}
///////////////////////////////////////////////////////////////////////////////
function gameUpdate()
{
// title / restart
const startPressed = keyWasPressed('Enter') || keyWasPressed('Space');
if (state !== 'play')
{
if (startPressed)
resetGame();
return;
}
// input
const up = keyIsDown('ArrowUp') || keyIsDown('KeyW');
const down = keyIsDown('ArrowDown') || keyIsDown('KeyS');
const left = keyIsDown('ArrowLeft') || keyIsDown('KeyA');
const right = keyIsDown('ArrowRight')|| keyIsDown('KeyD');
// speed
if (up) speed += ACCEL;
else speed -= COAST_DECEL;
if (down) speed -= BRAKE;
speed = clamp(speed, 0, MAX_SPEED);
// engine pulse: pops faster and higher in pitch with speed.
// at rest -> low idle every 14 frames; at top speed -> rapid 3-frame pops.
const sn = speed / MAX_SPEED;
const enginePeriod = max(3, (14 - sn*11)|0);
if (frame % enginePeriod === 0)
sEngine.play(undefined, 0.5 + sn*0.35, 0.6 + sn*1.5);
// steering as lateral acceleration -> velocity (with damping)
// gives weight/inertia: car keeps drifting briefly after key release,
// so curves are about anticipating rather than spamming the key.
const steer = (right?1:0) - (left?1:0);
const speedFactor = 0.35 + (speed/MAX_SPEED) * 1.25; // less twitchy at low speed
playerVX += steer * STEER_ACCEL * speedFactor;
// centrifugal force from current curve - applied to velocity, not position,
// so it integrates smoothly and is dampened the same way as steering input.
const baseIndex = trackPos|0;
const curve = segments[baseIndex % trackLen].curve;
playerVX -= curve * speed * CENTRIFUGAL;
// damp + clamp lateral velocity, then integrate
playerVX *= STEER_DAMP;
playerVX = clamp(playerVX, -STEER_MAX_VEL, STEER_MAX_VEL);
playerX += playerVX;
// crash recovery
if (crashTimer > 0)
crashTimer--;
// offroad
const offRoad = abs(playerX) > ROAD_W*1.02;
if (offRoad)
{
speed = max(0, speed - OFFROAD_DECEL);
if (speed > .15 && (frame & 7) === 0)
sRumble.play();
}
// advance along track
const lastPos = trackPos;
trackPos += speed;
if (trackPos >= trackLen)
{
trackPos -= trackLen;
lap++;
}
// score + timer
score += speed * 120 * (offRoad ? .6 : 1);
if (speed > .05)
timeLeftFrames--;
if (timeLeftFrames <= 0)
{
state = 'timeup';
speed = 0;
return;
}
// AI cars
for (const c of aiCars)
{
// slight lane wobble
c.wobble += 1;
c.offset += Math.sin(c.wobble*.02) * 0.0012;
c.offset = clamp(c.offset, -1.1, 1.1);
c.z += c.speed;
if (c.z >= trackLen)
c.z -= trackLen;
// collision when very close in Z
const dz = (c.z - trackPos + trackLen) % trackLen;
if (dz < 1.2 && dz > 0)
{
if (abs(playerX - c.offset) < .22 && crashTimer <= 0 && speed > .10)
{
crashTimer = 35;
speed *= .55;
playerX += sign(playerX - c.offset || randSign()) * .28;
sCrash.play();
}
}
// keep AI from lingering right on player forever
if (dz < .25)
c.z = (c.z + 12) % trackLen;
}
}
///////////////////////////////////////////////////////////////////////////////
function gameUpdatePost()
{
// no world-space camera needed, we render in screen space
}
///////////////////////////////////////////////////////////////////////////////
function projectPoint(z, x, w, h, horizonY)
{
const scale = CAMERA_DEPTH / z;
const screenX = w/2 + scale * (x - playerX) * w/2;
const screenY = horizonY + scale * CAMERA_HEIGHT * h;
const roadW = scale * ROAD_W * w/2;
const rumbleW = roadW * RUMBLE_W;
return { screenX, screenY, scale, roadW, rumbleW };
}
function fillQuad(ctx, x1,y1, x2,y2, x3,y3, x4,y4)
{
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.lineTo(x3,y3);
ctx.lineTo(x4,y4);
ctx.closePath();
ctx.fill();
}
// deterministic tiny hash for scenery variation
const frac = (x)=> x - Math.floor(x);
const hash01 = (n)=> frac(Math.sin(n*127.1) * 43758.5453123);
function drawTree(ctx, x, yGround, size, seed)
{
// size in pixels
const trunkH = size * 0.34;
const trunkW = size * 0.13;
const canopyR = size * 0.32;
const hJit = (hash01(seed+9) - .5) * size * 0.12;
const hue = .30 + (hash01(seed+2)-.5) * .06;
// trunk
ctx.fillStyle = hsl(.08, .45, .28).toString();
ctx.fillRect(x - trunkW/2, yGround - trunkH + hJit, trunkW, trunkH);
// canopy (3 blobs)
ctx.fillStyle = hsl(hue, .70, .30).toString();
ctx.beginPath();
const cY = yGround - trunkH + hJit;
const r1 = canopyR * (0.85 + hash01(seed+3)*0.25);
const r2 = canopyR * (0.75 + hash01(seed+4)*0.30);
const r3 = canopyR * (0.70 + hash01(seed+5)*0.35);
ctx.arc(x, cY - canopyR*0.55, r1, 0, Math.PI*2);
ctx.arc(x - canopyR*0.55, cY - canopyR*0.20, r2, 0, Math.PI*2);
ctx.arc(x + canopyR*0.55, cY - canopyR*0.15, r3, 0, Math.PI*2);
ctx.fill();
}
function drawSign(ctx, x, yGround, size, seed)
{
const postH = size * 0.60;
const postW = max(2, size * 0.07);
const boardW = size * (0.55 + hash01(seed+1)*0.25);
const boardH = size * 0.22;
// post
ctx.fillStyle = hsl(0, 0, .25).toString();
ctx.fillRect(x - postW/2, yGround - postH, postW, postH);
// sign board
const hue = hash01(seed+7);
ctx.fillStyle = hsl(hue, .75, .55).toString();
ctx.fillRect(x - boardW/2, yGround - postH - boardH*0.85, boardW, boardH);
// stripe detail
ctx.fillStyle = hsl(0,0,1,.85).toString();
ctx.fillRect(x - boardW*0.42, yGround - postH - boardH*0.62, boardW*0.84, max(2, boardH*0.18));
}
function renderRoadAndCars()
{
const ctx = mainContext;
const w = mainCanvasSize.x;
const h = mainCanvasSize.y;
const horizonY = h * 0.36;
// sky
ctx.fillStyle = hsl(.58, .55, .75).toString();
ctx.fillRect(0, 0, w, horizonY);
// distant haze
ctx.fillStyle = hsl(.58, .25, .85, .25).toString();
ctx.fillRect(0, horizonY-18, w, 36);
// precompute visible road
const baseIndex = trackPos|0;
const offset = trackPos - baseIndex;
let x = 0;
let dx = 0;
for (let i=0; i<=DRAW_DIST+1; ++i)
{
const seg = segments[(baseIndex + i) % trackLen];
x += dx;
dx += seg.curve;
const z = max(1.2, i + 1 - offset); // clamp near plane to prevent distortion but keep road visible
const p = projectPoint(z, x, w, h, horizonY);
p.i = i;
p.curve = seg.curve;
p.grassAlt = (((baseIndex + i) / 6)|0) & 1;
p.rumbleAlt = (((baseIndex + i) / 3)|0) & 1;
proj[i] = p;
}
// grass base under horizon
ctx.fillStyle = hsl(.33, .85, .25).toString();
ctx.fillRect(0, horizonY, w, h-horizonY);
// dash pattern settings (in world segments)
const dashPeriod = 8;
const dashOn = 4;
const dashIsOn = (worldPos)=> ((worldPos % dashPeriod + dashPeriod) % dashPeriod) < dashOn;
// draw from far -> near
let prev = proj[DRAW_DIST];
for (let i=DRAW_DIST-1; i>=0; --i)
{
const cur = proj[i];
// snap to integer scanlines to avoid cracks between segments
let yFar = clamp(prev.screenY, 0, h);
let yNear = clamp(cur.screenY, 0, h);
yFar = clamp(Math.floor(yFar), 0, h);
yNear = clamp(Math.ceil(yNear) + 1, 0, h); // +1px overlap prevents hairline gaps
if (yNear <= yFar)
{
prev = cur;
continue;
}
// grass stripes
ctx.fillStyle = (cur.grassAlt ? hsl(.33,.85,.22) : hsl(.33,.80,.28)).toString();
ctx.fillRect(0, yFar, w, yNear - yFar);
// rumble strips
const farL = prev.screenX - prev.rumbleW;
const farR = prev.screenX + prev.rumbleW;
const nearL = cur.screenX - cur.rumbleW;
const nearR = cur.screenX + cur.rumbleW;
ctx.fillStyle = (cur.rumbleAlt ? hsl(0,0,1) : hsl(0,1,.45)).toString();
fillQuad(ctx, nearL, yNear, farL, yFar, farR, yFar, nearR, yNear);
// road
const farRL = prev.screenX - prev.roadW;
const farRR = prev.screenX + prev.roadW;
const nearRL = cur.screenX - cur.roadW;
const nearRR = cur.screenX + cur.roadW;
ctx.fillStyle = (cur.rumbleAlt ? hsl(0,0,.23) : hsl(0,0,.18)).toString();
fillQuad(ctx, nearRL, yNear, farRL, yFar, farRR, yFar, nearRR, yNear);
// center line (dashed, locked to world so it scrolls correctly)
const worldPos = baseIndex + i + offset;
if (dashIsOn(worldPos))
{
const farC = prev.screenX;
const nearC = cur.screenX;
const lineWFar = max(1, prev.roadW * .03);
const lineWNear = max(1, cur.roadW * .03);
ctx.fillStyle = hsl(0,0,.92,.9).toString();
fillQuad(ctx,
nearC-lineWNear, yNear, farC-lineWFar, yFar,
farC+lineWFar, yFar, nearC+lineWNear, yNear);
}
// roadside scenery (trees + signs)
// draw in the same far->near order so near scenery occludes far scenery
if (cur.scale > 0.003 && yNear > horizonY + 6)
{
const segIndex = (baseIndex + i) % trackLen;
const baseSize = clamp(cur.scale * h * 1.15, 14, 230);
// trees every ~7-11 segments
if ((segIndex % 7) === 0)
{
const xTreeL = cur.screenX - (cur.rumbleW + cur.roadW*0.85);
drawTree(ctx, xTreeL, yNear, baseSize, segIndex*3 + 1);
}
if ((segIndex % 11) === 0)
{
const xTreeR = cur.screenX + (cur.rumbleW + cur.roadW*0.85);
drawTree(ctx, xTreeR, yNear, baseSize, segIndex*3 + 2);
}
// signs every ~13 segments (alternate sides)
if ((segIndex % 13) === 0)
{
const side = (segIndex & 1) ? -1 : 1;
const xSign = cur.screenX + side * (cur.rumbleW + cur.roadW*0.55);
drawSign(ctx, xSign, yNear, baseSize*0.85, segIndex*5 + 7);
}
}
prev = cur;
}
// ensure the road reaches the bottom of the screen (near cap)
{
const p = proj[0];
if (p)
{
const yTop = clamp(Math.floor(p.screenY), 0, h);
if (yTop < h)
{
const yBottom = h + 2; // a tiny overshoot to avoid bottom edge gaps
const bottomScale = 1.18;
// rumble
const topL = p.screenX - p.rumbleW;
const topR = p.screenX + p.rumbleW;
const botL = p.screenX - p.rumbleW * bottomScale;
const botR = p.screenX + p.rumbleW * bottomScale;
ctx.fillStyle = (p.rumbleAlt ? hsl(0,0,1) : hsl(0,1,.45)).toString();
fillQuad(ctx, botL, yBottom, topL, yTop, topR, yTop, botR, yBottom);
// road
const topRL = p.screenX - p.roadW;
const topRR = p.screenX + p.roadW;
const botRL = p.screenX - p.roadW * bottomScale;
const botRR = p.screenX + p.roadW * bottomScale;
ctx.fillStyle = (p.rumbleAlt ? hsl(0,0,.23) : hsl(0,0,.18)).toString();
fillQuad(ctx, botRL, yBottom, topRL, yTop, topRR, yTop, botRR, yBottom);
// center stripe (match dash pattern)
const capWorldPos = baseIndex + offset;
if (dashIsOn(capWorldPos))
{
ctx.fillStyle = hsl(0,0,.92,.9).toString();
const lineWTop = max(1, p.roadW * .03);
const lineWBot = max(1, p.roadW * .03 * bottomScale);
fillQuad(ctx,
p.screenX-lineWBot, yBottom, p.screenX-lineWTop, yTop,
p.screenX+lineWTop, yTop, p.screenX+lineWBot, yBottom);
}
}
}
}
// draw AI cars from far -> near (using the projection table)
const visibleCars = [];
for (const c of aiCars)
{
const dz = (c.z - trackPos + trackLen) % trackLen;
if (dz <= 0 || dz >= DRAW_DIST) continue;
visibleCars.push({ c, dz });
}
visibleCars.sort((a,b)=> b.dz - a.dz); // far first
for (const {c, dz} of visibleCars)
{
const i = dz|0;
const t = dz - i;
const a = proj[i];
const b = proj[i+1];
if (!a || !b) continue;
const lerpP = (k)=> lerp(a[k], b[k], t);
const sx = lerpP('screenX');
const sy = lerpP('screenY');
const sc = lerpP('scale');
const roadW = lerpP('roadW');
const carX = sx + sc * c.offset * w/2;
const carW = max(6, sc * 0.28 * w/2);
const carH = max(8, sc * 0.36 * h);
// simple occlusion: don't draw if behind horizon
if (sy - carH < h*0.08 || sy > h) continue;
drawAICar(ctx, carX, sy, carW, carH, c.colorH);
}
// player car (screen-fixed, like arcade view)
const carScreenY = h * 0.86;
const carScreenX = w * 0.5 + (keyIsDown('ArrowLeft')||keyIsDown('KeyA') ? -6 : 0) + (keyIsDown('ArrowRight')||keyIsDown('KeyD') ? 6 : 0);
const carScale = 1;
drawPlayerCar(ctx, carScreenX, carScreenY, carScale);
// subtle vignette
ctx.fillStyle = hsl(0,0,0,.18).toString();
ctx.fillRect(0, 0, w, 12);
ctx.fillRect(0, h-12, w, 12);
}
function drawAICar(ctx, cx, groundY, W, H, colorH)
{
// Compact F1 silhouette: trapezoid body, exposed rear tires,
// tiny rear wing. Helmet only on cars big enough to read it.
const body = hsl(colorH, .75, .55).toString();
const tire = hsl(0,0,.10).toString();
// soft shadow
ctx.fillStyle = hsl(0,0,0,.4).toString();
ctx.fillRect(cx - W*0.55, groundY - max(1, H*0.04), W*1.10, max(2, H*0.08));
// rear tires (sticking outside the body)
const rtW = W*0.22, rtH = H*0.44;
ctx.fillStyle = tire;
ctx.fillRect(cx - W*0.50, groundY - rtH, rtW, rtH);
ctx.fillRect(cx + W*0.50 - rtW, groundY - rtH, rtW, rtH);
// body trapezoid
const botY = groundY - H*0.20;
const topY = groundY - H*0.95;
const botW = W*0.60;
const topW = W*0.22;
ctx.fillStyle = body;
fillQuad(ctx,
cx - botW/2, botY,
cx - topW/2, topY,
cx + topW/2, topY,
cx + botW/2, botY);
// rear wing - thin dark band behind/above the rear tires
ctx.fillStyle = hsl(0,0,.12).toString();
ctx.fillRect(cx - W*0.42, groundY - H*0.56, W*0.84, max(1, H*0.07));
// cockpit opening
const ckBotW = W*0.22, ckTopW = W*0.13;
ctx.fillStyle = hsl(0,0,.08).toString();
fillQuad(ctx,
cx - ckBotW/2, groundY - H*0.34,
cx - ckTopW/2, groundY - H*0.68,
cx + ckTopW/2, groundY - H*0.68,
cx + ckBotW/2, groundY - H*0.34);
// driver helmet (skip on tiny far cars to avoid noise)
if (H > 18)
{
ctx.fillStyle = hsl(0,0,.95).toString();
ctx.beginPath();
ctx.arc(cx, groundY - H*0.55, max(1, H*0.10), 0, Math.PI*2);
ctx.fill();
}
}
function drawPlayerCar(ctx, x, y, s=1)
{
// F1 silhouette from behind: tapered body, exposed wheels,
// driver's helmet and a rear wing element behind the rear axle.
const W = 110*s;
const H = 68*s;
const flash = crashTimer>0 && (frame&3)<2;
const red = flash ? hsl(0,0,1).toString() : hsl(.01, .85, .52).toString();
const redDark = flash ? hsl(0,0,.78).toString() : hsl(.01, .85, .34).toString();
const tire = hsl(0,0,.08).toString();
const tireTop = hsl(0,0,.22).toString();
// ground shadow
ctx.fillStyle = hsl(0,0,0,.45).toString();
ctx.beginPath();
ctx.ellipse(x, y + H*0.04, W*0.62, H*0.10, 0, 0, Math.PI*2);
ctx.fill();
// rear tires (largest, closest to camera) - poking out wider than body
const rtW = W*0.22, rtH = H*0.46;
const rtY = y - rtH;
const rtxL = x - W*0.50;
const rtxR = x + W*0.50 - rtW;
ctx.fillStyle = tire;
ctx.fillRect(rtxL, rtY, rtW, rtH);
ctx.fillRect(rtxR, rtY, rtW, rtH);
ctx.fillStyle = tireTop;
ctx.fillRect(rtxL, rtY, rtW, rtH*0.16);
ctx.fillRect(rtxR, rtY, rtW, rtH*0.16);
// rear wing - black plate spanning behind the body, with endplates
const wingY = y - H*0.52;
const wingH = H*0.08;
const wingW = W*0.96;
ctx.fillStyle = hsl(0,0,.12).toString();
ctx.fillRect(x - wingW/2, wingY, wingW, wingH);
ctx.fillStyle = redDark;
ctx.fillRect(x - wingW/2, wingY - wingH*1.6, wingH*0.5, wingH*2.2);
ctx.fillRect(x + wingW/2 - wingH*0.5, wingY - wingH*1.6, wingH*0.5, wingH*2.2);
// main body - trapezoid: wide at rear, narrow toward nose
const bodyBotW = W*0.58;
const bodyTopW = W*0.18;
const bodyTopY = y - H*0.98;
const bodyBotY = y - H*0.18;
ctx.fillStyle = red;
fillQuad(ctx,
x - bodyBotW/2, bodyBotY,
x - bodyTopW/2, bodyTopY,
x + bodyTopW/2, bodyTopY,
x + bodyBotW/2, bodyBotY);
// body side-shading for depth (left + right slivers)
ctx.fillStyle = redDark;
fillQuad(ctx,
x - bodyBotW/2, bodyBotY,
x - bodyTopW/2, bodyTopY,
x - bodyTopW/2 + W*0.025, bodyTopY,
x - bodyBotW/2 + W*0.07, bodyBotY);
fillQuad(ctx,
x + bodyBotW/2 - W*0.07, bodyBotY,
x + bodyTopW/2 - W*0.025, bodyTopY,
x + bodyTopW/2, bodyTopY,
x + bodyBotW/2, bodyBotY);
// white centerline stripe down the nose
const strBotW = W*0.08;
const strTopW = W*0.03;
ctx.fillStyle = hsl(0,0,.95).toString();
fillQuad(ctx,
x - strBotW/2, bodyBotY,
x - strTopW/2, bodyTopY,
x + strTopW/2, bodyTopY,
x + strBotW/2, bodyBotY);
// front tires - smaller, peek above the body line near the front
const ftW = W*0.13, ftH = H*0.20;
const ftY = y - H*0.78;
ctx.fillStyle = tire;
ctx.fillRect(x - W*0.34, ftY, ftW, ftH);
ctx.fillRect(x + W*0.34 - ftW, ftY, ftW, ftH);
// cockpit opening - dark trapezoid set into the body
const ckBotW = W*0.26;
const ckTopW = W*0.15;
const ckBotY = y - H*0.32;
const ckTopY = y - H*0.70;
ctx.fillStyle = hsl(0,0,.08).toString();
fillQuad(ctx,
x - ckBotW/2, ckBotY,
x - ckTopW/2, ckTopY,
x + ckTopW/2, ckTopY,
x + ckBotW/2, ckBotY);
// driver helmet - white sphere with a dark visor band
const helmR = H*0.13;
const helmY = y - H*0.55;
ctx.fillStyle = hsl(0,0,.95).toString();
ctx.beginPath();
ctx.arc(x, helmY, helmR, 0, Math.PI*2);
ctx.fill();
ctx.fillStyle = hsl(.6, .4, .12).toString();
ctx.fillRect(x - helmR*0.85, helmY - helmR*0.18, helmR*1.7, helmR*0.55);
}
///////////////////////////////////////////////////////////////////////////////
function gameRender()
{
// clear (engine might already clear, but this is explicit)
mainContext.clearRect(0, 0, mainCanvasSize.x, mainCanvasSize.y);
if (state === 'play')
renderRoadAndCars();
else
{
// background for title/timeup
const ctx = mainContext;
const w = mainCanvasSize.x;
const h = mainCanvasSize.y;
ctx.fillStyle = hsl(.58, .55, .75).toString();
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = hsl(.33, .85, .25).toString();
ctx.fillRect(0, h*0.55, w, h*0.45);
// tiny fake road
ctx.fillStyle = hsl(0,0,.2).toString();
fillQuad(ctx, w*.40, h, w*.46, h*.58, w*.54, h*.58, w*.60, h);
// parked car
drawPlayerCar(ctx, w*0.5, h*0.82, 1);
}
}
///////////////////////////////////////////////////////////////////////////////
function gameRenderPost()
{
const w = mainCanvasSize.x;
const h = mainCanvasSize.y;
if (state === 'play')
{
const mph = (speed / MAX_SPEED * 230) | 0;
const t = max(0, timeLeftFrames) / 60;
drawTextScreen(`SPEED ${mph} mph`, vec2(14, 18), 28, hsl(0,0,1), 4, hsl(0,0,0), 'left', 'monospace');
drawTextScreen(`TIME ${formatTime(t)}`, vec2(14, 48), 28, hsl(0,0,1), 4, hsl(0,0,0), 'left', 'monospace');
drawTextScreen(`LAP ${lap}`, vec2(14, 78), 28, hsl(0,0,1), 4, hsl(0,0,0), 'left', 'monospace');
drawTextScreen(`SCORE ${score|0}`, vec2(w-14, 18), 28, hsl(0,0,1), 4, hsl(0,0,0), 'right', 'monospace');
// small hints
drawTextScreen('ARROWS/WASD = drive', vec2(w-14, h-52), 20, hsl(0,0,1,.85), 3, hsl(0,0,0,.8), 'right', 'monospace');
drawTextScreen('Stay on the asphalt!', vec2(w-14, h-28), 20, hsl(0,0,1,.85), 3, hsl(0,0,0,.8), 'right', 'monospace');
}
else if (state === 'title')
{
drawTextScreen('POLE POSITION (tiny)', vec2(w/2, h*0.20), 70, hsl(.02,.9,.55), 8, hsl(0,0,0), 'center', 'monospace');
drawTextScreen('PRESS ENTER / SPACE', vec2(w/2, h*0.30), 34, hsl(0,0,1), 6, hsl(0,0,0), 'center', 'monospace');
drawTextScreen('ARROWS/WASD TO DRIVE', vec2(w/2, h*0.36), 24, hsl(0,0,1,.9), 4, hsl(0,0,0,.85), 'center', 'monospace');
drawTextScreen('PASS CARS • DON\'T GO OFFROAD', vec2(w/2, h*0.40), 22, hsl(0,0,1,.9), 4, hsl(0,0,0,.85), 'center', 'monospace');
}
else if (state === 'timeup')
{
drawTextScreen('TIME UP!', vec2(w/2, h*0.22), 84, hsl(0,0,1), 10, hsl(0,0,0), 'center', 'monospace');
drawTextScreen(`FINAL SCORE ${score|0}`, vec2(w/2, h*0.34), 38, hsl(.02,.9,.55), 6, hsl(0,0,0), 'center', 'monospace');
drawTextScreen('PRESS ENTER / SPACE TO TRY AGAIN', vec2(w/2, h*0.42), 26, hsl(0,0,1,.9), 5, hsl(0,0,0,.85), 'center', 'monospace');
}
}
///////////////////////////////////////////////////////////////////////////////
// Startup LittleJS Engine
engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost);
</script>