-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasketball.html
More file actions
596 lines (514 loc) · 22.6 KB
/
Copy pathbasketball.html
File metadata and controls
596 lines (514 loc) · 22.6 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
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover">
<title>DIY 籃球機計分系統</title>
<style>
* { box-sizing: border-box; touch-action: manipulation; }
body {
margin: 0; padding: 0; background: #0a0a0f; color: #fff;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center;
min-height: 100vh; overflow: hidden;
}
#app-container {
position: relative; width: 100vw; height: 100vh;
background: #12121c; display: flex; flex-direction: column; overflow: hidden;
}
/* --- 直向模式 HUD --- */
#header {
padding: 10px; background: #1a1a2b; display: flex; justify-content: space-around; align-items: center;
border-bottom: 2px solid #2a2a40; z-index: 10; flex-shrink: 0;
}
.hud-title { font-size: 0.75rem; color: #8a8aa0; text-transform: uppercase; }
.hud-value { font-size: 1.6rem; font-weight: 800; color: #00ffcc; text-shadow: 0 0 10px rgba(0,255,204,0.5); }
.hud-score { color: #ff0055; text-shadow: 0 0 10px rgba(255,0,85,0.5); }
.btn-quit {
background: #3a2233; color: #ff5588; border: 1px solid #ff0055;
padding: 6px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: bold; cursor: pointer;
}
/* --- 攝影機畫面區 --- */
#viewfinder {
position: relative; flex: 1; width: 100%; height: 100%; background: #000; overflow: hidden;
display: flex; align-items: center; justify-content: center; z-index: 1;
}
video, canvas { position: absolute; width: 100%; height: 100%; object-fit: cover; }
.mirror { transform: scaleX(-1); }
/* --- 偵測框 ROI --- */
#roi-box {
position: absolute; border: 3px dashed #00ffcc; box-shadow: 0 0 15px rgba(0,255,204,0.4);
background: rgba(0, 255, 204, 0.15); cursor: move;
z-index: 30; display: flex; align-items: center; justify-content: center;
touch-action: none;
}
#roi-box::after {
content: "對準籃框入口"; font-size: 11px; color: #fff; background: rgba(0,0,0,0.6);
padding: 2px 5px; border-radius: 4px; pointer-events: none;
}
.resize-handle {
position: absolute; width: 26px; height: 26px; background: #00ffcc;
bottom: -13px; right: -13px; border-radius: 50%; cursor: se-resize;
border: 3px solid #000; z-index: 31;
}
/* --- 橫向模式 --- */
@media (orientation: landscape) {
#app-container { flex-direction: row; }
#header {
flex-direction: column; width: 160px; height: 100%;
border-bottom: none; border-right: 2px solid #2a2a40; justify-content: space-evenly;
padding: 15px 5px;
}
.hud-value { font-size: 1.8rem; }
}
/* --- 浮層選單 UI (關鍵修正:移除 backdrop-filter 防止背景 video 渲染被凍結) --- */
.overlay-screen {
position: absolute; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(18, 18, 28, 0.96); /* 使用高不透明度替代 blur */
z-index: 20; display: flex; flex-direction: column; padding: 20px;
overflow-y: auto; justify-content: center; align-items: center;
}
.hidden { display: none !important; }
h2 { font-size: 1.5rem; margin-top: 0; margin-bottom: 12px; color: #ff0055; letter-spacing: 1px; }
.form-grid {
display: grid; grid-template-columns: 1fr; gap: 10px; width: 100%; max-width: 360px; text-align: left;
}
@media (orientation: landscape) {
.form-grid { grid-template-columns: 1fr 1fr; max-width: 560px; }
}
.form-group { width: 100%; }
label { display: block; font-size: 0.8rem; color: #aaa; margin-bottom: 4px; }
input, select {
width: 100%; padding: 8px 12px; background: #222235; border: 1px solid #3a3a55;
border-radius: 8px; color: #fff; font-size: 0.95rem; outline: none;
}
input:focus { border-color: #00ffcc; }
.btn {
width: 100%; max-width: 360px; padding: 12px; margin-top: 10px; background: linear-gradient(135deg, #ff0055, #ff5500);
border: none; border-radius: 10px; color: #fff; font-size: 1rem; font-weight: bold;
cursor: pointer; box-shadow: 0 4px 15px rgba(255,0,85,0.4);
}
.btn:active { transform: scale(0.98); }
.btn-secondary { background: #2a2a40; box-shadow: none; border: 1px solid #4a4a65; }
.btn-accent { background: linear-gradient(135deg, #00b894, #00cec9); box-shadow: 0 4px 15px rgba(0,206,201,0.3); }
#countdown-display {
font-size: 6rem; font-weight: 900; color: #00ffcc; text-shadow: 0 0 30px #00ffcc;
animation: pulse 0.8s infinite alternate;
}
@keyframes pulse { from { transform: scale(0.9); } to { transform: scale(1.1); } }
#align-hint {
position: absolute; top: 15px; left: 50%; transform: translateX(-50%);
background: rgba(0,0,0,0.75); border: 1px solid #00ffcc; padding: 8px 16px;
border-radius: 20px; color: #00ffcc; font-size: 0.85rem; z-index: 15; pointer-events: none;
}
.leaderboard-table { width: 100%; max-width: 360px; border-collapse: collapse; margin: 15px 0; }
.leaderboard-table th, .leaderboard-table td { padding: 8px; border-bottom: 1px solid #3a3a55; text-align: left; }
.leaderboard-table th { color: #8a8aa0; font-size: 0.8rem; }
.rank-1 { color: #ffd700; font-weight: bold; }
</style>
</head>
<body>
<div id="app-container">
<!-- 1. 遊戲實時 HUD -->
<div id="header">
<div>
<div class="hud-title">PLAYER</div>
<div class="hud-value" id="hud-player">Ryan</div>
</div>
<div>
<div class="hud-title">TIME</div>
<div class="hud-value" id="hud-time">60</div>
</div>
<div>
<div class="hud-title">SCORE</div>
<div class="hud-value hud-score" id="hud-score">0</div>
</div>
<button class="btn-quit" id="btn-early-finish">提前結束 🏁</button>
</div>
<!-- 2. 攝影機檢視與偵測區域 -->
<div id="viewfinder">
<video id="webcam" autoplay playsinline class="mirror"></video>
<canvas id="canvas" style="display:none;"></canvas>
<div id="align-hint" class="hidden">🎯 請拖曳與縮放綠框對準籃框入口</div>
<div id="roi-box" style="top: 35%; left: 35%; width: 130px; height: 80px;">
<div class="resize-handle" id="resize-handle"></div>
</div>
</div>
<!-- 3. 選單:遊戲設定畫面 -->
<div id="screen-setup" class="overlay-screen">
<h2>🏀 籃球機設定</h2>
<div class="form-grid">
<div class="form-group">
<label>相機控制</label>
<button class="btn btn-secondary" id="btn-toggle-cam" style="margin-top:0;">🔄 切換鏡頭</button>
</div>
<div class="form-group">
<label>偵測校準</label>
<button class="btn btn-accent" id="btn-align-roi" style="margin-top:0;">🎯 調整籃框偵測位置</button>
</div>
<div class="form-group">
<label for="select-time">比賽時間</label>
<select id="select-time">
<option value="30">30 秒</option>
<option value="60" selected>60 秒</option>
<option value="90">90 秒</option>
</select>
</div>
<div class="form-group">
<label for="select-players">玩家人數</label>
<select id="select-players">
<option value="1">1 位</option>
<option value="2" selected>2 位</option>
<option value="3">3 位</option>
<option value="4">4 位</option>
</select>
</div>
</div>
<div id="player-names-container" class="form-grid" style="margin-top: 10px;"></div>
<button class="btn" id="btn-start-game">開始遊戲 🏀</button>
</div>
<!-- 4. 校準模式確認按鈕工具列 -->
<div id="align-controls" class="hidden" style="position: absolute; bottom: 0; left: 0; width: 100%; height: 100px; background: linear-gradient(to top, rgba(0,0,0,0.8), transparent); z-index: 25; display: flex; justify-content: center; align-items: center; padding-bottom: 20px; pointer-events: none;">
<button class="btn btn-accent" id="btn-confirm-align" style="max-width: 280px; margin-top: 0; pointer-events: auto;">完成調整,返回選單 👍</button>
</div>
<!-- 5. 選單:準備 & 3-2-1 倒數畫面 -->
<div id="screen-countdown" class="overlay-screen hidden">
<div style="font-size: 1.4rem; color: #aaa;">準備好投籃!</div>
<div id="next-player-name" style="font-size: 2rem; font-weight: bold; margin: 10px 0; color: #fff;"></div>
<div id="countdown-display">3</div>
</div>
<!-- 6. 選單:單人結束 / 換人過場畫面 -->
<div id="screen-turn-result" class="overlay-screen hidden">
<h2 style="color: #00ffcc;">時間到!</h2>
<div id="turn-summary-text" style="font-size: 1.2rem; margin-bottom: 20px;"></div>
<button class="btn" id="btn-next-turn">換下一位玩家 ➡️</button>
</div>
<!-- 7. 選單:總排行榜 -->
<div id="screen-leaderboard" class="overlay-screen hidden">
<h2>🏆 最終排行榜</h2>
<table class="leaderboard-table">
<thead>
<tr><th>名次</th><th>玩家</th><th>得分</th></tr>
</thead>
<tbody id="leaderboard-body"></tbody>
</table>
<button class="btn" id="btn-restart">再玩一次 🔄</button>
</div>
</div>
<script>
const DEFAULT_NAMES = ["Ryan", "Asher", "Jen", "Ellis"];
let facingMode = "user";
let currentStream = null;
let gameTimeLimit = 60;
let players = [];
let currentPlayerIndex = 0;
let scores = {};
let isPlaying = false;
let currentScore = 0;
let timeLeft = 0;
let gameTimer = null;
let isCooldown = false;
let prevFrameData = null;
const video = document.getElementById('webcam');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const roiBox = document.getElementById('roi-box');
const selectPlayers = document.getElementById('select-players');
const playerNamesContainer = document.getElementById('player-names-container');
// --- 1. 相機初始化與切換 ---
async function initCamera() {
if (currentStream) {
currentStream.getTracks().forEach(track => track.stop());
}
try {
currentStream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: facingMode, width: { ideal: 640 }, height: { ideal: 480 } },
audio: false
});
video.srcObject = currentStream;
await video.play();
if (facingMode === "user") {
video.classList.add('mirror');
} else {
video.classList.remove('mirror');
}
} catch (err) {
alert("無法讀取鏡頭,請確認存取權限!");
}
}
document.getElementById('btn-toggle-cam').addEventListener('click', () => {
facingMode = (facingMode === "user") ? "environment" : "user";
initCamera();
});
// --- 2. 獨立調整籃框區域 ---
document.getElementById('btn-align-roi').addEventListener('click', () => {
document.getElementById('screen-setup').classList.add('hidden');
document.getElementById('align-hint').classList.remove('hidden');
const controls = document.getElementById('align-controls');
controls.classList.remove('hidden');
controls.style.display = 'flex';
});
document.getElementById('btn-confirm-align').addEventListener('click', () => {
document.getElementById('align-hint').classList.add('hidden');
const controls = document.getElementById('align-controls');
controls.classList.add('hidden');
controls.style.display = 'none';
document.getElementById('screen-setup').classList.remove('hidden');
});
// --- 3. 玩家動態介面 ---
function renderPlayerInputs() {
const count = parseInt(selectPlayers.value);
playerNamesContainer.innerHTML = '';
for (let i = 0; i < count; i++) {
const div = document.createElement('div');
div.className = 'form-group';
div.innerHTML = `
<label>玩家 ${i + 1} 名字</label>
<input type="text" id="input-player-${i}" value="${DEFAULT_NAMES[i] || 'Player ' + (i+1)}">
`;
playerNamesContainer.appendChild(div);
}
}
selectPlayers.addEventListener('change', renderPlayerInputs);
renderPlayerInputs();
// --- 4. 手動拖曳與縮放 ROI 綠框 ---
let isDragging = false, isResizing = false;
let startX, startY, startW, startH, startLeft, startTop;
roiBox.addEventListener('mousedown', handlePointerDown);
roiBox.addEventListener('touchstart', handlePointerDown, { passive: false });
function handlePointerDown(e) {
if (e.type === 'touchstart') e.preventDefault();
const p = e.touches ? e.touches[0] : e;
if (e.target.id === 'resize-handle') {
isResizing = true;
isDragging = false;
startW = roiBox.offsetWidth;
startH = roiBox.offsetHeight;
} else {
isDragging = true;
isResizing = false;
startLeft = roiBox.offsetLeft;
startTop = roiBox.offsetTop;
}
startX = p.clientX;
startY = p.clientY;
if (e.type === 'touchstart') {
window.addEventListener('touchmove', handlePointerMove, { passive: false });
window.addEventListener('touchend', handlePointerUp);
} else {
window.addEventListener('mousemove', handlePointerMove);
window.addEventListener('mouseup', handlePointerUp);
}
}
function handlePointerMove(e) {
if (!isDragging && !isResizing) return;
if (e.type === 'touchmove') e.preventDefault();
const p = e.touches ? e.touches[0] : e;
const dx = p.clientX - startX;
const dy = p.clientY - startY;
if (isResizing) {
roiBox.style.width = Math.max(60, startW + dx) + 'px';
roiBox.style.height = Math.max(40, startH + dy) + 'px';
} else if (isDragging) {
roiBox.style.left = (startLeft + dx) + 'px';
roiBox.style.top = (startTop + dy) + 'px';
}
}
function handlePointerUp(e) {
isDragging = false;
isResizing = false;
window.removeEventListener('touchmove', handlePointerMove);
window.removeEventListener('mousemove', handlePointerMove);
window.removeEventListener('touchend', handlePointerUp);
window.removeEventListener('mouseup', handlePointerUp);
}
// --- 5. Web Audio 音效 ---
function playSound(type) {
try {
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.connect(gain);
gain.connect(audioCtx.destination);
if (type === 'goal') {
osc.type = 'sine';
osc.frequency.setValueAtTime(587.33, audioCtx.currentTime);
osc.frequency.exponentialRampToValueAtTime(880, audioCtx.currentTime + 0.15);
gain.gain.setValueAtTime(0.3, audioCtx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.15);
osc.start(); osc.stop(audioCtx.currentTime + 0.15);
} else if (type === 'beep') {
osc.type = 'triangle';
osc.frequency.setValueAtTime(440, audioCtx.currentTime);
gain.gain.setValueAtTime(0.2, audioCtx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.1);
osc.start(); osc.stop(audioCtx.currentTime + 0.1);
} else if (type === 'end') {
osc.type = 'square';
osc.frequency.setValueAtTime(220, audioCtx.currentTime);
gain.gain.setValueAtTime(0.3, audioCtx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.5);
osc.start(); osc.stop(audioCtx.currentTime + 0.5);
}
} catch (e) {}
}
// --- 6. 遊戲流程控制 ---
document.getElementById('btn-start-game').addEventListener('click', () => {
const count = parseInt(selectPlayers.value);
players = [];
for (let i = 0; i < count; i++) {
const name = document.getElementById(`input-player-${i}`).value.trim();
players.push(name || `Player ${i+1}`);
}
gameTimeLimit = parseInt(document.getElementById('select-time').value);
currentPlayerIndex = 0;
scores = {};
document.getElementById('screen-setup').classList.add('hidden');
startTurnCountdown();
});
function startTurnCountdown() {
const name = players[currentPlayerIndex];
document.getElementById('screen-turn-result').classList.add('hidden');
document.getElementById('screen-countdown').classList.remove('hidden');
document.getElementById('next-player-name').innerText = `輪到 ${name}!`;
let count = 3;
const countEl = document.getElementById('countdown-display');
countEl.innerText = count;
playSound('beep');
const timer = setInterval(() => {
count--;
if (count > 0) {
countEl.innerText = count;
playSound('beep');
} else {
clearInterval(timer);
document.getElementById('screen-countdown').classList.add('hidden');
startPlaying();
}
}, 1000);
}
function startPlaying() {
// 關鍵修復:重新喚醒影片播放(防止行動裝置選單遮罩凍結影片)
if (video.paused) {
video.play().catch(e => console.log(e));
}
// 重置當前玩家狀態
prevFrameData = null;
isCooldown = false;
roiBox.style.borderColor = '#00ffcc';
isPlaying = true;
currentScore = 0;
timeLeft = gameTimeLimit;
document.getElementById('hud-player').innerText = players[currentPlayerIndex];
document.getElementById('hud-time').innerText = timeLeft;
document.getElementById('hud-score').innerText = currentScore;
if (gameTimer) clearInterval(gameTimer);
gameTimer = setInterval(() => {
timeLeft--;
document.getElementById('hud-time').innerText = timeLeft;
if (timeLeft <= 0) {
endTurn();
}
}, 1000);
}
document.getElementById('btn-early-finish').addEventListener('click', () => {
if (isPlaying && confirm("確定要提前結束目前玩家的投籃嗎?")) {
endTurn();
}
});
function endTurn() {
isPlaying = false;
clearInterval(gameTimer);
playSound('end');
const name = players[currentPlayerIndex];
scores[name] = currentScore;
if (currentPlayerIndex < players.length - 1) {
document.getElementById('turn-summary-text').innerText = `${name} 獲得 ${currentScore} 分!`;
document.getElementById('btn-next-turn').innerText = `換下一位:${players[currentPlayerIndex + 1]} 準備`;
document.getElementById('screen-turn-result').classList.remove('hidden');
} else {
showLeaderboard();
}
}
document.getElementById('btn-next-turn').addEventListener('click', () => {
currentPlayerIndex++;
startTurnCountdown();
});
function showLeaderboard() {
document.getElementById('screen-turn-result').classList.add('hidden');
document.getElementById('screen-leaderboard').classList.remove('hidden');
const sorted = Object.keys(scores)
.map(name => ({ name, score: scores[name] }))
.sort((a, b) => b.score - a.score);
const tbody = document.getElementById('leaderboard-body');
tbody.innerHTML = '';
sorted.forEach((item, index) => {
const tr = document.createElement('tr');
if (index === 0) tr.className = 'rank-1';
tr.innerHTML = `
<td>${index === 0 ? '👑 1' : index + 1}</td>
<td>${item.name}</td>
<td>${item.score}</td>
`;
tbody.appendChild(tr);
});
}
document.getElementById('btn-restart').addEventListener('click', () => {
document.getElementById('screen-leaderboard').classList.add('hidden');
document.getElementById('screen-setup').classList.remove('hidden');
});
// --- 7. 影像動態偵測 (ROI) ---
function processFrame() {
try {
// 只有在遊戲進行中才執行動態比對與畫面處置
if (isPlaying && video.readyState === video.HAVE_ENOUGH_DATA) {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const viewRect = video.getBoundingClientRect();
if (viewRect.width > 0 && viewRect.height > 0) {
const scaleX = video.videoWidth / viewRect.width;
const scaleY = video.videoHeight / viewRect.height;
const roiRect = roiBox.getBoundingClientRect();
let rx = Math.max(0, (roiRect.left - viewRect.left) * scaleX);
let ry = Math.max(0, (roiRect.top - viewRect.top) * scaleY);
let rw = Math.min(canvas.width - rx, roiRect.width * scaleX);
let rh = Math.min(canvas.height - ry, roiRect.height * scaleY);
if (rw > 5 && rh > 5) {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const currentFrame = ctx.getImageData(rx, ry, rw, rh);
if (prevFrameData && prevFrameData.data.length === currentFrame.data.length && !isCooldown) {
let diff = 0;
const len = currentFrame.data.length;
for (let i = 0; i < len; i += 4) {
const rD = Math.abs(currentFrame.data[i] - prevFrameData.data[i]);
const gD = Math.abs(currentFrame.data[i+1] - prevFrameData.data[i+1]);
const bD = Math.abs(currentFrame.data[i+2] - prevFrameData.data[i+2]);
if (rD + gD + bD > 90) diff++;
}
if (diff > (rw * rh * 0.08)) {
currentScore += 2;
document.getElementById('hud-score').innerText = currentScore;
playSound('goal');
isCooldown = true;
roiBox.style.borderColor = '#ff0055';
setTimeout(() => {
isCooldown = false;
roiBox.style.borderColor = '#00ffcc';
}, 900);
}
}
prevFrameData = currentFrame;
}
}
}
} catch (err) {
console.error("Frame processing error:", err);
}
requestAnimationFrame(processFrame);
}
initCamera().then(() => {
requestAnimationFrame(processFrame);
});
</script>
</body>
</html>