-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
705 lines (605 loc) · 21.3 KB
/
index.html
File metadata and controls
705 lines (605 loc) · 21.3 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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>DanglePro Minigame Widget</title>
<link href="https://fonts.googleapis.com/css2?family=Oswald:wght@400;500;700&display=swap" rel="stylesheet">
<style>
:root {
--w: 440px;
/* base artwork width */
--h: 956px;
/* base artwork height */
--controlH: 270px;
/* white control zone height */
--laneTopY: 300px;
/* where objects appear (approx garage door) */
--laneBotY: 820px;
/* where objects exit / collide */
}
* {
box-sizing: border-box;
}
html,
body {
width: max-content;
}
body {
margin: 0;
font-family: 'Oswald', sans-serif;
overscroll-behavior: none;
overflow: hidden;
}
.dp-wrap {
position: relative;
width: 100vw;
aspect-ratio: 440/956;
user-select: none;
-webkit-user-select: none;
touch-action: none;
/* we handle touch ourselves */
padding-bottom: env(safe-area-inset-bottom, 0);
}
canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
}
.hud {
position: absolute;
inset: 0;
pointer-events: none;
display: flex;
align-items: flex-start;
justify-content: space-between;
padding: 14px 18px max(14px, env(safe-area-inset-right, 0)) max(18px, env(safe-area-inset-left, 0));
color: #000;
font-weight: 900;
letter-spacing: 1px;
text-shadow: 0 1px 0 #fff, 0 -1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff;
}
.hud .score {
font-size: 32px;
display: flex;
width: 100%;
align-items: center;
justify-content: space-between;
}
.hud .score .num {
color: #c81818;
}
.startBtn,
.restartBtn {
position: absolute;
left: 50%;
transform: translateX(-50%);
bottom: calc(var(--controlH) + 28px);
padding: 14px 22px;
border-radius: 999px;
border: none;
cursor: pointer;
font-weight: 800;
font-size: 16px;
letter-spacing: .4px;
background: #111;
color: #fff;
box-shadow: 0 8px 20px rgba(0, 0, 0, .35);
}
.restartBtn {
display: none;
}
.controlZone {
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: calc(var(--controlH) + env(safe-area-inset-bottom, 0));
padding-bottom: env(safe-area-inset-bottom, 0);
background: #fff;
opacity: 0;
border-top: 4px solid #e9e9e9;
display: grid;
place-items: center;
}
.gameover {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, .58);
display: none;
align-items: center;
justify-content: center;
text-align: center;
color: #fff;
padding: 24px;
padding-bottom: calc(24px + env(safe-area-inset-bottom, 0));
}
.gameover .card {
background: rgba(0, 0, 0, .65);
border: 1px solid rgba(255, 255, 255, .15);
border-radius: 18px;
padding: 20px 22px;
width: min(90%, 360px);
box-shadow: 0 20px 60px rgba(0, 0, 0, .5);
}
.gameover h2 {
margin: 0 0 6px;
font-size: 24px;
}
.gameover p {
margin: 0 0 14px;
opacity: .9;
}
.gameover .restartBtn {
display: inline-block;
position: static;
transform: none;
margin-top: 6px;
}
/* Hide default outline on buttons but keep focus visible for a11y */
.startBtn:focus-visible,
.restartBtn:focus-visible {
outline: 3px solid #3ea7ff;
outline-offset: 3px;
}
.startBtn,
.restartBtn {
bottom: calc(var(--controlH) + env(safe-area-inset-bottom, 0) + 28px);
}
</style>
</head>
<body>
<div class="dp-wrap" id="dp">
<canvas id="dp-canvas" width="440" height="956" aria-label="DanglePro Minigame"></canvas>
<div class="hud">
<div class="score">SCORE: <span class="num" id="dp-score">0</span></div>
</div>
<!-- <button class="startBtn" id="dp-start">START THE GAME</button> -->
<div class="gameover" id="dp-over" role="dialog" aria-modal="true" aria-labelledby="dp-over-title">
<div class="card">
<h2 id="dp-over-title">Game Over</h2>
<p>Your score: <strong id="dp-over-score">0</strong></p>
<button class="restartBtn" id="dp-restart">Play again</button>
</div>
</div>
<div class="controlZone" id="dp-zone" aria-label="Control zone. Drag or use arrow keys.">
</div>
</div>
<script>
(() => {
/* ================= CONFIG ================= */
const ASSETS_BASE = "./"; // change if images live elsewhere
const ART = {
scene: "scene_bg.jpg",
stick: "stick.png",
objects: [
"object_1.webp",
"object_2.png",
"object_3.webp",
"object_4.png",
"object_5.png",
"object_6.webp",
"object_7.png",
"object_8.webp",
"object_9.png",
]
};
const OBJECT_POINTS = {
"object_1.webp": 5,
"object_2.png": 3,
"object_3.webp": 2,
"object_4.png": 4,
"object_5.png": 1,
"object_6.webp": 7,
"object_7.png": 6,
"object_8.webp": 8,
"object_9.png": 9,
};
const SFX = {
hit: new Audio(ASSETS_BASE + "failure.wav"),
pass: new Audio(ASSETS_BASE + "success.wav"),
};
const DIM = { w: 440, h: 956 };
const LANE_TOP_Y = 520; // spawn Y (matches artwork perspective)
const LANE_BOT_Y = 870; // exit/collision Y
const CONTROL_H = 270;
const LIVES = 1; // one life by spec
const BASE_SPAWN_EVERY = 800; // ms
const BASE_SPEED = 100; // px/sec at start (will scale per lane and difficulty)
const SPEED_GROWTH_PER_SEC = 2; // progressive difficulty (added to base each second)
const LANE_COUNT = 6;
const PLAY_BOUNDS = { left: 45, right: DIM.w - 45 };
const DEBUG = { collisions: false, lanes: false };
// прямоугольный хитбокс у клюшки
const STICK_HITBOX = {
w: 40, // ширина прямоугольника
h: 70 // высота прямоугольника
};
const OBJ_HITBOX_TIGHTNESS_X = 0.70;
const OBJ_HITBOX_TIGHTNESS_Y = 0.70;
const OBJ_SCALE = 0.65;
/* ========================================== */
// "пробный" немой старт — браузеры быстрее создают аудиопотоки
SFX.hit.muted = true; SFX.hit.play().finally(() => { SFX.hit.pause(); SFX.hit.currentTime = 0; SFX.hit.muted = false; });
SFX.pass.muted = true; SFX.pass.play().finally(() => { SFX.pass.pause(); SFX.pass.currentTime = 0; SFX.pass.muted = false; });
const wrap = document.getElementById("dp");
const cvs = document.getElementById("dp-canvas");
const ctx = cvs.getContext("2d");
const zone = document.getElementById("dp-zone");
// const startBtn = document.getElementById("dp-start");
const overPane = document.getElementById("dp-over");
const overScore = document.getElementById("dp-over-score");
const restartBtn = document.getElementById("dp-restart");
const scoreEl = document.getElementById("dp-score");
let images = {};
let running = false;
let startedAt = 0;
let lastTs = 0;
let score = 0;
let lives = LIVES;
const lanes = makeLanes();
const objects = []; // active obstacles
// Puck / stick control
const stick = {
img: null, // loaded later
// mounted near bottom; we allow horizontal move in [margin, w-margin]
x: DIM.w / 2,
y: LANE_BOT_Y - 100,
angle: -0.08, // slight tilt
puckOffset: { x: -20, y: 20 }, // where puck is relative to stick tip (visual tweak)
width: 52, // drawn image width (autoscaled by image ratio)
height: 116,
puckRadius: 22, // collision radius scaled with perspective-ish
};
// External scoring hook (override in host)
window.onDPScore = window.onDPScore || function (score) {
console.debug("[DP] Score submitted:", score);
window.parent.postMessage(
{ type: "DP_SCORE", score },
'*'
);
};
window.addEventListener('message', (e) => {
if (!e.data || e.data.type !== "DP_START_GAME") return;
if (!running) startGame();
});
function playSfx(name, { volume = 0.5, rate = 1 } = {}) {
const src = SFX[name];
if (!src) return;
const a = src.cloneNode(); // независимый экземпляр
a.volume = volume;
a.playbackRate = rate;
a.play().catch(() => { });
}
function loadImage(src) {
return new Promise((resolve, reject) => {
const im = new Image();
im.onload = () => resolve(im);
im.onerror = reject;
im.src = ASSETS_BASE + src;
});
}
async function loadAssets() {
const [scene, stickImg, ...objImgs] = await Promise.all([
loadImage(ART.scene),
loadImage(ART.stick),
...ART.objects.map(loadImage),
]);
images.scene = scene;
images.stick = stickImg;
images.objects = objImgs;
stick.img = stickImg;
}
// Define six perspective lanes by start/end XY.
// Start (top) is slightly more centered due to perspective narrowing.
function makeLanes() {
// верхние точки (ближе к центру)
const topXs = [135, 170, 205, 240, 275, 305];
// нижние точки (также ближе)
const botXs = [40, 110, 175, 245, 315, 390];
const lanes = [];
for (let i = 0; i < LANE_COUNT; i++) {
lanes.push({
i,
top: { x: topXs[i], y: LANE_TOP_Y },
bot: { x: botXs[i], y: LANE_BOT_Y },
mult: 0.9 + Math.random() * 0.3
});
}
return lanes;
}
function laneXY(lane, t) {
// t: 0..1 from top to bottom
return {
x: lane.top.x + (lane.bot.x - lane.top.x) * t,
y: lane.top.y + (lane.bot.y - lane.top.y) * t
};
}
function laneXYWithDrift(o, t) {
return laneXY(o.lane, t);
}
function spawnObject() {
const lane = lanes[Math.floor(Math.random() * LANE_COUNT)];
const idx = Math.floor(Math.random() * ART.objects.length);
const spriteName = ART.objects[idx];
const sprite = images.objects[idx];
const points = OBJECT_POINTS[spriteName] ?? 1;
// масштаб/скорость — как было
const startScale = 0.6 + Math.random() * 0.4; // если уже переходил на start/target
const targetScale = 1.0;
const secs = (performance.now() - startedAt) / 1000;
const progressive = BASE_SPEED + SPEED_GROWTH_PER_SEC * secs;
const pxPerSec = (progressive * lane.mult) * (0.85 + Math.random() * 0.3);
objects.push({
lane,
sprite,
points,
t: 0,
speed: pxPerSec,
startScale,
targetScale,
passed: false,
radius: 18,
});
}
function resetGame() {
score = 0;
lives = LIVES;
objects.length = 0;
scoreEl.textContent = "0";
overPane.style.display = "none";
}
function startGame() {
if (!images.scene) return; // not loaded yet
resetGame();
running = true;
startedAt = performance.now();
lastTs = startedAt;
// startBtn.style.display = "none";
loop();
scheduleSpawns();
}
function scheduleSpawns() {
if (!running) return;
// Decrease interval over time to raise difficulty a bit
const secs = (performance.now() - startedAt) / 1000;
const every = Math.max(350, BASE_SPAWN_EVERY - secs * 10);
spawnObject();
setTimeout(scheduleSpawns, every);
}
function endGame() {
running = false;
overScore.textContent = String(score);
overPane.style.display = "flex";
window.onDPScore(score); // report score
}
function loop(ts) {
if (!running) return;
requestAnimationFrame(loop);
const now = ts || performance.now();
const dt = Math.min(0.035, (now - lastTs) / 1000); // clamp delta
lastTs = now;
update(dt);
draw();
}
function update(dt) {
// Keyboard horizontal control easing already handled via handlers; nothing here
// Move objects
for (const o of objects) {
// advance 't' based on desired px/sec along lane vertical distance
const laneDist = (o.lane.bot.y - o.lane.top.y);
const tDelta = (o.speed * dt) / laneDist;
o.t += tDelta;
// update pass / score
if (!o.passed && o.t >= 1) {
o.passed = true;
score += o.points;
scoreEl.textContent = String(score);
playSfx("pass", { volume: 0.7 });
}
}
// Remove fully off-screen
for (let i = objects.length - 1; i >= 0; i--) {
if (objects[i].t > 1.2) objects.splice(i, 1);
}
// Collision (only if we still have life)
if (lives > 0) {
const stickHB = getStickHitbox();
for (const o of objects) {
if (o.t < 0 || o.t > 1.05) continue;
// Позиция и масштаб объекта на дорожке
const pos = laneXYWithDrift(o, o.t);
const interpScale = o.startScale + (o.targetScale - o.startScale) * o.t;
const depthScale = OBJ_SCALE + 0.9 * o.t;// как и при отрисовке
const scale = interpScale * depthScale;
// ВНИМАНИЕ: OBJ_SCALE — тот же коэффициент, что и в draw() при рисовании спрайта!
// Если там поменяешь — тут тоже обнови.
const drawW = o.sprite.width * scale * OBJ_SCALE;
const drawH = o.sprite.height * scale * OBJ_SCALE;
// «Подрезаем» хитбокс, чтобы был честнее, чем весь прямоугольник спрайта
const hitW = drawW * OBJ_HITBOX_TIGHTNESS_X;
const hitH = drawH * OBJ_HITBOX_TIGHTNESS_Y;
// Прямоугольник объекта (по центру спрайта)
const objHB = { x: pos.x - hitW / 2, y: pos.y - hitH / 2, w: hitW, h: hitH };
// (опционально для отладки)
o._debugRect = objHB;
if (rectsIntersect(stickHB, objHB)) {
playSfx("hit", { volume: 1 });
lives = 0;
endGame();
break;
}
}
}
}
function draw() {
// Scene
ctx.clearRect(0, 0, DIM.w, DIM.h);
ctx.drawImage(images.scene, 0, 0, DIM.w, DIM.h);
// Objects
for (const o of objects) {
const p = laneXYWithDrift(o, o.t);
const interpScale = o.startScale + (o.targetScale - o.startScale) * o.t;
const depthScale = OBJ_SCALE + 0.9 * o.t;// как и при отрисовке
const scale = interpScale * depthScale;
const w = o.sprite.width * scale * OBJ_SCALE;
const h = o.sprite.height * scale * OBJ_SCALE;
ctx.drawImage(o.sprite, p.x - w / 2, p.y - h / 2, w, h);
}
// Stick + puck
drawStickAndPuck();
if (DEBUG.collisions) {
drawStickHitboxDebug();
drawObjectsHitboxDebug()
}
if (DEBUG.lanes) {
// рисуем линии дорожек
ctx.save();
ctx.strokeStyle = "rgba(0,120,255,.35)";
ctx.setLineDash([6, 6]);
for (const l of lanes) {
ctx.beginPath();
ctx.moveTo(l.top.x, l.top.y);
ctx.lineTo(l.bot.x, l.bot.y);
ctx.stroke();
}
ctx.restore();
}
}
function drawStickHitboxDebug() {
const hb = getStickHitbox();
ctx.save();
ctx.lineWidth = 2;
ctx.strokeStyle = "rgba(30,110,255,0.9)"; // синий
ctx.strokeRect(hb.x, hb.y, hb.w, hb.h);
ctx.restore();
}
function drawObjectsHitboxDebug() {
ctx.save();
ctx.lineWidth = 2;
for (const o of objects) {
if (!o._debugRect) continue;
const r = o._debugRect;
ctx.strokeStyle = "rgba(40,200,90,0.8)"; // зелёный
ctx.strokeRect(r.x, r.y, r.w, r.h);
}
ctx.restore();
}
function drawStickAndPuck() {
const img = stick.img;
if (!img) return;
// Draw stick around its lower tip (right edge of the sprite), then compute puck
const drawW = stick.width;
const drawH = stick.height;
const tipX = stick.x;
const tipY = stick.y;
ctx.save();
ctx.translate(tipX, tipY);
ctx.rotate(stick.angle);
// image anchor so that tip is near right-bottom-ish of the sprite
const anchorX = drawW * 0.82;
const anchorY = drawH * 0.15;
ctx.drawImage(img, -anchorX, -anchorY, drawW, drawH);
ctx.restore();
// Puck (invisible sprite – we render as a simple dark circle; the stick image already shows one)
// But for precise collision we compute its center:
const puck = getStickHitbox();
// Optional: draw helper (kept invisible in prod)
// ctx.fillStyle = "rgba(0,0,0,.0001)"; ctx.beginPath(); ctx.arc(puck.x, puck.y, puck.r, 0, Math.PI*2); ctx.fill();
}
// Прямоугольник клюшки (ось-выравненный, без вращения)
function getStickHitbox() {
const x = stick.x;
const y = stick.y;
return {
x: x - STICK_HITBOX.w / 2 - 10,
y: y - STICK_HITBOX.h / 2 + 30,
w: STICK_HITBOX.w,
h: STICK_HITBOX.h,
};
}
// Проверка пересечения AABB
function rectsIntersect(a, b) {
return (
a.x < b.x + b.w &&
a.x + a.w > b.x &&
a.y < b.y + b.h &&
a.y + a.h > b.y
);
}
let lastMoveSfx = 0;
/* ----------- Controls: touch/mouse in control zone ----------- */
let dragging = false;
function clampStickX(x) {
return Math.max(PLAY_BOUNDS.left, Math.min(PLAY_BOUNDS.right, x));
}
function pointerToLocal(e) {
const rect = cvs.getBoundingClientRect();
const isTouch = e.touches && e.touches.length;
const clientX = isTouch ? e.touches[0].clientX : e.clientX;
const clientY = isTouch ? e.touches[0].clientY : e.clientY;
// Convert to canvas coordinates (440x956)
const x = (clientX - rect.left) * (DIM.w / rect.width);
const y = (clientY - rect.top) * (DIM.h / rect.height);
return { x, y };
}
zone.addEventListener("pointerdown", (e) => {
dragging = true;
zone.setPointerCapture(e.pointerId);
const p = pointerToLocal(e);
stick.x = clampStickX(p.x);
});
zone.addEventListener("pointermove", (e) => {
if (!dragging) return;
const p = pointerToLocal(e);
stick.x = clampStickX(p.x);
});
const stopDrag = (e) => { dragging = false; try { zone.releasePointerCapture(e.pointerId); } catch { } };
zone.addEventListener("pointerup", stopDrag);
zone.addEventListener("pointercancel", stopDrag);
/* ----------- Controls: keyboard arrows ----------- */
let keyDir = 0; // -1 left, +1 right
const KEY_SPEED = 460; // px/sec
window.addEventListener("keydown", (e) => {
if (e.key === "ArrowLeft") {
keyDir = -1; e.preventDefault();
playSfx("move", { volume: 0.5 });
}
if (e.key === "ArrowRight") {
keyDir = +1; e.preventDefault();
playSfx("move", { volume: 0.5 });
}
if (e.key.toLowerCase() === "c") DEBUG.collisions = !DEBUG.collisions;
if (e.key.toLowerCase() === "l") DEBUG.lanes = !DEBUG.lanes;
console.debug("[DP] Debug mode:", DEBUG);
});
window.addEventListener("keyup", (e) => {
if ((e.key === "ArrowLeft" && keyDir < 0) || (e.key === "ArrowRight" && keyDir > 0)) keyDir = 0;
});
// integrate keyboard movement into loop timing by hooking before update on each RAF
const _origUpdate = update;
update = function (dt) {
if (keyDir) {
stick.x = clampStickX(stick.x + keyDir * KEY_SPEED * dt);
}
_origUpdate(dt);
};
/* ---------------- UI buttons ----------------- */
// startBtn.addEventListener("click", startGame);
restartBtn.addEventListener("click", () => {
overPane.style.display = "none";
startGame();
});
/* -------------- Boot ---------------- */
loadAssets().then(() => {
draw(); // initial scene render
restartBtn.disabled = false;
}).catch(err => {
console.error("Failed to load assets", err);
});
})();
</script>
</body>
</html>