實現生命值相當直接。讓我們首先在宣告其他變數的地方新增一個變數來儲存生命的數量。
繪製生命計數器看起來與繪製得分計數器幾乎相同——在程式碼中的 drawScore() 函式下方新增以下函式。
function drawLives() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText(`Lives: ${lives}`, canvas.width - 65, 20);
}
與其立即結束遊戲,不如在生命值用完之前減少生命的數量。當玩家開始下一條生命時,我們還可以重置球和擋板的位置。因此,在 draw() 函式中,用以下三行替換
alert("GAME OVER");
document.location.reload();
clearInterval(interval); // Needed for Chrome to end game
透過這一點,我們可以為其新增稍微複雜一些的邏輯,如下所示:
lives--;
if (!lives) {
alert("GAME OVER");
document.location.reload();
clearInterval(interval); // Needed for Chrome to end game
} else {
x = canvas.width / 2;
y = canvas.height - 30;
dx = 2;
dy = -2;
paddleX = (canvas.width - paddleWidth) / 2;
}
現在,當球擊中螢幕底部邊緣時,我們會從 lives 變數中減去一條生命。如果沒有剩餘生命,遊戲就失敗了;如果還有剩餘生命,則重置球和擋板的位置,並隨之重置球的移動。
現在您需要在 draw() 函式中呼叫 drawLives(),並將其放在 drawScore() 呼叫下方。
現在讓我們處理一些與遊戲機制無關,但與遊戲渲染方式相關的內容。 requestAnimationFrame() 幫助瀏覽器比我們目前使用 setInterval() 實現的固定幀率更好地渲染遊戲。替換以下行
interval = setInterval(draw, 10);
with
並刪除所有出現的
clearInterval(interval); // Needed for Chrome to end game
然後,在 draw() 函式的最底部(就在閉合花括號之前),新增以下行,這會導致 draw() 函式一遍又一遍地呼叫自身:
requestAnimationFrame(draw);
draw() 函式現在在一個 requestAnimationFrame() 迴圈中一遍又一遍地執行,但我們不再使用固定的 10 毫秒幀率,而是將幀率控制權交還給瀏覽器。它將相應地同步幀率,並僅在需要時渲染形狀。這比舊的 setInterval() 方法產生了更高效、更流暢的動畫迴圈。
就是這樣——遊戲的最終版本已經準備就緒,可以開始使用了!
<canvas id="myCanvas" width="480" height="320"></canvas>
<button id="runButton">Start game</button>
canvas {
background: #eeeeee;
}
button {
display: block;
}
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const ballRadius = 10;
let x = canvas.width / 2;
let y = canvas.height - 30;
let dx = 2;
let dy = -2;
const paddleHeight = 10;
const paddleWidth = 75;
let paddleX = (canvas.width - paddleWidth) / 2;
let rightPressed = false;
let leftPressed = false;
const brickRowCount = 5;
const brickColumnCount = 3;
const brickWidth = 75;
const brickHeight = 20;
const brickPadding = 10;
const brickOffsetTop = 30;
const brickOffsetLeft = 30;
let score = 0;
let lives = 3;
let bricks = [];
for (let c = 0; c < brickColumnCount; c++) {
bricks[c] = [];
for (let r = 0; r < brickRowCount; r++) {
bricks[c][r] = { x: 0, y: 0, status: 1 };
}
}
document.addEventListener("keydown", keyDownHandler);
document.addEventListener("keyup", keyUpHandler);
document.addEventListener("mousemove", mouseMoveHandler);
function keyDownHandler(e) {
if (e.key === "Right" || e.key === "ArrowRight") {
rightPressed = true;
} else if (e.key === "Left" || e.key === "ArrowLeft") {
leftPressed = true;
}
}
function keyUpHandler(e) {
if (e.key === "Right" || e.key === "ArrowRight") {
rightPressed = false;
} else if (e.key === "Left" || e.key === "ArrowLeft") {
leftPressed = false;
}
}
function mouseMoveHandler(e) {
let relativeX = e.clientX - canvas.offsetLeft;
if (relativeX > 0 && relativeX < canvas.width) {
paddleX = relativeX - paddleWidth / 2;
}
}
function collisionDetection() {
for (let c = 0; c < brickColumnCount; c++) {
for (let r = 0; r < brickRowCount; r++) {
let b = bricks[c][r];
if (b.status === 1) {
if (
x > b.x &&
x < b.x + brickWidth &&
y > b.y &&
y < b.y + brickHeight
) {
dy = -dy;
b.status = 0;
score++;
if (score === brickRowCount * brickColumnCount) {
alert("YOU WIN, CONGRATS!");
document.location.reload();
}
}
}
}
}
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function drawBricks() {
for (let c = 0; c < brickColumnCount; c++) {
for (let r = 0; r < brickRowCount; r++) {
if (bricks[c][r].status === 1) {
const brickX = r * (brickWidth + brickPadding) + brickOffsetLeft;
const brickY = c * (brickHeight + brickPadding) + brickOffsetTop;
bricks[c][r].x = brickX;
bricks[c][r].y = brickY;
ctx.beginPath();
ctx.rect(brickX, brickY, brickWidth, brickHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
}
}
}
function drawScore() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText(`Score: ${score}`, 8, 20);
}
function drawLives() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText(`Lives: ${lives}`, canvas.width - 65, 20);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBricks();
drawBall();
drawPaddle();
drawScore();
drawLives();
collisionDetection();
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if (y + dy < ballRadius) {
dy = -dy;
} else if (y + dy > canvas.height - ballRadius) {
if (x > paddleX && x < paddleX + paddleWidth) {
dy = -dy;
} else {
lives--;
if (!lives) {
alert("GAME OVER");
document.location.reload();
} else {
x = canvas.width / 2;
y = canvas.height - 30;
dx = 3;
dy = -3;
paddleX = (canvas.width - paddleWidth) / 2;
}
}
}
if (rightPressed && paddleX < canvas.width - paddleWidth) {
paddleX += 7;
} else if (leftPressed && paddleX > 0) {
paddleX -= 7;
}
x += dx;
y += dy;
requestAnimationFrame(draw);
}
const runButton = document.getElementById("runButton");
runButton.addEventListener("click", () => {
draw();
runButton.disabled = true;
});
您已經完成了所有課程——恭喜!至此,您應該已經掌握了 Canvas 操作的基礎知識和 2D 遊戲的邏輯。現在是學習一些框架並繼續遊戲開發的絕佳時機。您可以檢視本系列配套的 使用 Phaser 進行 2D 彈球遊戲 或 使用 Phaser 構建的 Cyber Orb 教程。您還可以檢視 MDN 上的 遊戲部分 以獲取靈感和更多知識。
您也可以返回 本教程系列的索引頁。祝您編碼愉快!