# ===== CodeLab: JavaScript 小游戏⑦:打砖块网页版 ===== # 来源: https://aoerliang.dpdns.org/articles/game-js-breakout # 以下代码片段按文章出现顺序拼接, 共 3 段 # ----- 片段 1 (javascript) ----- const cv = document.getElementById('cv'); const ctx = cv.getContext('2d'); const W = 640, H = 480; let px = (W - 100) / 2; let ball = { x: W / 2, y: H - 40, vx: 4, vy: -5, r: 8 }; cv.addEventListener('mousemove', e => { const rect = cv.getBoundingClientRect(); px = e.clientX - rect.left - 50; if (px < 0) px = 0; if (px > W - 100) px = W - 100; }); function loop() { moveBall(); hitTest(); draw(); requestAnimationFrame(loop); } # ----- 片段 2 (javascript) ----- function moveBall() { ball.x += ball.vx; ball.y += ball.vy; if (ball.x < ball.r || ball.x > W - ball.r) ball.vx = -ball.vx; if (ball.y < ball.r) ball.vy = -ball.vy; if (ball.vy > 0 && ball.y + ball.r >= H - 14 && ball.x >= px && ball.x <= px + 100) { const off = (ball.x - (px + 50)) / 50; const sp = Math.hypot(ball.vx, ball.vy); ball.vx = sp * off * 0.8; ball.vy = -Math.sqrt(Math.max(sp * sp - ball.vx * ball.vx, 0.01)); } } function hitTest() { for (let i = 0; i < bricks.length; i++) { const b = bricks[i]; if (ball.x + ball.r > b.x && ball.x - ball.r < b.x + b.w && ball.y + ball.r > b.y && ball.y - ball.r < b.y + b.h) { ball.vy = -ball.vy; bricks.splice(i, 1); score += 10; i--; } } } # ----- 片段 3 (html) -----